Add some more line number information
[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 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 static int pathMode(svn_fs_root_t *fs_root, const char *pathname, apr_pool_t *pool)
164 {
165     svn_string_t *propvalue;
166     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:executable", pool));
167     int mode = 0100644;
168     if (propvalue)
169         mode = 0100755;
170
171     // maybe it's a symlink?
172     SVN_ERR(svn_fs_node_prop(&propvalue, fs_root, pathname, "svn:special", pool));
173     if (propvalue && strcmp(propvalue->data, "symlink") == 0)
174         mode = 0120000;
175
176     return mode;
177 }
178
179 svn_error_t *QIODevice_write(void *baton, const char *data, apr_size_t *len)
180 {
181     QIODevice *device = reinterpret_cast<QIODevice *>(baton);
182     device->write(data, *len);
183
184     if (device->bytesToWrite() > 16384)
185         device->waitForBytesWritten(0);
186     return SVN_NO_ERROR;
187 }
188
189 static svn_stream_t *streamForDevice(QIODevice *device, apr_pool_t *pool)
190 {
191     svn_stream_t *stream = svn_stream_create(device, pool);
192     svn_stream_set_write(stream, QIODevice_write);
193
194     return stream;
195 }
196
197 static int dumpBlob(Repository::Transaction *txn, svn_fs_root_t *fs_root,
198                     const char *pathname, const QString &finalPathName, apr_pool_t *pool)
199 {
200     // what type is it?
201     int mode = pathMode(fs_root, pathname, pool);
202
203     svn_filesize_t stream_length;
204
205     SVN_ERR(svn_fs_file_length(&stream_length, fs_root, pathname, pool));
206     QIODevice *io = txn->addFile(finalPathName, mode, stream_length);
207
208 #ifndef DRY_RUN
209     // open the file
210     svn_stream_t *in_stream, *out_stream;
211     SVN_ERR(svn_fs_file_contents(&in_stream, fs_root, pathname, pool));
212
213     // open a generic svn_stream_t for the QIODevice
214     out_stream = streamForDevice(io, pool);
215     SVN_ERR(svn_stream_copy(in_stream, out_stream, pool));
216
217     // print an ending newline
218     io->putChar('\n');
219 #endif
220
221     return EXIT_SUCCESS;
222 }
223
224 static int recursiveDumpDir(Repository::Transaction *txn, svn_fs_root_t *fs_root,
225                             const QByteArray &pathname, const QString &finalPathName,
226                             apr_pool_t *pool)
227 {
228     // get the dir listing
229     apr_hash_t *entries;
230     SVN_ERR(svn_fs_dir_entries(&entries, fs_root, pathname, pool));
231     AprAutoPool dirpool(pool);
232
233     for (apr_hash_index_t *i = apr_hash_first(pool, entries); i; i = apr_hash_next(i)) {
234         dirpool.clear();
235         const void *vkey;
236         void *value;
237         apr_hash_this(i, &vkey, NULL, &value);
238
239         svn_fs_dirent_t *dirent = reinterpret_cast<svn_fs_dirent_t *>(value);
240         QByteArray entryName = pathname + '/' + dirent->name;
241         QString entryFinalName = finalPathName + '/' + dirent->name;
242
243         if (dirent->kind == svn_node_dir) {
244             if (recursiveDumpDir(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
245                 return EXIT_FAILURE;
246         } else if (dirent->kind == svn_node_file) {
247             if (dumpBlob(txn, fs_root, entryName, entryFinalName, dirpool) == EXIT_FAILURE)
248                 return EXIT_FAILURE;
249         }
250     }
251 }
252
253 static bool wasDir(svn_fs_t *fs, int revnum, const char *pathname, apr_pool_t *pool)
254 {
255     AprAutoPool subpool(pool);
256     svn_fs_root_t *fs_root;
257     if (svn_fs_revision_root(&fs_root, fs, revnum, subpool) != SVN_NO_ERROR)
258         return false;
259
260     svn_boolean_t is_dir;
261     if (svn_fs_is_dir(&is_dir, fs_root, pathname, subpool) != SVN_NO_ERROR)
262         return false;
263
264     return is_dir;
265 }
266
267 time_t get_epoch(char *svn_date)
268 {
269     struct tm tm;
270     memset(&tm, 0, sizeof tm);
271     QByteArray date(svn_date, strlen(svn_date) - 8);
272     strptime(date, "%Y-%m-%dT%H:%M:%S", &tm);
273     return mktime(&tm);
274 }
275
276 int SvnPrivate::exportRevision(int revnum)
277 {
278     AprAutoPool pool(global_pool.data());
279
280     // open this revision:
281     qDebug() << "Exporting revision" << revnum;
282     svn_fs_root_t *fs_root;
283     SVN_ERR(svn_fs_revision_root(&fs_root, fs, revnum, pool));
284
285     // find out what was changed in this revision:
286     QHash<QString, Repository::Transaction *> transactions;
287     apr_hash_t *changes;
288     SVN_ERR(svn_fs_paths_changed(&changes, fs_root, pool));
289     AprAutoPool revpool(pool.data());
290     for (apr_hash_index_t *i = apr_hash_first(pool, changes); i; i = apr_hash_next(i)) {
291         revpool.clear();
292
293         const void *vkey;
294         void *value;
295         apr_hash_this(i, &vkey, NULL, &value);
296         const char *key = reinterpret_cast<const char *>(vkey);
297
298         // is this a directory?
299         svn_boolean_t is_dir;
300         SVN_ERR(svn_fs_is_dir(&is_dir, fs_root, key, revpool));
301         if (is_dir) {
302             // was this directory copied from somewhere?
303             svn_revnum_t rev_from;
304             const char *path_from;
305             SVN_ERR(svn_fs_copied_from(&rev_from, &path_from, fs_root, key, revpool));
306
307             if (path_from == NULL)
308                 // no, it's a new directory being added
309                 // Git doesn't handle directories, so we don't either
310                 continue;
311
312             qDebug() << "..." << key << "was copied from" << path_from;
313         }
314
315         QString current = QString::fromUtf8(key);
316
317         // find the first rule that matches this pathname
318         bool foundMatch = false;
319         foreach (Rules::Match rule, matchRules) {
320             if (rule.minRevision > revnum)
321                 continue;
322             if (rule.maxRevision != -1 && rule.maxRevision < revnum)
323                 continue;
324             if (rule.rx.exactMatch(current)) {
325                 foundMatch = true;
326                 if (rule.repository.isEmpty()) {
327                     // ignore rule
328                     qDebug() << "..." << qPrintable(current) << "rev" << revnum
329                              << "-> ignored";
330                     break;
331                 }
332
333                 QString repository = current;
334                 QString branch = current;
335                 QString path = current;
336
337                 // do the replacement
338                 repository.replace(rule.rx, rule.repository);
339                 branch.replace(rule.rx, rule.branch);
340                 path.replace(rule.rx, rule.path);
341
342                 qDebug() << "..." << qPrintable(current) << "rev" << revnum << "->"
343                          << qPrintable(repository) << qPrintable(branch) << qPrintable(path);
344
345                 Repository::Transaction *txn = transactions.value(repository, 0);
346                 if (!txn) {
347                     Repository *repo = repositories.value(repository, 0);
348                     if (!repo) {
349                         qCritical() << "Rule" << rule.rx.pattern() << "line" << rule.lineNumber
350                                     << "references unknown repository" << repository;
351                         return EXIT_FAILURE;
352                     }
353
354                     QString svnprefix = current;
355                     if (svnprefix.endsWith(path))
356                         svnprefix.chop(path.length());
357
358                     txn = repo->newTransaction(branch, svnprefix, revnum);
359                     if (!txn)
360                         return EXIT_FAILURE;
361
362                     transactions.insert(repository, txn);
363                 }
364
365                 svn_fs_path_change_t *change = reinterpret_cast<svn_fs_path_change_t *>(value);
366                 if (change->change_kind == svn_fs_path_change_delete)
367                     txn->deleteFile(path);
368                 else if (!is_dir)
369                     dumpBlob(txn, fs_root, key, path, revpool);
370                 else
371                     recursiveDumpDir(txn, fs_root, key, path, revpool);
372
373                 break;
374             }
375         }
376
377         if (!foundMatch) {
378             if (is_dir) {
379                 qDebug() << current << "is a directory; ignoring";
380             } else if (wasDir(fs, revnum - 1, key, pool)) {
381                 qDebug() << current << "was a directory; ignoring";
382             } else {
383                 qCritical() << current << "did not match any rules; cannot continue";
384                 return EXIT_FAILURE;
385             }
386         }
387     }
388     revpool.clear();
389
390     if (transactions.isEmpty())
391         return EXIT_SUCCESS;    // no changes?
392
393     // now create the commit
394     apr_hash_t *revprops;
395     SVN_ERR(svn_fs_revision_proplist(&revprops, fs, revnum, pool));
396     svn_string_t *svnauthor = (svn_string_t*)apr_hash_get(revprops, "svn:author", APR_HASH_KEY_STRING);
397     svn_string_t *svndate = (svn_string_t*)apr_hash_get(revprops, "svn:date", APR_HASH_KEY_STRING);
398     svn_string_t *svnlog = (svn_string_t*)apr_hash_get(revprops, "svn:log", APR_HASH_KEY_STRING);
399
400     QByteArray log = (char *)svnlog->data;
401     QByteArray authorident = identities.value((char *)svnauthor->data);
402     time_t epoch = get_epoch((char*)svndate->data);
403     if (authorident.isEmpty()) {
404         if (!svnauthor || svn_string_isempty(svnauthor))
405             authorident = "nobody <nobody@localhost>";
406         else
407             authorident = svnauthor->data + QByteArray(" <") +
408                           svnauthor->data + QByteArray("@localhost>");
409     }
410
411     foreach (Repository::Transaction *txn, transactions) {
412         txn->setAuthor(authorident);
413         txn->setDateTime(epoch);
414         txn->setLog(log);
415
416         txn->commit();
417         delete txn;
418     }
419
420     return EXIT_SUCCESS;
421 }