]> andersk Git - svn-all-fast-export.git/blob - src/svn.cpp
1e7dcbff40a22408d65731808345e56b04139226
[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 void Svn::setIdentityMap(const IdentityHash &identityMap)
126 {
127     d->identities = identityMap;
128 }
129
130 int Svn::youngestRevision()
131 {
132     return d->youngestRevision();
133 }
134
135 bool Svn::exportRevision(int revnum)
136 {
137     return d->exportRevision(revnum) == EXIT_SUCCESS;
138 }
139
140 SvnPrivate::SvnPrivate(const QString &pathToRepository)
141     : global_pool(NULL)
142 {
143     openRepository(pathToRepository);
144
145     // get the youngest revision
146     svn_fs_youngest_rev(&youngest_rev, fs, global_pool);
147 }
148
149 SvnPrivate::~SvnPrivate()
150 {
151     svn_pool_destroy(global_pool);
152 }
153
154 int SvnPrivate::youngestRevision()
155 {
156     return youngest_rev;
157 }
158
159 int SvnPrivate::openRepository(const QString &pathToRepository)
160 {
161     svn_repos_t *repos;
162     SVN_ERR(svn_repos_open(&repos, QFile::encodeName(pathToRepository), global_pool));
163     fs = svn_repos_fs(repos);
164
165     return EXIT_SUCCESS;
166 }
167
168 enum RuleType { AnyRule = 0, NoIgnoreRule = 0x01, NoRecurseRule = 0x02 };
169
170 static MatchRuleList::ConstIterator
171 findMatchRule(const MatchRuleList &matchRules, int revnum, const QString &current,
172               int ruleMask = AnyRule)
173 {
174     MatchRuleList::ConstIterator it = matchRules.constBegin(),
175                                 end = matchRules.constEnd();
176     for ( ; it != end; ++it) {
177         if (it->minRevision > revnum)
178             continue;
179         if (it->maxRevision != -1 && it->maxRevision < revnum)
180             continue;
181         if (it->action == Rules::Match::Ignore && ruleMask & NoIgnoreRule)
182             continue;
183         if (it->action == Rules::Match::Recurse && ruleMask & NoRecurseRule)
184             continue;
185         if (it->rx.indexIn(current) == 0)
186             return it;
187     }
188
189     // no match
190     return end;
191 }
192
193 static void splitPathName(const Rules::Match &rule, const QString &pathName, QString *svnprefix_p,
194                           QString *repository_p, QString *branch_p, QString *path_p)
195 {
196     QString svnprefix = pathName;
197     svnprefix.truncate(rule.rx.matchedLength());
198     if (svnprefix_p)
199         *svnprefix_p = svnprefix;
200
201     if (repository_p) {
202         *repository_p = svnprefix;
203         repository_p->replace(rule.rx, rule.repository);
204     }
205
206     if (branch_p) {
207         *branch_p = svnprefix;
208         branch_p->replace(rule.rx, rule.branch);
209     }
210
211     if (path_p)
212         *path_p = pathName.mid(svnprefix.length());
213 }
214
215 static int pathMode(svn_fs_root_t *fs_root, const char *pathname, apr_pool_t *pool)
216 {
217     svn_string_t *propvalue;
218     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:executable", pool));
219     int mode = 0100644;
220     if (propvalue)
221         mode = 0100755;
222
223     // maybe it's a symlink?
224     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:special", pool));
225     if (propvalue && strcmp(propvalue->data, "symlink") == 0)
226         mode = 0120000;
227
228     return mode;
229 }
230
231 svn_error_t *QIODevice_write(void *baton, const char *data, apr_size_t *len)
232 {
233     QIODevice *device = reinterpret_cast<QIODevice *>(baton);
234     device->write(data, *len);
235
236     while (device->bytesToWrite() > 32*1024) {
237         if (!device->waitForBytesWritten(-1)) {
238             qFatal("Failed to write to process: %s", qPrintable(device->errorString()));
239             return svn_error_createf(APR_EOF, SVN_NO_ERROR, "Failed to write to process: %s",
240                                      qPrintable(device->errorString()));
241         }
242     }
243     return SVN_NO_ERROR;
244 }
245
246 static svn_stream_t *streamForDevice(QIODevice *device, apr_pool_t *pool)
247 {
248     svn_stream_t *stream = svn_stream_create(device, pool);
249     svn_stream_set_write(stream, QIODevice_write);
250
251     return stream;
252 }
253
254 static int dumpBlob(Repository::Transaction *txn, svn_fs_root_t *fs_root,
255                     const char *pathname, const QString &finalPathName, apr_pool_t *pool)
256 {
257     AprAutoPool dumppool(pool);
258     // what type is it?
259     int mode = pathMode(fs_root, pathname, dumppool);
260
261     svn_filesize_t stream_length;
262
263     SVN_ERR(svn_fs_file_length(&stream_length, fs_root, pathname, dumppool));
264     QIODevice *io = txn->addFile(finalPathName, mode, stream_length);
265
266 #ifndef DRY_RUN
267     // open the file
268     svn_stream_t *in_stream, *out_stream;
269     SVN_ERR(svn_fs_file_contents(&in_stream, fs_root, pathname, dumppool));
270
271     // open a generic svn_stream_t for the QIODevice
272     out_stream = streamForDevice(io, dumppool);
273     SVN_ERR(svn_stream_copy(in_stream, out_stream, dumppool));
274
275     // print an ending newline
276     io->putChar('\n');
277 #endif
278
279     return EXIT_SUCCESS;
280 }
281
282 static int recursiveDumpDir(Repository::Transaction *txn, svn_fs_root_t *fs_root,
283                             const QByteArray &pathname, const QString &finalPathName,
284                             apr_pool_t *pool)
285 {
286     // get the dir listing
287     apr_hash_t *entries;
288     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, pathname, pool));
289     AprAutoPool dirpool(pool);
290
291     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
292         dirpool.clear();
293         const void *vkey;
294         void *value;
295         apr_hash_this(i, &vkey, NULL, &value);
296
297         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
298         QByteArray entryName = pathname + '/' + dirent->name;
299         QString entryFinalName = finalPathName + dirent->name;
300
301         if (dirent->kind == svn_node_dir) {
302             entryFinalName += '/';
303             if (recursiveDumpDir(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
304                 return EXIT_FAILURE;
305         } else if (dirent->kind == svn_node_file) {
306             printf("+");
307             fflush(stdout);
308             if (dumpBlob(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
309                 return EXIT_FAILURE;
310         }
311     }
312
313     return EXIT_SUCCESS;
314 }
315
316 static bool wasDir(svn_fs_t *fs, int revnum, const char *pathname, apr_pool_t *pool)
317 {
318     AprAutoPool subpool(pool);
319     svn_fs_root_t *fs_root;
320     if (svn_fs_revision_root(&fs_root, fs, revnum, subpool) != SVN_NO_ERROR)
321         return false;
322
323     svn_boolean_t is_dir;
324     if (svn_fs_is_dir(&is_dir, fs_root, pathname, subpool) != SVN_NO_ERROR)
325         return false;
326
327     return is_dir;
328 }
329
330 time_t get_epoch(char *svn_date)
331 {
332     struct tm tm;
333     memset(&tm, 0, sizeof tm);
334     QByteArray date(svn_date, strlen(svn_date) - 8);
335     strptime(date, "%Y-%m-%dT%H:%M:%S", &tm);
336     return mktime(&tm);
337 }
338
339 class SvnRevision
340 {
341 public:
342     AprAutoPool pool;
343     QHash<QString, Repository::Transaction *> transactions;
344     MatchRuleList matchRules;
345     RepositoryHash repositories;
346     IdentityHash identities;
347
348     svn_fs_t *fs;
349     svn_fs_root_t *fs_root;
350     int revnum;
351
352     SvnRevision(int revision, svn_fs_t *f, apr_pool_t *parent_pool)
353         : pool(parent_pool), fs(f), fs_root(0), revnum(revision)
354     {
355     }
356
357     int open()
358     {
359         SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum, pool));
360         return EXIT_SUCCESS;
361     }
362
363     int prepareTransactions();
364     int commit();
365
366     int exportEntry(const char *path, const svn_fs_path_change_t *change, apr_hash_t *changes);
367     int exportDispatch(const char *path, const svn_fs_path_change_t *change,
368                        const char *path_from, svn_revnum_t rev_from,
369                        apr_hash_t *changes, const QString &current, const Rules::Match &rule,
370                        apr_pool_t *pool);
371     int exportInternal(const char *path, const svn_fs_path_change_t *change,
372                        const char *path_from, svn_revnum_t rev_from,
373                        const QString &current, const Rules::Match &rule);
374     int recurse(const char *path, const svn_fs_path_change_t *change,
375                 const char *path_from, svn_revnum_t rev_from,
376                 apr_hash_t *changes, apr_pool_t *pool);
377 };
378
379 int SvnPrivate::exportRevision(int revnum)
380 {
381     SvnRevision rev(revnum, fs, global_pool);
382     rev.matchRules = matchRules;
383     rev.repositories = repositories;
384     rev.identities = identities;
385
386     // open this revision:
387     printf("Exporting revision %d ", revnum);
388     fflush(stdout);
389
390     if (rev.open() == EXIT_FAILURE)
391         return EXIT_FAILURE;
392
393     if (rev.prepareTransactions() == EXIT_FAILURE)
394         return EXIT_FAILURE;
395
396     if (rev.transactions.isEmpty()) {
397         printf(" nothing to do\n");
398         return EXIT_SUCCESS;    // no changes?
399     }
400
401     if (rev.commit() == EXIT_FAILURE)
402         return EXIT_FAILURE;
403
404     printf(" done\n");
405     return EXIT_SUCCESS;
406 }
407
408 int SvnRevision::prepareTransactions()
409 {
410     // find out what was changed in this revision:
411     apr_hash_t *changes;
412     SVN_ERR(svn_fs_paths_changed(&changes, fs_root, pool));
413     for (apr_hash_index_t *i = apr_hash_first(pool, changes); i; i = apr_hash_next(i)) {
414         const void *vkey;
415         void *value;
416         apr_hash_this(i, &vkey, NULL, &value);
417         const char *key = reinterpret_cast<const char *>(vkey);
418         svn_fs_path_change_t *change = reinterpret_cast<svn_fs_path_change_t *>(value);
419
420         if (exportEntry(key, change, changes) == EXIT_FAILURE)
421             return EXIT_FAILURE;
422     }
423
424     return EXIT_SUCCESS;
425 }
426
427 int SvnRevision::commit()
428 {
429     // now create the commit
430     apr_hash_t *revprops;
431     SVN_ERR(svn_fs_revision_proplist(&revprops, fs, revnum, pool));
432     svn_string_t *svnauthor = (svn_string_t*)apr_hash_get(revprops, "svn:author", APR_HASH_KEY_STRING);
433     svn_string_t *svndate = (svn_string_t*)apr_hash_get(revprops, "svn:date", APR_HASH_KEY_STRING);
434     svn_string_t *svnlog = (svn_string_t*)apr_hash_get(revprops, "svn:log", APR_HASH_KEY_STRING);
435
436     QByteArray log = (char *)svnlog->data;
437     QByteArray authorident = svnauthor ? identities.value((char *)svnauthor->data) : QByteArray();
438     time_t epoch = get_epoch((char*)svndate->data);
439     if (authorident.isEmpty()) {
440         if (!svnauthor || svn_string_isempty(svnauthor))
441             authorident = "nobody <nobody@localhost>";
442         else
443             authorident = svnauthor->data + QByteArray(" <") +
444                           svnauthor->data + QByteArray("@localhost>");
445     }
446
447     foreach (Repository::Transaction *txn, transactions) {
448         txn->setAuthor(authorident);
449         txn->setDateTime(epoch);
450         txn->setLog(log);
451
452         txn->commit();
453         delete txn;
454     }
455
456     return EXIT_SUCCESS;
457 }
458
459 int SvnRevision::exportEntry(const char *key, const svn_fs_path_change_t *change,
460                              apr_hash_t *changes)
461 {
462     AprAutoPool revpool(pool.data());
463     QString current = QString::fromUtf8(key);
464
465     // was this copied from somewhere?
466     svn_revnum_t rev_from;
467     const char *path_from;
468     SVN_ERR(svn_fs_copied_from(&rev_from, &path_from, fs_root, key, revpool));
469
470     // is this a directory?
471     svn_boolean_t is_dir;
472     SVN_ERR(svn_fs_is_dir(&is_dir, fs_root, key, revpool));
473     if (is_dir) {
474         if (path_from == NULL) {
475             // no, it's a new directory being added
476             // Git doesn't handle directories, so we don't either
477             //qDebug() << "   mkdir ignored:" << key;
478             return EXIT_SUCCESS;
479         }
480
481         current += '/';
482         qDebug() << "   " << key << "was copied from" << path_from << "rev" << rev_from;
483     }
484
485     // find the first rule that matches this pathname
486     MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current);
487     if (match != matchRules.constEnd()) {
488         const Rules::Match &rule = *match;
489         return exportDispatch(key, change, path_from, rev_from, changes, current, rule, revpool);
490     }
491
492     if (is_dir && path_from != NULL) {
493         qDebug() << current << "is a copy-with-history, auto-recursing";
494         return recurse(key, change, path_from, rev_from, changes, revpool);
495     } else if (wasDir(fs, revnum - 1, key, revpool)) {
496         qDebug() << current << "was a directory; ignoring";
497     } else if (change->change_kind == svn_fs_path_change_delete) {
498         qDebug() << current << "is being deleted but I don't know anything about it; ignoring";
499     } else {
500         qCritical() << current << "did not match any rules; cannot continue";
501         return EXIT_FAILURE;
502     }
503
504     return EXIT_SUCCESS;
505 }
506
507 int SvnRevision::exportDispatch(const char *key, const svn_fs_path_change_t *change,
508                                 const char *path_from, svn_revnum_t rev_from,
509                                 apr_hash_t *changes, const QString &current,
510                                 const Rules::Match &rule, apr_pool_t *pool)
511 {
512     switch (rule.action) {
513     case Rules::Match::Ignore:
514         // ignore rule
515         //qDebug() << "   " << qPrintable(current) << "rev" << revnum
516         //         << "-> ignored (rule" << rule << ")";
517         return EXIT_SUCCESS;
518
519     case Rules::Match::Recurse:
520         return recurse(key, change, path_from, rev_from, changes, pool);
521
522     case Rules::Match::Export:
523         return exportInternal(key, change, path_from, rev_from, current, rule);
524     }
525
526     // never reached
527     return EXIT_FAILURE;
528 }
529
530 int SvnRevision::exportInternal(const char *key, const svn_fs_path_change_t *change,
531                                 const char *path_from, svn_revnum_t rev_from,
532                                 const QString &current, const Rules::Match &rule)
533 {
534     QString svnprefix, repository, branch, path;
535     splitPathName(rule, current, &svnprefix, &repository, &branch, &path);
536
537     printf(".");
538     fflush(stdout);
539 //                qDebug() << "   " << qPrintable(current) << "rev" << revnum << "->"
540 //                         << qPrintable(repository) << qPrintable(branch) << qPrintable(path);
541
542     if (path.isEmpty() && path_from != NULL) {
543         QString previous = QString::fromUtf8(path_from) + '/';
544         MatchRuleList::ConstIterator prevmatch =
545             findMatchRule(matchRules, rev_from, previous, NoIgnoreRule);
546         if (prevmatch != matchRules.constEnd()) {
547             QString prevsvnprefix, prevrepository, prevbranch, prevpath;
548             splitPathName(*prevmatch, previous, &prevsvnprefix, &prevrepository,
549                           &prevbranch, &prevpath);
550
551             if (!prevpath.isEmpty()) {
552                 qDebug() << qPrintable(current) << "is a partial branch of repository"
553                          << qPrintable(prevrepository) << "branch"
554                          << qPrintable(prevbranch) << "subdir"
555                          << qPrintable(prevpath);
556             } else if (prevrepository != repository) {
557                 qWarning() << qPrintable(current) << "rev" << revnum
558                            << "is a cross-repository copy (from repository"
559                            << qPrintable(prevrepository) << "branch"
560                            << qPrintable(prevbranch) << "path"
561                            << qPrintable(prevpath) << "rev" << rev_from << ")";
562             } else if (prevbranch == branch) {
563                 // same branch and same repository
564                 qDebug() << qPrintable(current) << "rev" << revnum
565                          << "is an SVN rename from"
566                          << qPrintable(previous) << "rev" << rev_from;
567                 return EXIT_SUCCESS;
568             } else {
569                 // same repository but not same branch
570                 // this means this is a plain branch
571                 qDebug() << qPrintable(repository) << ": branch"
572                          << qPrintable(branch) << "is branching from"
573                          << qPrintable(prevbranch);
574
575                 Repository *repo = repositories.value(repository, 0);
576                 if (!repo) {
577                     qCritical() << "Rule" << rule
578                                 << "references unknown repository" << repository;
579                     return EXIT_FAILURE;
580                 }
581
582                 repo->createBranch(branch, revnum, prevbranch, rev_from);
583                 return EXIT_SUCCESS;
584             }
585         }
586     }
587
588     Repository::Transaction *txn = transactions.value(repository + branch, 0);
589     if (!txn) {
590         Repository *repo = repositories.value(repository, 0);
591         if (!repo) {
592             qCritical() << "Rule" << rule
593                         << "references unknown repository" << repository;
594             return EXIT_FAILURE;
595         }
596
597         txn = repo->newTransaction(branch, svnprefix, revnum);
598         if (!txn)
599             return EXIT_FAILURE;
600
601         transactions.insert(repository + branch, txn);
602     }
603
604     if (change->change_kind == svn_fs_path_change_delete) {
605         txn->deleteFile(path);
606     } else if (!current.endsWith('/')) {
607         dumpBlob(txn, fs_root, key, path, pool);
608     } else {
609         QString pathNoSlash = path;
610         pathNoSlash.chop(1);
611         txn->deleteFile(pathNoSlash);
612         recursiveDumpDir(txn, fs_root, key, path, pool);
613     }
614
615     return EXIT_SUCCESS;
616 }
617
618 int SvnRevision::recurse(const char *path, const svn_fs_path_change_t *change,
619                          const char *path_from, svn_revnum_t rev_from,
620                          apr_hash_t *changes, apr_pool_t *pool)
621 {
622     // get the dir listing
623     apr_hash_t *entries;
624     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, path, pool));
625
626     AprAutoPool dirpool(pool);
627     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
628         dirpool.clear();
629         const void *vkey;
630         void *value;
631         apr_hash_this(i, &vkey, NULL, &value);
632
633         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
634         if (dirent->kind != svn_node_dir)
635             continue;           // not a directory, so can't recurse; skip
636
637         QByteArray entry = path + QByteArray("/") + dirent->name;
638         QByteArray entryFrom;
639         if (path_from)
640             entryFrom = path_from + QByteArray("/") + dirent->name;
641
642         // check if this entry is in the changelist for this revision already
643         if (apr_hash_get(changes, entry.constData(), APR_HASH_KEY_STRING)) {
644             qDebug() << entry << "rev" << revnum
645                      << "is in the change-list, deferring to that one";
646             continue;
647         }
648
649         QString current = QString::fromUtf8(entry);
650         if (dirent->kind == svn_node_dir)
651             current += '/';
652
653         // find the first rule that matches this pathname
654         MatchRuleList::ConstIterator match = findMatchRule(matchRules, revnum, current);
655         if (match != matchRules.constEnd()) {
656             if (exportDispatch(entry, change, entryFrom.isNull() ? 0 : entryFrom.constData(),
657                                rev_from, changes, current, *match, dirpool) == EXIT_FAILURE)
658                 return EXIT_FAILURE;
659         } else {
660             qCritical() << current << "rev" << revnum
661                         << "did not match any rules; cannot continue";
662             return EXIT_FAILURE;
663         }
664     }
665
666     return EXIT_SUCCESS;
667 }
This page took 0.086696 seconds and 3 git commands to generate.