]> andersk Git - svn-all-fast-export.git/blob - src/svn.cpp
Fail if writing to the process fails
[svn-all-fast-export.git] / src / svn.cpp
1 /*
2  *  Copyright (C) 2007  Thiago Macieira <thiago@kde.org>
3  *
4  *  This program is free software: you can redistribute it and/or modify
5  *  it under the terms of the GNU General Public License as published by
6  *  the Free Software Foundation, either version 2 of the License, or
7  *  (at your option) any later version.
8  *
9  *  This program is distributed in the hope that it will be useful,
10  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *  GNU General Public License for more details.
13  *
14  *  You should have received a copy of the GNU General Public License
15  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Based on svn-fast-export by Chris Lee <clee@kde.org>
20  * License: MIT <http://www.opensource.org/licenses/mit-license.php>
21  * URL: git://repo.or.cz/fast-import.git http://repo.or.cz/w/fast-export.git
22  */
23
24 #define _XOPEN_SOURCE
25 #define _LARGEFILE_SUPPORT
26 #define _LARGEFILE64_SUPPORT
27
28 #include "svn.h"
29
30 #include <unistd.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <time.h>
34 #include <unistd.h>
35
36 #include <apr_lib.h>
37 #include <apr_getopt.h>
38 #include <apr_general.h>
39
40 #include <svn_fs.h>
41 #include <svn_pools.h>
42 #include <svn_repos.h>
43 #include <svn_types.h>
44
45 #include <QFile>
46 #include <QDebug>
47
48 #include "repository.h"
49
50 #undef SVN_ERR
51 #define SVN_ERR(expr) SVN_INT_ERR(expr)
52
53 typedef QList<Rules::Match> MatchRuleList;
54 typedef QHash<QString, Repository *> RepositoryHash;
55 typedef QHash<QByteArray, QByteArray> IdentityHash;
56
57 class AprAutoPool
58 {
59     apr_pool_t *pool;
60     AprAutoPool(const AprAutoPool &);
61     AprAutoPool &operator=(const AprAutoPool &);
62 public:
63     inline AprAutoPool(apr_pool_t *parent = NULL)
64         { pool = svn_pool_create(parent); }
65     inline ~AprAutoPool()
66         { svn_pool_destroy(pool); }
67
68     inline void clear() { svn_pool_clear(pool); }
69     inline apr_pool_t *data() const { return pool; }
70     inline operator apr_pool_t *() const { return pool; }
71 };
72
73 class SvnPrivate
74 {
75 public:
76     MatchRuleList matchRules;
77     RepositoryHash repositories;
78     IdentityHash identities;
79
80     SvnPrivate(const QString &pathToRepository);
81     ~SvnPrivate();
82     int youngestRevision();
83     int exportRevision(int revnum);
84
85     int openRepository(const QString &pathToRepository);
86
87 private:
88     AprAutoPool global_pool;
89     svn_fs_t *fs;
90     svn_revnum_t youngest_rev;
91 };
92
93 void Svn::initialize()
94 {
95     // initialize APR or exit
96     if (apr_initialize() != APR_SUCCESS) {
97         fprintf(stderr, "You lose at apr_initialize().\n");
98         exit(1);
99     }
100
101     // static destructor
102     static struct Destructor { ~Destructor() { apr_terminate(); } } destructor;
103 }
104
105 Svn::Svn(const QString &pathToRepository)
106     : d(new SvnPrivate(pathToRepository))
107 {
108 }
109
110 Svn::~Svn()
111 {
112     delete d;
113 }
114
115 void Svn::setMatchRules(const MatchRuleList &matchRules)
116 {
117     d->matchRules = matchRules;
118 }
119
120 void Svn::setRepositories(const RepositoryHash &repositories)
121 {
122     d->repositories = repositories;
123 }
124
125 int Svn::youngestRevision()
126 {
127     return d->youngestRevision();
128 }
129
130 bool Svn::exportRevision(int revnum)
131 {
132     return d->exportRevision(revnum) == EXIT_SUCCESS;
133 }
134
135 SvnPrivate::SvnPrivate(const QString &pathToRepository)
136     : global_pool(NULL)
137 {
138     openRepository(pathToRepository);
139
140     // get the youngest revision
141     svn_fs_youngest_rev(&youngest_rev, fs, global_pool);
142 }
143
144 SvnPrivate::~SvnPrivate()
145 {
146     svn_pool_destroy(global_pool);
147 }
148
149 int SvnPrivate::youngestRevision()
150 {
151     return youngest_rev;
152 }
153
154 int SvnPrivate::openRepository(const QString &pathToRepository)
155 {
156     svn_repos_t *repos;
157     SVN_ERR(svn_repos_open(&repos, QFile::encodeName(pathToRepository), global_pool));
158     fs = svn_repos_fs(repos);
159
160     return EXIT_SUCCESS;
161 }
162
163 enum RuleType { AnyRule = 0, NoIgnoreRule = 0x01, NoRecurseRule = 0x02 };
164
165 static MatchRuleList::ConstIterator
166 findMatchRule(const MatchRuleList &matchRules, int revnum, const QString &current,
167               int ruleMask = AnyRule)
168 {
169     MatchRuleList::ConstIterator it = matchRules.constBegin(),
170                                 end = matchRules.constEnd();
171     for ( ; it != end; ++it) {
172         if (it->minRevision > revnum)
173             continue;
174         if (it->maxRevision != -1 && it->maxRevision < revnum)
175             continue;
176         if (it->action == Rules::Match::Ignore && ruleMask & NoIgnoreRule)
177             continue;
178         if (it->action == Rules::Match::Recurse && ruleMask & NoRecurseRule)
179             continue;
180         if (it->rx.indexIn(current) == 0)
181             return it;
182     }
183
184     // no match
185     return end;
186 }
187
188 static void splitPathName(const Rules::Match &rule, const QString &pathName, QString *svnprefix_p,
189                           QString *repository_p, QString *branch_p, QString *path_p)
190 {
191     QString svnprefix = pathName;
192     svnprefix.truncate(rule.rx.matchedLength());
193     if (svnprefix_p)
194         *svnprefix_p = svnprefix;
195
196     if (repository_p) {
197         *repository_p = svnprefix;
198         repository_p->replace(rule.rx, rule.repository);
199     }
200
201     if (branch_p) {
202         *branch_p = svnprefix;
203         branch_p->replace(rule.rx, rule.branch);
204     }
205
206     if (path_p)
207         *path_p = pathName.mid(svnprefix.length());
208 }
209
210 static int pathMode(svn_fs_root_t *fs_root, const char *pathname, apr_pool_t *pool)
211 {
212     svn_string_t *propvalue;
213     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:executable", pool));
214     int mode = 0100644;
215     if (propvalue)
216         mode = 0100755;
217
218     // maybe it's a symlink?
219     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:special", pool));
220     if (propvalue && strcmp(propvalue->data, "symlink") == 0)
221         mode = 0120000;
222
223     return mode;
224 }
225
226 svn_error_t *QIODevice_write(void *baton, const char *data, apr_size_t *len)
227 {
228     QIODevice *device = reinterpret_cast<QIODevice *>(baton);
229     device->write(data, *len);
230
231     while (device->bytesToWrite() > 16*1024) {
232         int timeout = device->bytesToWrite() >= 128*1024 ? -1 : 0;
233         if (!device->waitForBytesWritten(timeout)) {
234             qFatal("Failed to write to process: %s", qPrintable(device->errorString()));
235             return svn_error_createf(APR_EOF, SVN_NO_ERROR, "Failed to write to process: %s",
236                                      qPrintable(device->errorString()));
237         }
238     }
239     return SVN_NO_ERROR;
240 }
241
242 static svn_stream_t *streamForDevice(QIODevice *device, apr_pool_t *pool)
243 {
244     svn_stream_t *stream = svn_stream_create(device, pool);
245     svn_stream_set_write(stream, QIODevice_write);
246
247     return stream;
248 }
249
250 static int dumpBlob(Repository::Transaction *txn, svn_fs_root_t *fs_root,
251                     const char *pathname, const QString &finalPathName, apr_pool_t *pool)
252 {
253     AprAutoPool dumppool(pool);
254     // what type is it?
255     int mode = pathMode(fs_root, pathname, dumppool);
256
257     svn_filesize_t stream_length;
258
259     SVN_ERR(svn_fs_file_length(&stream_length, fs_root, pathname, dumppool));
260     QIODevice *io = txn->addFile(finalPathName, mode, stream_length);
261
262 #ifndef DRY_RUN
263     // open the file
264     svn_stream_t *in_stream, *out_stream;
265     SVN_ERR(svn_fs_file_contents(&in_stream, fs_root, pathname, dumppool));
266
267     // open a generic svn_stream_t for the QIODevice
268     out_stream = streamForDevice(io, dumppool);
269     SVN_ERR(svn_stream_copy(in_stream, out_stream, dumppool));
270
271     // print an ending newline
272     io->putChar('\n');
273 #endif
274
275     return EXIT_SUCCESS;
276 }
277
278 static int recursiveDumpDir(Repository::Transaction *txn, svn_fs_root_t *fs_root,
279                             const QByteArray &pathname, const QString &finalPathName,
280                             apr_pool_t *pool)
281 {
282     // get the dir listing
283     apr_hash_t *entries;
284     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, pathname, pool));
285     AprAutoPool dirpool(pool);
286
287     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
288         dirpool.clear();
289         const void *vkey;
290         void *value;
291         apr_hash_this(i, &vkey, NULL, &value);
292
293         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
294         QByteArray entryName = pathname + '/' + dirent->name;
295         QString entryFinalName = finalPathName + dirent->name;
296
297         if (dirent->kind == svn_node_dir) {
298             entryFinalName += '/';
299             if (recursiveDumpDir(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
300                 return EXIT_FAILURE;
301         } else if (dirent->kind == svn_node_file) {
302             printf("+");
303             fflush(stdout);
304             if (dumpBlob(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
305                 return EXIT_FAILURE;
306         }
307     }
308
309     return EXIT_SUCCESS;
310 }
311
312 static bool wasDir(svn_fs_t *fs, int revnum, const char *pathname, apr_pool_t *pool)
313 {
314     AprAutoPool subpool(pool);
315     svn_fs_root_t *fs_root;
316     if (svn_fs_revision_root(&fs_root, fs, revnum, subpool) != SVN_NO_ERROR)
317         return false;
318
319     svn_boolean_t is_dir;
320     if (svn_fs_is_dir(&is_dir, fs_root, pathname, subpool) != SVN_NO_ERROR)
321         return false;
322
323     return is_dir;
324 }
325
326 time_t get_epoch(char *svn_date)
327 {
328     struct tm tm;
329     memset(&tm, 0, sizeof tm);
330     QByteArray date(svn_date, strlen(svn_date) - 8);
331     strptime(date, "%Y-%m-%dT%H:%M:%S", &tm);
332     return mktime(&tm);
333 }
334
335 class SvnRevision
336 {
337 public:
338     AprAutoPool pool;
339     QHash<QString, Repository::Transaction *> transactions;
340     MatchRuleList matchRules;
341     RepositoryHash repositories;
342     IdentityHash identities;
343
344     svn_fs_t *fs;
345     svn_fs_root_t *fs_root;
346     int revnum;
347
348     SvnRevision(int revision, svn_fs_t *f, apr_pool_t *parent_pool)
349         : pool(parent_pool), fs(f), fs_root(0), revnum(revision)
350     {
351     }
352
353     int open()
354     {
355         SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum, pool));
356         return EXIT_SUCCESS;
357     }
358
359     int prepareTransactions();
360     int commit();
361
362     int exportEntry(const char *path, const svn_fs_path_change_t *change, apr_hash_t *changes);
363     int exportDispatch(const char *path, const svn_fs_path_change_t *change,
364                        const char *path_from, svn_revnum_t rev_from,
365                        apr_hash_t *changes, const QString &current, const Rules::Match &rule,
366                        apr_pool_t *pool);
367     int exportInternal(const char *path, const svn_fs_path_change_t *change,
368                        const char *path_from, svn_revnum_t rev_from,
369                        const QString &current, const Rules::Match &rule);
370     int recurse(const char *path, const svn_fs_path_change_t *change,
371                 const char *path_from, svn_revnum_t rev_from,
372                 apr_hash_t *changes, apr_pool_t *pool);
373 };
374
375 int SvnPrivate::exportRevision(int revnum)
376 {
377     SvnRevision rev(revnum, fs, global_pool);
378     rev.matchRules = matchRules;
379     rev.repositories = repositories;
380     rev.identities = identities;
381
382     // open this revision:
383     printf("Exporting revision %d ", revnum);
384     fflush(stdout);
385
386     if (rev.open() == EXIT_FAILURE)
387         return EXIT_FAILURE;
388
389     if (rev.prepareTransactions() == EXIT_FAILURE)
390         return EXIT_FAILURE;
391
392     if (rev.transactions.isEmpty()) {
393         printf(" nothing to do\n");
394         return EXIT_SUCCESS;    // no changes?
395     }
396
397     if (rev.commit() == EXIT_FAILURE)
398         return EXIT_FAILURE;
399
400     printf(" done\n");
401     return EXIT_SUCCESS;
402 }
403
404 int SvnRevision::prepareTransactions()
405 {
406     // find out what was changed in this revision:
407     apr_hash_t *changes;
408     SVN_ERR(svn_fs_paths_changed(&changes, fs_root, pool));
409     for (apr_hash_index_t *i = apr_hash_first(pool, changes); i; i = apr_hash_next(i)) {
410         const void *vkey;
411         void *value;
412         apr_hash_this(i, &vkey, NULL, &value);
413         const char *key = reinterpret_cast<const char *>(vkey);
414         svn_fs_path_change_t *change = reinterpret_cast<svn_fs_path_change_t *>(value);
415
416         if (exportEntry(key, change, changes) == EXIT_FAILURE)
417             return EXIT_FAILURE;
418     }
419
420     return EXIT_SUCCESS;
421 }
422
423 int SvnRevision::commit()
424 {
425     // now create the commit
426     apr_hash_t *revprops;
427     SVN_ERR(svn_fs_revision_proplist(&revprops, fs, revnum, pool));
428     svn_string_t *svnauthor = (svn_string_t*)apr_hash_get(revprops, "svn:author", APR_HASH_KEY_STRING);
429     svn_string_t *svndate = (svn_string_t*)apr_hash_get(revprops, "svn:date", APR_HASH_KEY_STRING);
430     svn_string_t *svnlog = (svn_string_t*)apr_hash_get(revprops, "svn:log", APR_HASH_KEY_STRING);
431
432     QByteArray log = (char *)svnlog->data;
433     QByteArray authorident = svnauthor ? identities.value((char *)svnauthor->data) : QByteArray();
434     time_t epoch = get_epoch((char*)svndate->data);
435     if (authorident.isEmpty()) {
436         if (!svnauthor || svn_string_isempty(svnauthor))
437             authorident = "nobody <nobody@localhost>";
438         else
439             authorident = svnauthor->data + QByteArray(" <") +
440                           svnauthor->data + QByteArray("@localhost>");
441     }
442
443     foreach (Repository::Transaction *txn, transactions) {
444         txn->setAuthor(authorident);
445         txn->setDateTime(epoch);
446         txn->setLog(log);
447
448         txn->commit();
449         delete txn;
450     }
451
452     return EXIT_SUCCESS;
453 }
454
455 int SvnRevision::exportEntry(const char *key, const svn_fs_path_change_t *change,
456                              apr_hash_t *changes)
457 {
458     AprAutoPool revpool(pool.data());
459     QString current = QString::fromUtf8(key);
460
461     // was this copied from somewhere?
462     svn_revnum_t rev_from;
463     const char *path_from;
464     SVN_ERR(svn_fs_copied_from(&rev_from, &path_from, fs_root, key, revpool));
465
466     // is this a directory?
467     svn_boolean_t is_dir;
468     SVN_ERR(svn_fs_is_dir(&is_dir, fs_root, key, revpool));
469     if (is_dir) {
470         if (path_from == NULL) {
471             // no, it's a new directory being added
472             // Git doesn't handle directories, so we don't either
473             //qDebug() << "   mkdir ignored:" << key;
474             return EXIT_SUCCESS;
475         }
476
477         current += '/';
478         qDebug() << "   " << key << "was copied from" << path_from;
479     }
480
481     // find the first rule that matches this pathname
482     MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current);
483     if (match != matchRules.constEnd()) {
484         const Rules::Match &rule = *match;
485         return exportDispatch(key, change, path_from, rev_from, changes, current, rule, revpool);
486     }
487
488     if (is_dir && path_from != NULL) {
489         qDebug() << current << "is a copy-with-history, auto-recursing";
490         return recurse(key, change, path_from, rev_from, changes, revpool);
491     } else if (wasDir(fs, revnum - 1, key, revpool)) {
492         qDebug() << current << "was a directory; ignoring";
493     } else if (change->change_kind == svn_fs_path_change_delete) {
494         qDebug() << current << "is being deleted but I don't know anything about it; ignoring";
495     } else {
496         qCritical() << current << "did not match any rules; cannot continue";
497         return EXIT_FAILURE;
498     }
499
500     return EXIT_SUCCESS;
501 }
502
503 int SvnRevision::exportDispatch(const char *key, const svn_fs_path_change_t *change,
504                                 const char *path_from, svn_revnum_t rev_from,
505                                 apr_hash_t *changes, const QString &current,
506                                 const Rules::Match &rule, apr_pool_t *pool)
507 {
508     switch (rule.action) {
509     case Rules::Match::Ignore:
510         // ignore rule
511         qDebug() << "   " << qPrintable(current) << "rev" << revnum
512                  << "-> ignored (rule" << rule << ")";
513         return EXIT_SUCCESS;
514
515     case Rules::Match::Recurse:
516         return recurse(key, change, path_from, rev_from, changes, pool);
517
518     case Rules::Match::Export:
519         return exportInternal(key, change, path_from, rev_from, current, rule);
520     }
521
522     // never reached
523     return EXIT_FAILURE;
524 }
525
526 int SvnRevision::exportInternal(const char *key, const svn_fs_path_change_t *change,
527                                 const char *path_from, svn_revnum_t rev_from,
528                                 const QString &current, const Rules::Match &rule)
529 {
530     QString svnprefix, repository, branch, path;
531     splitPathName(rule, current, &svnprefix, &repository, &branch, &path);
532
533     printf(".");
534     fflush(stdout);
535 //                qDebug() << "   " << qPrintable(current) << "rev" << revnum << "->"
536 //                         << qPrintable(repository) << qPrintable(branch) << qPrintable(path);
537
538     if (path.isEmpty() && path_from != NULL) {
539         QString previous = QString::fromUtf8(path_from) + '/';
540         MatchRuleList::ConstIterator prevmatch =
541             findMatchRule(matchRules, rev_from, previous, NoIgnoreRule);
542         if (prevmatch != matchRules.constEnd()) {
543             QString prevsvnprefix, prevrepository, prevbranch, prevpath;
544             splitPathName(*prevmatch, previous, &prevsvnprefix, &prevrepository,
545                           &prevbranch, &prevpath);
546
547             if (!prevpath.isEmpty()) {
548                 qDebug() << qPrintable(current) << "is a partial branch of repository"
549                          << qPrintable(prevrepository) << "branch"
550                          << qPrintable(prevbranch) << "subdir"
551                          << qPrintable(prevpath);
552             } else if (prevrepository != repository) {
553                 qWarning() << qPrintable(current) << "rev" << revnum
554                            << "is a cross-repository copy (from repository"
555                            << qPrintable(prevrepository) << "branch"
556                            << qPrintable(prevbranch) << "path"
557                            << qPrintable(prevpath) << "rev" << rev_from << ")";
558             } else if (prevbranch == branch) {
559                 // same branch and same repository
560                 qDebug() << qPrintable(current) << "rev" << revnum
561                          << "is an SVN rename from"
562                          << qPrintable(previous) << "rev" << rev_from;
563                 return EXIT_SUCCESS;
564             } else {
565                 // same repository but not same branch
566                 // this means this is a plain branch
567                 qDebug() << qPrintable(repository) << ": branch"
568                          << qPrintable(branch) << "is branching from"
569                          << qPrintable(prevbranch);
570
571                 Repository *repo = repositories.value(repository, 0);
572                 if (!repo) {
573                     qCritical() << "Rule" << rule
574                                 << "references unknown repository" << repository;
575                     return EXIT_FAILURE;
576                 }
577
578                 repo->createBranch(branch, revnum, prevbranch, rev_from);
579                 return EXIT_SUCCESS;
580             }
581         }
582     }
583
584     Repository::Transaction *txn = transactions.value(repository + branch, 0);
585     if (!txn) {
586         Repository *repo = repositories.value(repository, 0);
587         if (!repo) {
588             qCritical() << "Rule" << rule
589                         << "references unknown repository" << repository;
590             return EXIT_FAILURE;
591         }
592
593         txn = repo->newTransaction(branch, svnprefix, revnum);
594         if (!txn)
595             return EXIT_FAILURE;
596
597         transactions.insert(repository + branch, txn);
598     }
599
600     if (change->change_kind == svn_fs_path_change_delete) {
601         txn->deleteFile(path);
602     } else if (!current.endsWith('/')) {
603         dumpBlob(txn, fs_root, key, path, pool);
604     } else {
605         QString pathNoSlash = path;
606         pathNoSlash.chop(1);
607         txn->deleteFile(pathNoSlash);
608         recursiveDumpDir(txn, fs_root, key, path, pool);
609     }
610
611     return EXIT_SUCCESS;
612 }
613
614 int SvnRevision::recurse(const char *path, const svn_fs_path_change_t *change,
615                          const char *path_from, svn_revnum_t rev_from,
616                          apr_hash_t *changes, apr_pool_t *pool)
617 {
618     // get the dir listing
619     apr_hash_t *entries;
620     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, path, pool));
621
622     AprAutoPool dirpool(pool);
623     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
624         dirpool.clear();
625         const void *vkey;
626         void *value;
627         apr_hash_this(i, &vkey, NULL, &value);
628
629         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
630         QByteArray entry = path + QByteArray("/") + dirent->name;
631         QByteArray entryFrom;
632         if (path_from)
633             entryFrom = path_from + QByteArray("/") + dirent->name;
634
635         // check if this entry is in the changelist for this revision already
636         if (apr_hash_get(changes, entry.constData(), APR_HASH_KEY_STRING)) {
637             qDebug() << entry << "rev" << revnum
638                      << "is in the change-list, deferring to that one";
639             continue;
640         }
641
642         QString current = QString::fromUtf8(entry);
643         if (dirent->kind == svn_node_dir)
644             current += '/';
645
646         // find the first rule that matches this pathname
647         MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current);
648         if (match != matchRules.constEnd()) {
649             if (exportDispatch(entry, change, entryFrom.isNull() ? 0 : entryFrom.constData(),
650                                rev_from, changes, current, *match, dirpool) == EXIT_FAILURE)
651                 return EXIT_FAILURE;
652         } else {
653             qCritical() << current << "rev" << revnum
654                         << "did not match any rules; cannot continue";
655             return EXIT_FAILURE;
656         }
657     }
658
659     return EXIT_SUCCESS;
660 }
This page took 0.100283 seconds and 5 git commands to generate.