More verbose debug output
[svn2git:cuboxs-uqs-svn2git.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 3 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 #include "CommandLineParser.h"
30
31 #include <unistd.h>
32 #include <string.h>
33 #include <stdio.h>
34 #include <time.h>
35 #include <unistd.h>
36
37 #include <apr_lib.h>
38 #include <apr_getopt.h>
39 #include <apr_general.h>
40
41 #include <svn_fs.h>
42 #include <svn_pools.h>
43 #include <svn_repos.h>
44 #include <svn_types.h>
45
46 #include <QFile>
47 #include <QDebug>
48
49 #include "repository.h"
50
51 #undef SVN_ERR
52 #define SVN_ERR(expr) SVN_INT_ERR(expr)
53
54 typedef QList<Rules::Match> MatchRuleList;
55 typedef QHash<QString, Repository *> RepositoryHash;
56 typedef QHash<QByteArray, QByteArray> IdentityHash;
57
58 class AprAutoPool
59 {
60     apr_pool_t *pool;
61     AprAutoPool(const AprAutoPool &);
62     AprAutoPool &operator=(const AprAutoPool &);
63 public:
64     inline AprAutoPool(apr_pool_t *parent = NULL)
65         { pool = svn_pool_create(parent); }
66     inline ~AprAutoPool()
67         { svn_pool_destroy(pool); }
68
69     inline void clear() { svn_pool_clear(pool); }
70     inline apr_pool_t *data() const { return pool; }
71     inline operator apr_pool_t *() const { return pool; }
72 };
73
74 class SvnPrivate
75 {
76 public:
77     MatchRuleList matchRules;
78     RepositoryHash repositories;
79     IdentityHash identities;
80
81     SvnPrivate(const QString &pathToRepository);
82     ~SvnPrivate();
83     int youngestRevision();
84     int exportRevision(int revnum);
85
86     int openRepository(const QString &pathToRepository);
87
88 private:
89     AprAutoPool global_pool;
90     svn_fs_t *fs;
91     svn_revnum_t youngest_rev;
92 };
93
94 void Svn::initialize()
95 {
96     // initialize APR or exit
97     if (apr_initialize() != APR_SUCCESS) {
98         fprintf(stderr, "You lose at apr_initialize().\n");
99         exit(1);
100     }
101
102     // static destructor
103     static struct Destructor { ~Destructor() { apr_terminate(); } } destructor;
104 }
105
106 Svn::Svn(const QString &pathToRepository)
107     : d(new SvnPrivate(pathToRepository))
108 {
109 }
110
111 Svn::~Svn()
112 {
113     delete d;
114 }
115
116 void Svn::setMatchRules(const MatchRuleList &matchRules)
117 {
118     d->matchRules = matchRules;
119 }
120
121 void Svn::setRepositories(const RepositoryHash &repositories)
122 {
123     d->repositories = repositories;
124 }
125
126 void Svn::setIdentityMap(const IdentityHash &identityMap)
127 {
128     d->identities = identityMap;
129 }
130
131 int Svn::youngestRevision()
132 {
133     return d->youngestRevision();
134 }
135
136 bool Svn::exportRevision(int revnum)
137 {
138     return d->exportRevision(revnum) == EXIT_SUCCESS;
139 }
140
141 SvnPrivate::SvnPrivate(const QString &pathToRepository)
142     : global_pool(NULL)
143 {
144     if( openRepository(pathToRepository) != EXIT_SUCCESS) {
145         qCritical() << "Failed to open repository";
146         exit(1);
147     }
148
149     // get the youngest revision
150     svn_fs_youngest_rev(&youngest_rev, fs, global_pool);
151 }
152
153 SvnPrivate::~SvnPrivate()
154 {
155     svn_pool_destroy(global_pool);
156 }
157
158 int SvnPrivate::youngestRevision()
159 {
160     return youngest_rev;
161 }
162
163 int SvnPrivate::openRepository(const QString &pathToRepository)
164 {
165     svn_repos_t *repos;
166     QString path = pathToRepository;
167     while (path.endsWith('/')) // no trailing slash allowed
168         path = path.mid(0, path.length()-1);
169     SVN_ERR(svn_repos_open(&repos, QFile::encodeName(path), global_pool));
170     fs = svn_repos_fs(repos);
171
172     return EXIT_SUCCESS;
173 }
174
175 enum RuleType { AnyRule = 0, NoIgnoreRule = 0x01, NoRecurseRule = 0x02 };
176
177 static MatchRuleList::ConstIterator
178 findMatchRule(const MatchRuleList &matchRules, int revnum, const QString &current,
179               int ruleMask = AnyRule)
180 {
181     MatchRuleList::ConstIterator it = matchRules.constBegin(),
182                                 end = matchRules.constEnd();
183     for ( ; it != end; ++it) {
184         if (it->minRevision > revnum)
185             continue;
186         if (it->maxRevision != -1 && it->maxRevision < revnum)
187             continue;
188         if (it->action == Rules::Match::Ignore && ruleMask & NoIgnoreRule)
189             continue;
190         if (it->action == Rules::Match::Recurse && ruleMask & NoRecurseRule)
191             continue;
192         if (it->rx.indexIn(current) == 0) {
193             return it;
194         }
195     }
196
197     // no match
198     return end;
199 }
200
201 static void splitPathName(const Rules::Match &rule, const QString &pathName, QString *svnprefix_p,
202                           QString *repository_p, QString *branch_p, QString *path_p)
203 {
204     QString svnprefix = pathName;
205     svnprefix.truncate(rule.rx.matchedLength());
206
207     if (svnprefix_p) {
208         *svnprefix_p = svnprefix;
209     }
210
211     if (repository_p) {
212         *repository_p = svnprefix;
213         repository_p->replace(rule.rx, rule.repository);
214     }
215
216     if (branch_p) {
217         *branch_p = svnprefix;
218         branch_p->replace(rule.rx, rule.branch);
219     }
220
221     if (path_p) {
222         QString prefix = svnprefix;
223         prefix.replace(rule.rx, rule.prefix);
224         *path_p = prefix + pathName.mid(svnprefix.length());
225     }
226 }
227
228 static int pathMode(svn_fs_root_t *fs_root, const char *pathname, apr_pool_t *pool)
229 {
230     svn_string_t *propvalue;
231     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:executable", pool));
232     int mode = 0100644;
233     if (propvalue)
234         mode = 0100755;
235
236     return mode;
237 }
238
239 svn_error_t *QIODevice_write(void *baton, const char *data, apr_size_t *len)
240 {
241     QIODevice *device = reinterpret_cast<QIODevice *>(baton);
242     device->write(data, *len);
243
244     while (device->bytesToWrite() > 32*1024) {
245         if (!device->waitForBytesWritten(-1)) {
246             qFatal("Failed to write to process: %s", qPrintable(device->errorString()));
247             return svn_error_createf(APR_EOF, SVN_NO_ERROR, "Failed to write to process: %s",
248                                      qPrintable(device->errorString()));
249         }
250     }
251     return SVN_NO_ERROR;
252 }
253
254 static svn_stream_t *streamForDevice(QIODevice *device, apr_pool_t *pool)
255 {
256     svn_stream_t *stream = svn_stream_create(device, pool);
257     svn_stream_set_write(stream, QIODevice_write);
258
259     return stream;
260 }
261
262 static int dumpBlob(Repository::Transaction *txn, svn_fs_root_t *fs_root,
263                     const char *pathname, const QString &finalPathName, apr_pool_t *pool)
264 {
265     AprAutoPool dumppool(pool);
266     // what type is it?
267     int mode = pathMode(fs_root, pathname, dumppool);
268
269     svn_filesize_t stream_length;
270
271     SVN_ERR(svn_fs_file_length(&stream_length, fs_root, pathname, dumppool));
272
273     svn_stream_t *in_stream, *out_stream;
274     if (!CommandLineParser::instance()->contains("dry-run")) {
275         // open the file
276         SVN_ERR(svn_fs_file_contents(&in_stream, fs_root, pathname, dumppool));
277     }
278
279     // maybe it's a symlink?
280     svn_string_t *propvalue;
281     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:special", dumppool));
282     if (propvalue) {
283         apr_size_t len = strlen("link ");
284         if (!CommandLineParser::instance()->contains("dry-run")) {
285             QByteArray buf;
286             buf.reserve(len);
287             SVN_ERR(svn_stream_read(in_stream, buf.data(), &len));
288             if (len != strlen("link ") || strncmp(buf, "link ", len) != 0)
289                 qFatal("file %s is svn:special but not a symlink", pathname);
290         }
291         mode = 0120000;
292         stream_length -= len;
293     }
294
295     QIODevice *io = txn->addFile(finalPathName, mode, stream_length);
296
297     if (!CommandLineParser::instance()->contains("dry-run")) {
298         // open a generic svn_stream_t for the QIODevice
299         out_stream = streamForDevice(io, dumppool);
300         SVN_ERR(svn_stream_copy(in_stream, out_stream, dumppool));
301         svn_stream_close(out_stream);
302         svn_stream_close(in_stream);
303
304         // print an ending newline
305         io->putChar('\n');
306     }
307
308     return EXIT_SUCCESS;
309 }
310
311 static int recursiveDumpDir(Repository::Transaction *txn, svn_fs_root_t *fs_root,
312                             const QByteArray &pathname, const QString &finalPathName,
313                             apr_pool_t *pool)
314 {
315     // get the dir listing
316     apr_hash_t *entries;
317     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, pathname, pool));
318     AprAutoPool dirpool(pool);
319
320     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
321         dirpool.clear();
322         const void *vkey;
323         void *value;
324         apr_hash_this(i, &vkey, NULL, &value);
325
326         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
327         QByteArray entryName = pathname + '/' + dirent->name;
328         QString entryFinalName = finalPathName + QString::fromUtf8(dirent->name);
329
330         if (dirent->kind == svn_node_dir) {
331             entryFinalName += '/';
332             if (recursiveDumpDir(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
333                 return EXIT_FAILURE;
334         } else if (dirent->kind == svn_node_file) {
335             printf("+");
336             fflush(stdout);
337             if (dumpBlob(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
338                 return EXIT_FAILURE;
339         }
340     }
341
342     return EXIT_SUCCESS;
343 }
344
345 static bool wasDir(svn_fs_t *fs, int revnum, const char *pathname, apr_pool_t *pool)
346 {
347     AprAutoPool subpool(pool);
348     svn_fs_root_t *fs_root;
349     if (svn_fs_revision_root(&fs_root, fs, revnum, subpool) != SVN_NO_ERROR)
350         return false;
351
352     svn_boolean_t is_dir;
353     if (svn_fs_is_dir(&is_dir, fs_root, pathname, subpool) != SVN_NO_ERROR)
354         return false;
355
356     return is_dir;
357 }
358
359 time_t get_epoch(char *svn_date)
360 {
361     struct tm tm;
362     memset(&tm, 0, sizeof tm);
363     QByteArray date(svn_date, strlen(svn_date) - 8);
364     strptime(date, "%Y-%m-%dT%H:%M:%S", &tm);
365     return timegm(&tm);
366 }
367
368 class SvnRevision
369 {
370 public:
371     AprAutoPool pool;
372     QHash<QString, Repository::Transaction *> transactions;
373     MatchRuleList matchRules;
374     RepositoryHash repositories;
375     IdentityHash identities;
376
377     svn_fs_t *fs;
378     svn_fs_root_t *fs_root;
379     int revnum;
380
381     // must call fetchRevProps first:
382     QByteArray authorident;
383     QByteArray log;
384     uint epoch;
385     bool ruledebug;
386
387     SvnRevision(int revision, svn_fs_t *f, apr_pool_t *parent_pool)
388         : pool(parent_pool), fs(f), fs_root(0), revnum(revision)
389     {
390         ruledebug = CommandLineParser::instance()->contains( QLatin1String("debug-rules"));
391     }
392
393     int open()
394     {
395         SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum, pool));
396         return EXIT_SUCCESS;
397     }
398
399     int prepareTransactions();
400     int fetchRevProps();
401     int commit();
402
403     int exportEntry(const char *path, const svn_fs_path_change_t *change, apr_hash_t *changes);
404     int exportDispatch(const char *path, const svn_fs_path_change_t *change,
405                        const char *path_from, svn_revnum_t rev_from,
406                        apr_hash_t *changes, const QString &current, const Rules::Match &rule,
407                        apr_pool_t *pool);
408     int exportInternal(const char *path, const svn_fs_path_change_t *change,
409                        const char *path_from, svn_revnum_t rev_from,
410                        const QString &current, const Rules::Match &rule);
411     int recurse(const char *path, const svn_fs_path_change_t *change,
412                 const char *path_from, svn_revnum_t rev_from,
413                 apr_hash_t *changes, apr_pool_t *pool);
414 };
415
416 int SvnPrivate::exportRevision(int revnum)
417 {
418     SvnRevision rev(revnum, fs, global_pool);
419     rev.matchRules = matchRules;
420     rev.repositories = repositories;
421     rev.identities = identities;
422
423     // open this revision:
424     printf("Exporting revision %d ", revnum);
425     fflush(stdout);
426
427     if (rev.open() == EXIT_FAILURE)
428         return EXIT_FAILURE;
429
430     if (rev.prepareTransactions() == EXIT_FAILURE)
431         return EXIT_FAILURE;
432
433     if (rev.transactions.isEmpty()) {
434         printf(" nothing to do\n");
435         return EXIT_SUCCESS;    // no changes?
436     }
437
438     if (rev.commit() == EXIT_FAILURE)
439         return EXIT_FAILURE;
440
441     printf(" done\n");
442     return EXIT_SUCCESS;
443 }
444
445 int SvnRevision::prepareTransactions()
446 {
447     // find out what was changed in this revision:
448     apr_hash_t *changes;
449     SVN_ERR(svn_fs_paths_changed(&changes, fs_root, pool));
450     for (apr_hash_index_t *i = apr_hash_first(pool, changes); i; i = apr_hash_next(i)) {
451         const void *vkey;
452         void *value;
453         apr_hash_this(i, &vkey, NULL, &value);
454         const char *key = reinterpret_cast<const char *>(vkey);
455         svn_fs_path_change_t *change = reinterpret_cast<svn_fs_path_change_t *>(value);
456
457         if (exportEntry(key, change, changes) == EXIT_FAILURE)
458             return EXIT_FAILURE;
459     }
460
461     return EXIT_SUCCESS;
462 }
463
464 int SvnRevision::fetchRevProps()
465 {
466     apr_hash_t *revprops;
467     SVN_ERR(svn_fs_revision_proplist(&revprops, fs, revnum, pool));
468     svn_string_t *svnauthor = (svn_string_t*)apr_hash_get(revprops, "svn:author", APR_HASH_KEY_STRING);
469     svn_string_t *svndate = (svn_string_t*)apr_hash_get(revprops, "svn:date", APR_HASH_KEY_STRING);
470     svn_string_t *svnlog = (svn_string_t*)apr_hash_get(revprops, "svn:log", APR_HASH_KEY_STRING);
471
472     log = (char *)svnlog->data;
473     authorident = svnauthor ? identities.value((char *)svnauthor->data) : QByteArray();
474     epoch = get_epoch((char*)svndate->data);
475     if (authorident.isEmpty()) {
476         if (!svnauthor || svn_string_isempty(svnauthor))
477             authorident = "nobody <nobody@localhost>";
478         else
479             authorident = svnauthor->data + QByteArray(" <") +
480                           svnauthor->data + QByteArray("@localhost>");
481     }
482     return EXIT_SUCCESS;
483 }
484
485 int SvnRevision::commit()
486 {
487     // now create the commit
488     if (fetchRevProps() != EXIT_SUCCESS)
489         return EXIT_FAILURE;
490     foreach (Repository::Transaction *txn, transactions) {
491         txn->setAuthor(authorident);
492         txn->setDateTime(epoch);
493         txn->setLog(log);
494
495         txn->commit();
496         delete txn;
497     }
498
499     return EXIT_SUCCESS;
500 }
501
502 int SvnRevision::exportEntry(const char *key, const svn_fs_path_change_t *change,
503                              apr_hash_t *changes)
504 {
505     AprAutoPool revpool(pool.data());
506     QString current = QString::fromUtf8(key);
507
508     // was this copied from somewhere?
509     svn_revnum_t rev_from;
510     const char *path_from;
511     SVN_ERR(svn_fs_copied_from(&rev_from, &path_from, fs_root, key, revpool));
512
513     // is this a directory?
514     svn_boolean_t is_dir;
515     SVN_ERR(svn_fs_is_dir(&is_dir, fs_root, key, revpool));
516     if (is_dir) {
517         if (change->change_kind == svn_fs_path_change_modify ||
518             change->change_kind == svn_fs_path_change_add) {
519             if (path_from == NULL) {
520                 // freshly added directory, or modified properties
521                 // Git doesn't handle directories, so we don't either
522                 //qDebug() << "   mkdir ignored:" << key;
523                 return EXIT_SUCCESS;
524             }
525
526             qDebug() << "   " << key << "was copied from" << path_from << "rev" << rev_from;
527         } else if (change->change_kind == svn_fs_path_change_replace) {
528             if (path_from == NULL)
529                 qDebug() << "   " << key << "was replaced";
530             else
531                 qDebug() << "   " << key << "was replaced from" << path_from << "rev" << rev_from;
532         } else if (change->change_kind == svn_fs_path_change_reset) {
533             qCritical() << "   " << key << "was reset, panic!";
534             return EXIT_FAILURE;
535         } else {
536             // if change_kind == delete, it shouldn't come into this arm of the 'is_dir' test
537             qCritical() << "   " << key << "has unhandled change kind " << change->change_kind << ", panic!";
538             return EXIT_FAILURE;
539         }
540     } else if (change->change_kind == svn_fs_path_change_delete) {
541         is_dir = wasDir(fs, revnum - 1, key, revpool);
542     }
543
544     if (is_dir)
545         current += '/';
546
547     // find the first rule that matches this pathname
548     MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current);
549     if (match != matchRules.constEnd()) {
550         const Rules::Match &rule = *match;
551         return exportDispatch(key, change, path_from, rev_from, changes, current, rule, revpool);
552     }
553
554     if (is_dir && path_from != NULL) {
555         qDebug() << current << "is a copy-with-history, auto-recursing";
556         return recurse(key, change, path_from, rev_from, changes, revpool);
557     } else if (is_dir && change->change_kind == svn_fs_path_change_delete) {
558         qDebug() << current << "deleted, auto-recursing";
559         return recurse(key, change, path_from, rev_from, changes, revpool);
560     } else if (wasDir(fs, revnum - 1, key, revpool)) {
561         qDebug() << current << "was a directory; ignoring";
562     } else if (change->change_kind == svn_fs_path_change_delete) {
563         qDebug() << current << "is being deleted but I don't know anything about it; ignoring";
564     } else {
565         qCritical() << current << "did not match any rules; cannot continue";
566         return EXIT_FAILURE;
567     }
568
569     return EXIT_SUCCESS;
570 }
571
572 int SvnRevision::exportDispatch(const char *key, const svn_fs_path_change_t *change,
573                                 const char *path_from, svn_revnum_t rev_from,
574                                 apr_hash_t *changes, const QString &current,
575                                 const Rules::Match &rule, apr_pool_t *pool)
576 {
577     //if(ruledebug)
578     //  qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.lineNumber << "(" << rule.rx.pattern() << ")";
579     switch (rule.action) {
580     case Rules::Match::Ignore:
581         //if(ruledebug)
582         //    qDebug() << "  " << "ignoring.";
583         return EXIT_SUCCESS;
584
585     case Rules::Match::Recurse:
586         if(ruledebug)
587             qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.lineNumber << "(" << rule.rx.pattern() << ")" << "  " << "recursing.";
588         return recurse(key, change, path_from, rev_from, changes, pool);
589
590     case Rules::Match::Export:
591         if(ruledebug)
592             qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.lineNumber << "(" << rule.rx.pattern() << ")" << "  " << "exporting.";
593         if (exportInternal(key, change, path_from, rev_from, current, rule) == EXIT_SUCCESS)
594             return EXIT_SUCCESS;
595         if (change->change_kind != svn_fs_path_change_delete) {
596             if(ruledebug)
597                 qDebug() << "rev" << revnum << qPrintable(current) << "matched rule:" << rule.lineNumber << "(" << rule.rx.pattern() << ")" << "  " << "Unable to export non path removal.";
598             return EXIT_FAILURE;
599         }
600         // we know that the default action inside recurse is to recurse further or to ignore,
601         // either of which is reasonably safe for deletion
602         qWarning() << "deleting unknown path" << current << "; auto-recursing";
603         return recurse(key, change, path_from, rev_from, changes, pool);
604     }
605
606     // never reached
607     return EXIT_FAILURE;
608 }
609
610 int SvnRevision::exportInternal(const char *key, const svn_fs_path_change_t *change,
611                                 const char *path_from, svn_revnum_t rev_from,
612                                 const QString &current, const Rules::Match &rule)
613 {
614     QString svnprefix, repository, branch, path;
615     splitPathName(rule, current, &svnprefix, &repository, &branch, &path);
616
617     Repository *repo = repositories.value(repository, 0);
618     if (!repo) {
619         if (change->change_kind != svn_fs_path_change_delete)
620             qCritical() << "Rule" << rule
621                         << "references unknown repository" << repository;
622         return EXIT_FAILURE;
623     }
624
625     printf(".");
626     fflush(stdout);
627 //                qDebug() << "   " << qPrintable(current) << "rev" << revnum << "->"
628 //                         << qPrintable(repository) << qPrintable(branch) << qPrintable(path);
629
630     if (change->change_kind == svn_fs_path_change_delete && current == svnprefix && path.isEmpty()) {
631         if(ruledebug)
632             qDebug() << "repository" << repository << "branch" << branch << "deleted";
633         return repo->deleteBranch(branch, revnum);
634     }
635
636     QString previous;
637     QString prevsvnprefix, prevrepository, prevbranch, prevpath;
638
639     if (path_from != NULL) {
640         previous = QString::fromUtf8(path_from) + '/';
641         MatchRuleList::ConstIterator prevmatch =
642             findMatchRule(matchRules, rev_from, previous, NoIgnoreRule);
643         if (prevmatch != matchRules.constEnd()) {
644             splitPathName(*prevmatch, previous, &prevsvnprefix, &prevrepository,
645                           &prevbranch, &prevpath);
646         } else {
647             qWarning() << "SVN reports a \"copy from\" but no matching rules found! Ignoring copy, treating as a modification";
648             path_from = NULL;
649         }
650     }
651
652     // current == svnprefix => we're dealing with the contents of the whole branch here
653     if (path_from != NULL && current == svnprefix && path.isEmpty()) {
654         if (previous != prevsvnprefix) {
655             // source is not the whole of its branch
656             qDebug() << qPrintable(current) << "is a partial branch of repository"
657                      << qPrintable(prevrepository) << "branch"
658                      << qPrintable(prevbranch) << "subdir"
659                      << qPrintable(prevpath);
660         } else if (prevrepository != repository) {
661             qWarning() << qPrintable(current) << "rev" << revnum
662                        << "is a cross-repository copy (from repository"
663                        << qPrintable(prevrepository) << "branch"
664                        << qPrintable(prevbranch) << "path"
665                        << qPrintable(prevpath) << "rev" << rev_from << ")";
666         } else if (path != prevpath) {
667             qDebug() << qPrintable(current)
668                      << "is a branch copy which renames base directory of all contents"
669                      << qPrintable(prevpath) << "to" << qPrintable(path);
670             // FIXME: Handle with fast-import 'file rename' facility
671             //        ??? Might need special handling when path == / or prevpath == /
672         } else {
673             if (prevbranch == branch) {
674                 // same branch and same repository
675                 qDebug() << qPrintable(current) << "rev" << revnum
676                          << "is reseating branch" << qPrintable(branch)
677                          << "to an earlier revision"
678                          << qPrintable(previous) << "rev" << rev_from;
679             } else {
680                 // same repository but not same branch
681                 // this means this is a plain branch
682                 qDebug() << qPrintable(repository) << ": branch"
683                          << qPrintable(branch) << "is branching from"
684                          << qPrintable(prevbranch);
685             }
686
687             if (repo->createBranch(branch, revnum, prevbranch, rev_from) == EXIT_FAILURE)
688                 return EXIT_FAILURE;
689             if (rule.annotate) {
690                 // create an annotated tag
691                 fetchRevProps();
692                 repo->createAnnotatedTag(branch, svnprefix, revnum, authorident,
693                                          epoch, log);
694             }
695             return EXIT_SUCCESS;
696         }
697     }
698     Repository::Transaction *txn = transactions.value(repository + branch, 0);
699     if (!txn) {
700         txn = repo->newTransaction(branch, svnprefix, revnum);
701         if (!txn)
702             return EXIT_FAILURE;
703
704         transactions.insert(repository + branch, txn);
705     }
706
707     //
708     // If this path was copied from elsewhere, use it to infer _some_
709     // merge points.  This heuristic is fairly useful for tracking
710     // changes across directory re-organizations and wholesale branch
711     // imports.
712     //
713     if (path_from != NULL && prevrepository == repository) {
714         if(ruledebug)
715             qDebug() << "copy from branch" << prevbranch << "rev" << rev_from;
716         txn->noteCopyFromBranch (prevbranch, rev_from);
717     }
718
719     if (change->change_kind == svn_fs_path_change_replace && path_from == NULL) {
720         if(ruledebug)
721             qDebug() << "replaced with empty path (" << branch << path << ")";
722         txn->deleteFile(path);
723     }
724     if (change->change_kind == svn_fs_path_change_delete) {
725         if(ruledebug)
726             qDebug() << "delete (" << branch << path << ")";
727         txn->deleteFile(path);
728     } else if (!current.endsWith('/')) {
729         if(ruledebug)
730             qDebug() << "add/change file (" << key << "->" << branch << path << ")";
731         dumpBlob(txn, fs_root, key, path, pool);
732     } else {
733         if(ruledebug)
734             qDebug() << "add/change dir (" << key << "->" << branch << path << ")";
735         txn->deleteFile(path);
736         recursiveDumpDir(txn, fs_root, key, path, pool);
737     }
738
739     return EXIT_SUCCESS;
740 }
741
742 int SvnRevision::recurse(const char *path, const svn_fs_path_change_t *change,
743                          const char *path_from, svn_revnum_t rev_from,
744                          apr_hash_t *changes, apr_pool_t *pool)
745 {
746     svn_fs_root_t *fs_root = this->fs_root;
747     if (change->change_kind == svn_fs_path_change_delete)
748         SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum - 1, pool));
749
750     // get the dir listing
751     apr_hash_t *entries;
752     svn_node_kind_t kind;
753     SVN_ERR(svn_fs_check_path(&kind, fs_root, path, pool));
754     if(kind == svn_node_none) {
755         qWarning() << "Trying to recurse using a nonexistant path" << path << ", ignoring";
756         return EXIT_SUCCESS;
757     }
758
759     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, path, pool));
760
761     AprAutoPool dirpool(pool);
762     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
763         dirpool.clear();
764         const void *vkey;
765         void *value;
766         apr_hash_this(i, &vkey, NULL, &value);
767
768         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
769         if (dirent->kind != svn_node_dir)
770             continue;           // not a directory, so can't recurse; skip
771
772         QByteArray entry = path + QByteArray("/") + dirent->name;
773         QByteArray entryFrom;
774         if (path_from)
775             entryFrom = path_from + QByteArray("/") + dirent->name;
776
777         // check if this entry is in the changelist for this revision already
778         svn_fs_path_change_t *otherchange =
779             (svn_fs_path_change_t*)apr_hash_get(changes, entry.constData(), APR_HASH_KEY_STRING);
780         if (otherchange && otherchange->change_kind == svn_fs_path_change_add) {
781             qDebug() << entry << "rev" << revnum
782                      << "is in the change-list, deferring to that one";
783             continue;
784         }
785
786         QString current = QString::fromUtf8(entry);
787         if (dirent->kind == svn_node_dir)
788             current += '/';
789
790         // find the first rule that matches this pathname
791         MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current);
792         if (match != matchRules.constEnd()) {
793             if (exportDispatch(entry, change, entryFrom.isNull() ? 0 : entryFrom.constData(),
794                                rev_from, changes, current, *match, dirpool) == EXIT_FAILURE)
795                 return EXIT_FAILURE;
796         } else {
797             qDebug() << current << "rev" << revnum
798                      << "did not match any rules; auto-recursing";
799             if (recurse(entry, change, entryFrom.isNull() ? 0 : entryFrom.constData(),
800                         rev_from, changes, dirpool) == EXIT_FAILURE)
801                 return EXIT_FAILURE;
802         }
803     }
804
805     return EXIT_SUCCESS;
806 }