OSDN Git Service

git-svn: bugfix: allow SVN:: lib users to track the root of the repository
[git-core/git.git] / git-svn.perl
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/    $AUTHOR $VERSION
7                 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8                 $GIT_SVN_INDEX $GIT_SVN
9                 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
12
13 use Cwd qw/abs_path/;
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
16
17 my $LC_ALL = $ENV{LC_ALL};
18 my $TZ = $ENV{TZ};
19 # make sure the svn binary gives consistent output between locales and TZs:
20 $ENV{TZ} = 'UTC';
21 $ENV{LC_ALL} = 'C';
22 $| = 1; # unbuffer STDOUT
23
24 # If SVN:: library support is added, please make the dependencies
25 # optional and preserve the capability to use the command-line client.
26 # use eval { require SVN::... } to make it lazy load
27 # We don't use any modules not in the standard Perl distribution:
28 use Carp qw/croak/;
29 use IO::File qw//;
30 use File::Basename qw/dirname basename/;
31 use File::Path qw/mkpath/;
32 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
33 use File::Spec qw//;
34 use File::Copy qw/copy/;
35 use POSIX qw/strftime/;
36 use IPC::Open3;
37 use Memoize;
38 memoize('revisions_eq');
39 memoize('cmt_metadata');
40 memoize('get_commit_time');
41
42 my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
43 $_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
44 libsvn_load();
45 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
46 my $sha1 = qr/[a-f\d]{40}/;
47 my $sha1_short = qr/[a-f\d]{4,40}/;
48 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
49         $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
50         $_repack, $_repack_nr, $_repack_flags, $_q,
51         $_message, $_file, $_follow_parent, $_no_metadata,
52         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
53         $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
54         $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
55 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
56 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
57 my @repo_path_split_cache;
58
59 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
60                 'branch|b=s' => \@_branch_from,
61                 'follow-parent|follow' => \$_follow_parent,
62                 'branch-all-refs|B' => \$_branch_all_refs,
63                 'authors-file|A=s' => \$_authors,
64                 'repack:i' => \$_repack,
65                 'no-metadata' => \$_no_metadata,
66                 'quiet|q' => \$_q,
67                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
68
69 my ($_trunk, $_tags, $_branches);
70 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
71                 'tags|t=s' => \$_tags,
72                 'branches|b=s' => \$_branches );
73 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
74 my %cmt_opts = ( 'edit|e' => \$_edit,
75                 'rmdir' => \$_rmdir,
76                 'find-copies-harder' => \$_find_copies_harder,
77                 'l=i' => \$_l,
78                 'copy-similarity|C=i'=> \$_cp_similarity
79 );
80
81 my %cmd = (
82         fetch => [ \&fetch, "Download new revisions from SVN",
83                         { 'revision|r=s' => \$_revision, %fc_opts } ],
84         init => [ \&init, "Initialize a repo for tracking" .
85                           " (requires URL argument)",
86                           \%init_opts ],
87         commit => [ \&commit, "Commit git revisions to SVN",
88                         {       'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
89         'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
90                         { 'revision|r=i' => \$_revision } ],
91         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
92                         { 'no-ignore-externals' => \$_no_ignore_ext,
93                           'copy-remote|remote=s' => \$_cp_remote,
94                           'upgrade' => \$_upgrade } ],
95         'graft-branches' => [ \&graft_branches,
96                         'Detect merges/branches from already imported history',
97                         { 'merge-rx|m' => \@_opt_m,
98                           'branch|b=s' => \@_branch_from,
99                           'branch-all-refs|B' => \$_branch_all_refs,
100                           'no-default-regex' => \$_no_default_regex,
101                           'no-graft-copy' => \$_no_graft_copy } ],
102         'multi-init' => [ \&multi_init,
103                         'Initialize multiple trees (like git-svnimport)',
104                         { %multi_opts, %fc_opts } ],
105         'multi-fetch' => [ \&multi_fetch,
106                         'Fetch multiple trees (like git-svnimport)',
107                         \%fc_opts ],
108         'log' => [ \&show_log, 'Show commit logs',
109                         { 'limit=i' => \$_limit,
110                           'revision|r=s' => \$_revision,
111                           'verbose|v' => \$_verbose,
112                           'incremental' => \$_incremental,
113                           'oneline' => \$_oneline,
114                           'show-commit' => \$_show_commit,
115                           'authors-file|A=s' => \$_authors,
116                         } ],
117         'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
118                         { 'message|m=s' => \$_message,
119                           'file|F=s' => \$_file,
120                         %cmt_opts } ],
121 );
122
123 my $cmd;
124 for (my $i = 0; $i < @ARGV; $i++) {
125         if (defined $cmd{$ARGV[$i]}) {
126                 $cmd = $ARGV[$i];
127                 splice @ARGV, $i, 1;
128                 last;
129         }
130 };
131
132 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
133
134 read_repo_config(\%opts);
135 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
136                                 'version|V' => \$_version,
137                                 'id|i=s' => \$GIT_SVN);
138 exit 1 if (!$rv && $cmd ne 'log');
139
140 set_default_vals();
141 usage(0) if $_help;
142 version() if $_version;
143 usage(1) unless defined $cmd;
144 init_vars();
145 load_authors() if $_authors;
146 load_all_refs() if $_branch_all_refs;
147 svn_compat_check() unless $_use_lib;
148 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
149 $cmd{$cmd}->[0]->(@ARGV);
150 exit 0;
151
152 ####################### primary functions ######################
153 sub usage {
154         my $exit = shift || 0;
155         my $fd = $exit ? \*STDERR : \*STDOUT;
156         print $fd <<"";
157 git-svn - bidirectional operations between a single Subversion tree and git
158 Usage: $0 <command> [options] [arguments]\n
159
160         print $fd "Available commands:\n" unless $cmd;
161
162         foreach (sort keys %cmd) {
163                 next if $cmd && $cmd ne $_;
164                 print $fd '  ',pack('A13',$_),$cmd{$_}->[1],"\n";
165                 foreach (keys %{$cmd{$_}->[2]}) {
166                         # prints out arguments as they should be passed:
167                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
168                         print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
169                                                         "--$_" : "-$_" }
170                                                 split /\|/,$_)," $x\n";
171                 }
172         }
173         print $fd <<"";
174 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
175 arbitrary identifier if you're tracking multiple SVN branches/repositories in
176 one git repository and want to keep them separate.  See git-svn(1) for more
177 information.
178
179         exit $exit;
180 }
181
182 sub version {
183         print "git-svn version $VERSION\n";
184         exit 0;
185 }
186
187 sub rebuild {
188         if (quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0")) {
189                 copy_remote_ref();
190         }
191         $SVN_URL = shift or undef;
192         my $newest_rev = 0;
193         if ($_upgrade) {
194                 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
195         } else {
196                 check_upgrade_needed();
197         }
198
199         my $pid = open(my $rev_list,'-|');
200         defined $pid or croak $!;
201         if ($pid == 0) {
202                 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
203         }
204         my $latest;
205         while (<$rev_list>) {
206                 chomp;
207                 my $c = $_;
208                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
209                 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
210                 next if (!@commit); # skip merges
211                 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
212                 if (!$rev || !$uuid) {
213                         croak "Unable to extract revision or UUID from ",
214                                 "$c, $commit[$#commit]\n";
215                 }
216
217                 # if we merged or otherwise started elsewhere, this is
218                 # how we break out of it
219                 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
220                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
221
222                 unless (defined $latest) {
223                         if (!$SVN_URL && !$url) {
224                                 croak "SVN repository location required: $url\n";
225                         }
226                         $SVN_URL ||= $url;
227                         $SVN_UUID ||= $uuid;
228                         setup_git_svn();
229                         $latest = $rev;
230                 }
231                 revdb_set($REVDB, $rev, $c);
232                 print "r$rev = $c\n";
233                 $newest_rev = $rev if ($rev > $newest_rev);
234         }
235         close $rev_list or croak $?;
236
237         goto out if $_use_lib;
238         if (!chdir $SVN_WC) {
239                 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
240                 chdir $SVN_WC or croak $!;
241         }
242
243         $pid = fork;
244         defined $pid or croak $!;
245         if ($pid == 0) {
246                 my @svn_up = qw(svn up);
247                 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
248                 sys(@svn_up,"-r$newest_rev");
249                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
250                 index_changes();
251                 exec('git-write-tree') or croak $!;
252         }
253         waitpid $pid, 0;
254         croak $? if $?;
255 out:
256         if ($_upgrade) {
257                 print STDERR <<"";
258 Keeping deprecated refs/head/$GIT_SVN-HEAD for now.  Please remove it
259 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
260
261         }
262 }
263
264 sub init {
265         my $url = shift or die "SVN repository location required " .
266                                 "as a command-line argument\n";
267         $url =~ s!/+$!!; # strip trailing slash
268
269         if (my $repo_path = shift) {
270                 unless (-d $repo_path) {
271                         mkpath([$repo_path]);
272                 }
273                 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
274                 init_vars();
275         }
276
277         $SVN_URL = $url;
278         unless (-d $GIT_DIR) {
279                 my @init_db = ('git-init-db');
280                 push @init_db, "--template=$_template" if defined $_template;
281                 push @init_db, "--shared" if defined $_shared;
282                 sys(@init_db);
283         }
284         setup_git_svn();
285 }
286
287 sub fetch {
288         check_upgrade_needed();
289         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
290         my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
291         if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
292                                                 refs/heads/master^0))) {
293                 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
294         }
295         return $ret;
296 }
297
298 sub fetch_cmd {
299         my (@parents) = @_;
300         my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
301         unless ($_revision) {
302                 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
303         }
304         push @log_args, "-r$_revision";
305         push @log_args, '--stop-on-copy' unless $_no_stop_copy;
306
307         my $svn_log = svn_log_raw(@log_args);
308
309         my $base = next_log_entry($svn_log) or croak "No base revision!\n";
310         # don't need last_revision from grab_base_rev() because
311         # user could've specified a different revision to skip (they
312         # didn't want to import certain revisions into git for whatever
313         # reason, so trust $base->{revision} instead.
314         my (undef, $last_commit) = svn_grab_base_rev();
315         unless (-d $SVN_WC) {
316                 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
317                 chdir $SVN_WC or croak $!;
318                 read_uuid();
319                 $last_commit = git_commit($base, @parents);
320                 assert_tree($last_commit);
321         } else {
322                 chdir $SVN_WC or croak $!;
323                 read_uuid();
324                 # looks like a user manually cp'd and svn switch'ed
325                 unless ($last_commit) {
326                         sys(qw/svn revert -R ./);
327                         assert_svn_wc_clean($base->{revision});
328                         $last_commit = git_commit($base, @parents);
329                         assert_tree($last_commit);
330                 }
331         }
332         my @svn_up = qw(svn up);
333         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
334         my $last = $base;
335         while (my $log_msg = next_log_entry($svn_log)) {
336                 if ($last->{revision} >= $log_msg->{revision}) {
337                         croak "Out of order: last >= current: ",
338                                 "$last->{revision} >= $log_msg->{revision}\n";
339                 }
340                 # Revert is needed for cases like:
341                 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
342                 # I can't seem to reproduce something like that on a test...
343                 sys(qw/svn revert -R ./);
344                 assert_svn_wc_clean($last->{revision});
345                 sys(@svn_up,"-r$log_msg->{revision}");
346                 $last_commit = git_commit($log_msg, $last_commit, @parents);
347                 $last = $log_msg;
348         }
349         close $svn_log->{fh};
350         $last->{commit} = $last_commit;
351         return $last;
352 }
353
354 sub fetch_lib {
355         my (@parents) = @_;
356         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
357         my $repo;
358         ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
359         $SVN_LOG ||= libsvn_connect($repo);
360         $SVN ||= libsvn_connect($repo);
361         my ($last_rev, $last_commit) = svn_grab_base_rev();
362         my ($base, $head) = libsvn_parse_revision($last_rev);
363         if ($base > $head) {
364                 return { revision => $last_rev, commit => $last_commit }
365         }
366         my $index = set_index($GIT_SVN_INDEX);
367
368         # limit ourselves and also fork() since get_log won't release memory
369         # after processing a revision and SVN stuff seems to leak
370         my $inc = 1000;
371         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
372         read_uuid();
373         if (defined $last_commit) {
374                 unless (-e $GIT_SVN_INDEX) {
375                         sys(qw/git-read-tree/, $last_commit);
376                 }
377                 chomp (my $x = `git-write-tree`);
378                 my ($y) = (`git-cat-file commit $last_commit`
379                                                         =~ /^tree ($sha1)/m);
380                 if ($y ne $x) {
381                         unlink $GIT_SVN_INDEX or croak $!;
382                         sys(qw/git-read-tree/, $last_commit);
383                 }
384                 chomp ($x = `git-write-tree`);
385                 if ($y ne $x) {
386                         print STDERR "trees ($last_commit) $y != $x\n",
387                                  "Something is seriously wrong...\n";
388                 }
389         }
390         while (1) {
391                 # fork, because using SVN::Pool with get_log() still doesn't
392                 # seem to help enough to keep memory usage down.
393                 defined(my $pid = fork) or croak $!;
394                 if (!$pid) {
395                         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
396
397                         # Yes I'm perfectly aware that the fourth argument
398                         # below is the limit revisions number.  Unfortunately
399                         # performance sucks with it enabled, so it's much
400                         # faster to fetch revision ranges instead of relying
401                         # on the limiter.
402                         libsvn_get_log($SVN_LOG, '/'.$SVN_PATH,
403                                         $min, $max, 0, 1, 1,
404                                 sub {
405                                         my $log_msg;
406                                         if ($last_commit) {
407                                                 $log_msg = libsvn_fetch(
408                                                         $last_commit, @_);
409                                                 $last_commit = git_commit(
410                                                         $log_msg,
411                                                         $last_commit,
412                                                         @parents);
413                                         } else {
414                                                 $log_msg = libsvn_new_tree(@_);
415                                                 $last_commit = git_commit(
416                                                         $log_msg, @parents);
417                                         }
418                                 });
419                         exit 0;
420                 }
421                 waitpid $pid, 0;
422                 croak $? if $?;
423                 ($last_rev, $last_commit) = svn_grab_base_rev();
424                 last if ($max >= $head);
425                 $min = $max + 1;
426                 $max += $inc;
427                 $max = $head if ($max > $head);
428         }
429         restore_index($index);
430         return { revision => $last_rev, commit => $last_commit };
431 }
432
433 sub commit {
434         my (@commits) = @_;
435         check_upgrade_needed();
436         if ($_stdin || !@commits) {
437                 print "Reading from stdin...\n";
438                 @commits = ();
439                 while (<STDIN>) {
440                         if (/\b($sha1_short)\b/o) {
441                                 unshift @commits, $1;
442                         }
443                 }
444         }
445         my @revs;
446         foreach my $c (@commits) {
447                 chomp(my @tmp = safe_qx('git-rev-parse',$c));
448                 if (scalar @tmp == 1) {
449                         push @revs, $tmp[0];
450                 } elsif (scalar @tmp > 1) {
451                         push @revs, reverse (safe_qx('git-rev-list',@tmp));
452                 } else {
453                         die "Failed to rev-parse $c\n";
454                 }
455         }
456         chomp @revs;
457         $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
458         print "Done committing ",scalar @revs," revisions to SVN\n";
459 }
460
461 sub commit_cmd {
462         my (@revs) = @_;
463
464         chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
465         my $info = svn_info('.');
466         my $fetched = fetch();
467         if ($info->{Revision} != $fetched->{revision}) {
468                 print STDERR "There are new revisions that were fetched ",
469                                 "and need to be merged (or acknowledged) ",
470                                 "before committing.\n";
471                 exit 1;
472         }
473         $info = svn_info('.');
474         read_uuid($info);
475         my $last = $fetched;
476         foreach my $c (@revs) {
477                 my $mods = svn_checkout_tree($last, $c);
478                 if (scalar @$mods == 0) {
479                         print "Skipping, no changes detected\n";
480                         next;
481                 }
482                 $last = svn_commit_tree($last, $c);
483         }
484 }
485
486 sub commit_lib {
487         my (@revs) = @_;
488         my ($r_last, $cmt_last) = svn_grab_base_rev();
489         defined $r_last or die "Must have an existing revision to commit\n";
490         my $fetched = fetch();
491         if ($r_last != $fetched->{revision}) {
492                 print STDERR "There are new revisions that were fetched ",
493                                 "and need to be merged (or acknowledged) ",
494                                 "before committing.\n",
495                                 "last rev: $r_last\n",
496                                 " current: $fetched->{revision}\n";
497                 exit 1;
498         }
499         read_uuid();
500         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
501         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
502
503         set_svn_commit_env();
504         foreach my $c (@revs) {
505                 my $log_msg = get_commit_message($c, $commit_msg);
506
507                 # fork for each commit because there's a memory leak I
508                 # can't track down... (it's probably in the SVN code)
509                 defined(my $pid = open my $fh, '-|') or croak $!;
510                 if (!$pid) {
511                         my $ed = SVN::Git::Editor->new(
512                                         {       r => $r_last,
513                                                 ra => $SVN,
514                                                 c => $c,
515                                                 svn_path => $SVN_PATH
516                                         },
517                                         $SVN->get_commit_editor(
518                                                 $log_msg->{msg},
519                                                 sub {
520                                                         libsvn_commit_cb(
521                                                                 @_, $c,
522                                                                 $log_msg->{msg},
523                                                                 $r_last,
524                                                                 $cmt_last)
525                                                 },
526                                                 @lock)
527                                         );
528                         my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
529                         if (@$mods == 0) {
530                                 print "No changes\nr$r_last = $cmt_last\n";
531                                 $ed->abort_edit;
532                         } else {
533                                 $ed->close_edit;
534                         }
535                         exit 0;
536                 }
537                 my ($r_new, $cmt_new, $no);
538                 while (<$fh>) {
539                         print $_;
540                         chomp;
541                         if (/^r(\d+) = ($sha1)$/o) {
542                                 ($r_new, $cmt_new) = ($1, $2);
543                         } elsif ($_ eq 'No changes') {
544                                 $no = 1;
545                         }
546                 }
547                 close $fh or croak $?;
548                 if (! defined $r_new && ! defined $cmt_new) {
549                         unless ($no) {
550                                 die "Failed to parse revision information\n";
551                         }
552                 } else {
553                         ($r_last, $cmt_last) = ($r_new, $cmt_new);
554                 }
555         }
556         $ENV{LC_ALL} = 'C';
557         unlink $commit_msg;
558 }
559
560 sub show_ignore {
561         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
562         $_use_lib ? show_ignore_lib() : show_ignore_cmd();
563 }
564
565 sub show_ignore_cmd {
566         require File::Find or die $!;
567         if (defined $_revision) {
568                 die "-r/--revision option doesn't work unless the Perl SVN ",
569                         "libraries are used\n";
570         }
571         chdir $SVN_WC or croak $!;
572         my %ign;
573         File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
574                 s#^\./##;
575                 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
576                 }}, no_chdir=>1},'.');
577
578         print "\n# /\n";
579         foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
580         delete $ign{'.'};
581         foreach my $i (sort keys %ign) {
582                 print "\n# ",$i,"\n";
583                 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
584         }
585 }
586
587 sub show_ignore_lib {
588         my $repo;
589         ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
590         $SVN ||= libsvn_connect($repo);
591         my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
592         libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
593 }
594
595 sub graft_branches {
596         my $gr_file = "$GIT_DIR/info/grafts";
597         my ($grafts, $comments) = read_grafts($gr_file);
598         my $gr_sha1;
599
600         if (%$grafts) {
601                 # temporarily disable our grafts file to make this idempotent
602                 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
603                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
604         }
605
606         my $l_map = read_url_paths();
607         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
608         unless ($_no_default_regex) {
609                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
610                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
611                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
612         }
613         foreach my $u (keys %$l_map) {
614                 if (@re) {
615                         foreach my $p (keys %{$l_map->{$u}}) {
616                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
617                         }
618                 }
619                 unless ($_no_graft_copy) {
620                         if ($_use_lib) {
621                                 graft_file_copy_lib($grafts,$l_map,$u);
622                         } else {
623                                 graft_file_copy_cmd($grafts,$l_map,$u);
624                         }
625                 }
626         }
627         graft_tree_joins($grafts);
628
629         write_grafts($grafts, $comments, $gr_file);
630         unlink "$gr_file~$gr_sha1" if $gr_sha1;
631 }
632
633 sub multi_init {
634         my $url = shift;
635         $_trunk ||= 'trunk';
636         $_trunk =~ s#/+$##;
637         $url =~ s#/+$## if $url;
638         if ($_trunk !~ m#^[a-z\+]+://#) {
639                 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
640                 unless ($url) {
641                         print STDERR "E: '$_trunk' is not a complete URL ",
642                                 "and a separate URL is not specified\n";
643                         exit 1;
644                 }
645                 $_trunk = $url . $_trunk;
646         }
647         if ($GIT_SVN eq 'git-svn') {
648                 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
649                 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
650         }
651         init_vars();
652         init($_trunk);
653         complete_url_ls_init($url, $_branches, '--branches/-b', '');
654         complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
655 }
656
657 sub multi_fetch {
658         # try to do trunk first, since branches/tags
659         # may be descended from it.
660         if (-e "$GIT_DIR/svn/trunk/info/url") {
661                 fetch_child_id('trunk', @_);
662         }
663         rec_fetch('', "$GIT_DIR/svn", @_);
664 }
665
666 sub show_log {
667         my (@args) = @_;
668         my ($r_min, $r_max);
669         my $r_last = -1; # prevent dupes
670         rload_authors() if $_authors;
671         if (defined $TZ) {
672                 $ENV{TZ} = $TZ;
673         } else {
674                 delete $ENV{TZ};
675         }
676         if (defined $_revision) {
677                 if ($_revision =~ /^(\d+):(\d+)$/) {
678                         ($r_min, $r_max) = ($1, $2);
679                 } elsif ($_revision =~ /^\d+$/) {
680                         $r_min = $r_max = $_revision;
681                 } else {
682                         print STDERR "-r$_revision is not supported, use ",
683                                 "standard \'git log\' arguments instead\n";
684                         exit 1;
685                 }
686         }
687
688         my $pid = open(my $log,'-|');
689         defined $pid or croak $!;
690         if (!$pid) {
691                 exec(git_svn_log_cmd($r_min,$r_max), @args) or croak $!;
692         }
693         setup_pager();
694         my (@k, $c, $d);
695
696         while (<$log>) {
697                 if (/^commit ($sha1_short)/o) {
698                         my $cmt = $1;
699                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
700                                 $r_last = $c->{r};
701                                 process_commit($c, $r_min, $r_max, \@k) or
702                                                                 goto out;
703                         }
704                         $d = undef;
705                         $c = { c => $cmt };
706                 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
707                         get_author_info($c, $1, $2, $3);
708                 } elsif (/^(?:tree|parent|committer) /) {
709                         # ignore
710                 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
711                         push @{$c->{raw}}, $_;
712                 } elsif (/^diff /) {
713                         $d = 1;
714                         push @{$c->{diff}}, $_;
715                 } elsif ($d) {
716                         push @{$c->{diff}}, $_;
717                 } elsif (/^    (git-svn-id:.+)$/) {
718                         (undef, $c->{r}, undef) = extract_metadata($1);
719                 } elsif (s/^    //) {
720                         push @{$c->{l}}, $_;
721                 }
722         }
723         if ($c && defined $c->{r} && $c->{r} != $r_last) {
724                 $r_last = $c->{r};
725                 process_commit($c, $r_min, $r_max, \@k);
726         }
727         if (@k) {
728                 my $swap = $r_max;
729                 $r_max = $r_min;
730                 $r_min = $swap;
731                 process_commit($_, $r_min, $r_max) foreach reverse @k;
732         }
733 out:
734         close $log;
735         print '-' x72,"\n" unless $_incremental || $_oneline;
736 }
737
738 sub commit_diff_usage {
739         print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
740         exit 1
741 }
742
743 sub commit_diff {
744         if (!$_use_lib) {
745                 print STDERR "commit-diff must be used with SVN libraries\n";
746                 exit 1;
747         }
748         my $ta = shift or commit_diff_usage();
749         my $tb = shift or commit_diff_usage();
750         if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
751                 print STDERR "Needed URL or usable git-svn id command-line\n";
752                 commit_diff_usage();
753         }
754         if (defined $_message && defined $_file) {
755                 print STDERR "Both --message/-m and --file/-F specified ",
756                                 "for the commit message.\n",
757                                 "I have no idea what you mean\n";
758                 exit 1;
759         }
760         if (defined $_file) {
761                 $_message = file_to_s($_file);
762         } else {
763                 $_message ||= get_commit_message($tb,
764                                         "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
765         }
766         my $repo;
767         ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
768         $SVN_LOG ||= libsvn_connect($repo);
769         $SVN ||= libsvn_connect($repo);
770         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
771         my $ed = SVN::Git::Editor->new({        r => $SVN->get_latest_revnum,
772                                                 ra => $SVN, c => $tb,
773                                                 svn_path => $SVN_PATH
774                                         },
775                                 $SVN->get_commit_editor($_message,
776                                         sub {print "Committed $_[0]\n"},@lock)
777                                 );
778         my $mods = libsvn_checkout_tree($ta, $tb, $ed);
779         if (@$mods == 0) {
780                 print "No changes\n$ta == $tb\n";
781                 $ed->abort_edit;
782         } else {
783                 $ed->close_edit;
784         }
785 }
786
787 ########################### utility functions #########################
788
789 sub cmt_showable {
790         my ($c) = @_;
791         return 1 if defined $c->{r};
792         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
793                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
794                 my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
795                 shift @msg while ($msg[0] ne "\n");
796                 shift @msg;
797                 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
798
799                 (undef, $c->{r}, undef) = extract_metadata(
800                                 (grep(/^git-svn-id: /, @msg))[-1]);
801         }
802         return defined $c->{r};
803 }
804
805 sub git_svn_log_cmd {
806         my ($r_min, $r_max) = @_;
807         my @cmd = (qw/git-log --abbrev-commit --pretty=raw
808                         --default/, "refs/remotes/$GIT_SVN");
809         push @cmd, '--summary' if $_verbose;
810         return @cmd unless defined $r_max;
811         if ($r_max == $r_min) {
812                 push @cmd, '--max-count=1';
813                 if (my $c = revdb_get($REVDB, $r_max)) {
814                         push @cmd, $c;
815                 }
816         } else {
817                 my ($c_min, $c_max);
818                 $c_max = revdb_get($REVDB, $r_max);
819                 $c_min = revdb_get($REVDB, $r_min);
820                 if ($c_min && $c_max) {
821                         if ($r_max > $r_max) {
822                                 push @cmd, "$c_min..$c_max";
823                         } else {
824                                 push @cmd, "$c_max..$c_min";
825                         }
826                 } elsif ($r_max > $r_min) {
827                         push @cmd, $c_max;
828                 } else {
829                         push @cmd, $c_min;
830                 }
831         }
832         return @cmd;
833 }
834
835 sub fetch_child_id {
836         my $id = shift;
837         print "Fetching $id\n";
838         my $ref = "$GIT_DIR/refs/remotes/$id";
839         defined(my $pid = open my $fh, '-|') or croak $!;
840         if (!$pid) {
841                 $_repack = undef;
842                 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
843                 init_vars();
844                 fetch(@_);
845                 exit 0;
846         }
847         while (<$fh>) {
848                 print $_;
849                 check_repack() if (/^r\d+ = $sha1/);
850         }
851         close $fh or croak $?;
852 }
853
854 sub rec_fetch {
855         my ($pfx, $p, @args) = @_;
856         my @dir;
857         foreach (sort <$p/*>) {
858                 if (-r "$_/info/url") {
859                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
860                         my $id = $pfx . basename $_;
861                         next if $id eq 'trunk';
862                         fetch_child_id($id, @args);
863                 } elsif (-d $_) {
864                         push @dir, $_;
865                 }
866         }
867         foreach (@dir) {
868                 my $x = $_;
869                 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
870                 rec_fetch($x, $_);
871         }
872 }
873
874 sub complete_url_ls_init {
875         my ($url, $var, $switch, $pfx) = @_;
876         unless ($var) {
877                 print STDERR "W: $switch not specified\n";
878                 return;
879         }
880         $var =~ s#/+$##;
881         if ($var !~ m#^[a-z\+]+://#) {
882                 $var = '/' . $var if ($var !~ m#^/#);
883                 unless ($url) {
884                         print STDERR "E: '$var' is not a complete URL ",
885                                 "and a separate URL is not specified\n";
886                         exit 1;
887                 }
888                 $var = $url . $var;
889         }
890         chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
891                                 : safe_qx(qw/svn ls --non-interactive/, $var));
892         my $old = $GIT_SVN;
893         defined(my $pid = fork) or croak $!;
894         if (!$pid) {
895                 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
896                         $u =~ s#/+$##;
897                         if ($u !~ m!\Q$var\E/(.+)$!) {
898                                 print STDERR "W: Unrecognized URL: $u\n";
899                                 die "This should never happen\n";
900                         }
901                         my $id = $pfx.$1;
902                         print "init $u => $id\n";
903                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
904                         init_vars();
905                         init($u);
906                 }
907                 exit 0;
908         }
909         waitpid $pid, 0;
910         croak $? if $?;
911 }
912
913 sub common_prefix {
914         my $paths = shift;
915         my %common;
916         foreach (@$paths) {
917                 my @tmp = split m#/#, $_;
918                 my $p = '';
919                 while (my $x = shift @tmp) {
920                         $p .= "/$x";
921                         $common{$p} ||= 0;
922                         $common{$p}++;
923                 }
924         }
925         foreach (sort {length $b <=> length $a} keys %common) {
926                 if ($common{$_} == @$paths) {
927                         return $_;
928                 }
929         }
930         return '';
931 }
932
933 # grafts set here are 'stronger' in that they're based on actual tree
934 # matches, and won't be deleted from merge-base checking in write_grafts()
935 sub graft_tree_joins {
936         my $grafts = shift;
937         map_tree_joins() if (@_branch_from && !%tree_map);
938         return unless %tree_map;
939
940         git_svn_each(sub {
941                 my $i = shift;
942                 defined(my $pid = open my $fh, '-|') or croak $!;
943                 if (!$pid) {
944                         exec qw/git-rev-list --pretty=raw/,
945                                         "refs/remotes/$i" or croak $!;
946                 }
947                 while (<$fh>) {
948                         next unless /^commit ($sha1)$/o;
949                         my $c = $1;
950                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
951                         next unless $tree_map{$t};
952
953                         my $l;
954                         do {
955                                 $l = readline $fh;
956                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
957
958                         my ($s, $tz) = ($1, $2);
959                         if ($tz =~ s/^\+//) {
960                                 $s += tz_to_s_offset($tz);
961                         } elsif ($tz =~ s/^\-//) {
962                                 $s -= tz_to_s_offset($tz);
963                         }
964
965                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
966
967                         foreach my $p (@{$tree_map{$t}}) {
968                                 next if $p eq $c;
969                                 my $mb = eval {
970                                         safe_qx('git-merge-base', $c, $p)
971                                 };
972                                 next unless ($@ || $?);
973                                 if (defined $r_a) {
974                                         # see if SVN says it's a relative
975                                         my ($url_b, $r_b, $uuid_b) =
976                                                         cmt_metadata($p);
977                                         next if (defined $url_b &&
978                                                         defined $url_a &&
979                                                         ($url_a eq $url_b) &&
980                                                         ($uuid_a eq $uuid_b));
981                                         if ($uuid_a eq $uuid_b) {
982                                                 if ($r_b < $r_a) {
983                                                         $grafts->{$c}->{$p} = 2;
984                                                         next;
985                                                 } elsif ($r_b > $r_a) {
986                                                         $grafts->{$p}->{$c} = 2;
987                                                         next;
988                                                 }
989                                         }
990                                 }
991                                 my $ct = get_commit_time($p);
992                                 if ($ct < $s) {
993                                         $grafts->{$c}->{$p} = 2;
994                                 } elsif ($ct > $s) {
995                                         $grafts->{$p}->{$c} = 2;
996                                 }
997                                 # what should we do when $ct == $s ?
998                         }
999                 }
1000                 close $fh or croak $?;
1001         });
1002 }
1003
1004 # this isn't funky-filename safe, but good enough for now...
1005 sub graft_file_copy_cmd {
1006         my ($grafts, $l_map, $u) = @_;
1007         my $paths = $l_map->{$u};
1008         my $pfx = common_prefix([keys %$paths]);
1009         $SVN_URL ||= $u.$pfx;
1010         my $pid = open my $fh, '-|';
1011         defined $pid or croak $!;
1012         unless ($pid) {
1013                 my @exec = qw/svn log -v/;
1014                 push @exec, "-r$_revision" if defined $_revision;
1015                 exec @exec, $u.$pfx or croak $!;
1016         }
1017         my ($r, $mp) = (undef, undef);
1018         while (<$fh>) {
1019                 chomp;
1020                 if (/^\-{72}$/) {
1021                         $mp = $r = undef;
1022                 } elsif (/^r(\d+) \| /) {
1023                         $r = $1 unless defined $r;
1024                 } elsif (/^Changed paths:/) {
1025                         $mp = 1;
1026                 } elsif ($mp && m#^   [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
1027                         my ($p1, $p0, $r0) = ($1, $2, $3);
1028                         my $c = find_graft_path_commit($paths, $p1, $r);
1029                         next unless $c;
1030                         find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
1031                 }
1032         }
1033 }
1034
1035 sub graft_file_copy_lib {
1036         my ($grafts, $l_map, $u) = @_;
1037         my $tree_paths = $l_map->{$u};
1038         my $pfx = common_prefix([keys %$tree_paths]);
1039         my ($repo, $path) = repo_path_split($u.$pfx);
1040         $SVN_LOG ||= libsvn_connect($repo);
1041         $SVN ||= libsvn_connect($repo);
1042
1043         my ($base, $head) = libsvn_parse_revision();
1044         my $inc = 1000;
1045         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1046         my $eh = $SVN::Error::handler;
1047         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1048         while (1) {
1049                 my $pool = SVN::Pool->new;
1050                 libsvn_get_log($SVN_LOG, "/$path", $min, $max, 0, 1, 1,
1051                         sub {
1052                                 libsvn_graft_file_copies($grafts, $tree_paths,
1053                                                         $path, @_);
1054                         }, $pool);
1055                 $pool->clear;
1056                 last if ($max >= $head);
1057                 $min = $max + 1;
1058                 $max += $inc;
1059                 $max = $head if ($max > $head);
1060         }
1061         $SVN::Error::handler = $eh;
1062 }
1063
1064 sub process_merge_msg_matches {
1065         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1066         my (@strong, @weak);
1067         foreach (@matches) {
1068                 # merging with ourselves is not interesting
1069                 next if $_ eq $p;
1070                 if ($l_map->{$u}->{$_}) {
1071                         push @strong, $_;
1072                 } else {
1073                         push @weak, $_;
1074                 }
1075         }
1076         foreach my $w (@weak) {
1077                 last if @strong;
1078                 # no exact match, use branch name as regexp.
1079                 my $re = qr/\Q$w\E/i;
1080                 foreach (keys %{$l_map->{$u}}) {
1081                         if (/$re/) {
1082                                 push @strong, $l_map->{$u}->{$_};
1083                                 last;
1084                         }
1085                 }
1086                 last if @strong;
1087                 $w = basename($w);
1088                 $re = qr/\Q$w\E/i;
1089                 foreach (keys %{$l_map->{$u}}) {
1090                         if (/$re/) {
1091                                 push @strong, $l_map->{$u}->{$_};
1092                                 last;
1093                         }
1094                 }
1095         }
1096         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1097                                         \s(?:[a-f\d\-]+)$/xsm);
1098         unless (defined $rev) {
1099                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1100                                         \@(?:[a-f\d\-]+)/xsm);
1101                 return unless defined $rev;
1102         }
1103         foreach my $m (@strong) {
1104                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1105                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1106         }
1107 }
1108
1109 sub graft_merge_msg {
1110         my ($grafts, $l_map, $u, $p, @re) = @_;
1111
1112         my $x = $l_map->{$u}->{$p};
1113         my $rl = rev_list_raw($x);
1114         while (my $c = next_rev_list_entry($rl)) {
1115                 foreach my $re (@re) {
1116                         my (@br) = ($c->{m} =~ /$re/g);
1117                         next unless @br;
1118                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1119                 }
1120         }
1121 }
1122
1123 sub read_uuid {
1124         return if $SVN_UUID;
1125         if ($_use_lib) {
1126                 my $pool = SVN::Pool->new;
1127                 $SVN_UUID = $SVN->get_uuid($pool);
1128                 $pool->clear;
1129         } else {
1130                 my $info = shift || svn_info('.');
1131                 $SVN_UUID = $info->{'Repository UUID'} or
1132                                         croak "Repository UUID unreadable\n";
1133         }
1134 }
1135
1136 sub quiet_run {
1137         my $pid = fork;
1138         defined $pid or croak $!;
1139         if (!$pid) {
1140                 open my $null, '>', '/dev/null' or croak $!;
1141                 open STDERR, '>&', $null or croak $!;
1142                 open STDOUT, '>&', $null or croak $!;
1143                 exec @_ or croak $!;
1144         }
1145         waitpid $pid, 0;
1146         return $?;
1147 }
1148
1149 sub repo_path_split {
1150         my $full_url = shift;
1151         $full_url =~ s#/+$##;
1152
1153         foreach (@repo_path_split_cache) {
1154                 if ($full_url =~ s#$_##) {
1155                         my $u = $1;
1156                         $full_url =~ s#^/+##;
1157                         return ($u, $full_url);
1158                 }
1159         }
1160
1161         my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1162         $path =~ s#^/+##;
1163         my @paths = split(m#/+#, $path);
1164
1165         if ($_use_lib) {
1166                 while (1) {
1167                         $SVN = libsvn_connect($url);
1168                         last if (defined $SVN &&
1169                                 defined eval { $SVN->get_latest_revnum });
1170                         my $n = shift @paths || last;
1171                         $url .= "/$n";
1172                 }
1173         } else {
1174                 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1175                         my $n = shift @paths || last;
1176                         $url .= "/$n";
1177                 }
1178         }
1179         push @repo_path_split_cache, qr/^(\Q$url\E)/;
1180         $path = join('/',@paths);
1181         return ($url, $path);
1182 }
1183
1184 sub setup_git_svn {
1185         defined $SVN_URL or croak "SVN repository location required\n";
1186         unless (-d $GIT_DIR) {
1187                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1188         }
1189         mkpath([$GIT_SVN_DIR]);
1190         mkpath(["$GIT_SVN_DIR/info"]);
1191         open my $fh, '>>',$REVDB or croak $!;
1192         close $fh;
1193         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1194
1195 }
1196
1197 sub assert_svn_wc_clean {
1198         return if $_use_lib;
1199         my ($svn_rev) = @_;
1200         croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1201         my $lcr = svn_info('.')->{'Last Changed Rev'};
1202         if ($svn_rev != $lcr) {
1203                 print STDERR "Checking for copy-tree ... ";
1204                 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1205                                                 "-r$lcr:$svn_rev")));
1206                 if (@diff) {
1207                         croak "Nope!  Expected r$svn_rev, got r$lcr\n";
1208                 } else {
1209                         print STDERR "OK!\n";
1210                 }
1211         }
1212         my @status = grep(!/^Performing status on external/,(`svn status`));
1213         @status = grep(!/^\s*$/,@status);
1214         if (scalar @status) {
1215                 print STDERR "Tree ($SVN_WC) is not clean:\n";
1216                 print STDERR $_ foreach @status;
1217                 croak;
1218         }
1219 }
1220
1221 sub get_tree_from_treeish {
1222         my ($treeish) = @_;
1223         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1224         chomp(my $type = `git-cat-file -t $treeish`);
1225         my $expected;
1226         while ($type eq 'tag') {
1227                 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1228         }
1229         if ($type eq 'commit') {
1230                 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1231                 ($expected) = ($expected =~ /^tree ($sha1)$/);
1232                 die "Unable to get tree from $treeish\n" unless $expected;
1233         } elsif ($type eq 'tree') {
1234                 $expected = $treeish;
1235         } else {
1236                 die "$treeish is a $type, expected tree, tag or commit\n";
1237         }
1238         return $expected;
1239 }
1240
1241 sub assert_tree {
1242         return if $_use_lib;
1243         my ($treeish) = @_;
1244         my $expected = get_tree_from_treeish($treeish);
1245
1246         my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1247         if (-e $tmpindex) {
1248                 unlink $tmpindex or croak $!;
1249         }
1250         my $old_index = set_index($tmpindex);
1251         index_changes(1);
1252         chomp(my $tree = `git-write-tree`);
1253         restore_index($old_index);
1254         if ($tree ne $expected) {
1255                 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1256         }
1257         unlink $tmpindex;
1258 }
1259
1260 sub parse_diff_tree {
1261         my $diff_fh = shift;
1262         local $/ = "\0";
1263         my $state = 'meta';
1264         my @mods;
1265         while (<$diff_fh>) {
1266                 chomp $_; # this gets rid of the trailing "\0"
1267                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1268                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1269                         push @mods, {   mode_a => $1, mode_b => $2,
1270                                         sha1_b => $3, chg => $4 };
1271                         if ($4 =~ /^(?:C|R)$/) {
1272                                 $state = 'file_a';
1273                         } else {
1274                                 $state = 'file_b';
1275                         }
1276                 } elsif ($state eq 'file_a') {
1277                         my $x = $mods[$#mods] or croak "Empty array\n";
1278                         if ($x->{chg} !~ /^(?:C|R)$/) {
1279                                 croak "Error parsing $_, $x->{chg}\n";
1280                         }
1281                         $x->{file_a} = $_;
1282                         $state = 'file_b';
1283                 } elsif ($state eq 'file_b') {
1284                         my $x = $mods[$#mods] or croak "Empty array\n";
1285                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1286                                 croak "Error parsing $_, $x->{chg}\n";
1287                         }
1288                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1289                                 croak "Error parsing $_, $x->{chg}\n";
1290                         }
1291                         $x->{file_b} = $_;
1292                         $state = 'meta';
1293                 } else {
1294                         croak "Error parsing $_\n";
1295                 }
1296         }
1297         close $diff_fh or croak $?;
1298
1299         return \@mods;
1300 }
1301
1302 sub svn_check_prop_executable {
1303         my $m = shift;
1304         return if -l $m->{file_b};
1305         if ($m->{mode_b} =~ /755$/) {
1306                 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1307                 if ($m->{mode_a} !~ /755$/) {
1308                         sys(qw(svn propset svn:executable 1), $m->{file_b});
1309                 }
1310                 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1311         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1312                 sys(qw(svn propdel svn:executable), $m->{file_b});
1313                 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1314                 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1315         }
1316 }
1317
1318 sub svn_ensure_parent_path {
1319         my $dir_b = dirname(shift);
1320         svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1321         mkpath([$dir_b]) unless (-d $dir_b);
1322         sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1323 }
1324
1325 sub precommit_check {
1326         my $mods = shift;
1327         my (%rm_file, %rmdir_check, %added_check);
1328
1329         my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1330         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1331                 if ($m->{chg} eq 'R') {
1332                         if (-d $m->{file_b}) {
1333                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1334                         }
1335                         # dir/$file => dir/file/$file
1336                         my $dirname = dirname($m->{file_b});
1337                         while ($dirname ne File::Spec->curdir) {
1338                                 if ($dirname ne $m->{file_a}) {
1339                                         $dirname = dirname($dirname);
1340                                         next;
1341                                 }
1342                                 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1343                         }
1344                         # baz/zzz => baz (baz is a file)
1345                         $dirname = dirname($m->{file_a});
1346                         while ($dirname ne File::Spec->curdir) {
1347                                 if ($dirname ne $m->{file_b}) {
1348                                         $dirname = dirname($dirname);
1349                                         next;
1350                                 }
1351                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1352                         }
1353                 }
1354                 if ($m->{chg} =~ /^(D|R)$/) {
1355                         my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1356                         $rm_file{ $m->{$t} } = 1;
1357                         my $dirname = dirname( $m->{$t} );
1358                         my $basename = basename( $m->{$t} );
1359                         $rmdir_check{$dirname}->{$basename} = 1;
1360                 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1361                         if (-d $m->{file_b}) {
1362                                 err_dir_to_file($m->{file_b});
1363                         }
1364                         my $dirname = dirname( $m->{file_b} );
1365                         my $basename = basename( $m->{file_b} );
1366                         $added_check{$dirname}->{$basename} = 1;
1367                         while ($dirname ne File::Spec->curdir) {
1368                                 if ($rm_file{$dirname}) {
1369                                         err_file_to_dir($m->{file_b});
1370                                 }
1371                                 $dirname = dirname $dirname;
1372                         }
1373                 }
1374         }
1375         return (\%rmdir_check, \%added_check);
1376
1377         sub err_dir_to_file {
1378                 my $file = shift;
1379                 print STDERR "Node change from directory to file ",
1380                                 "is not supported by Subversion: ",$file,"\n";
1381                 exit 1;
1382         }
1383         sub err_file_to_dir {
1384                 my $file = shift;
1385                 print STDERR "Node change from file to directory ",
1386                                 "is not supported by Subversion: ",$file,"\n";
1387                 exit 1;
1388         }
1389 }
1390
1391
1392 sub get_diff {
1393         my ($from, $treeish) = @_;
1394         assert_tree($from);
1395         print "diff-tree $from $treeish\n";
1396         my $pid = open my $diff_fh, '-|';
1397         defined $pid or croak $!;
1398         if ($pid == 0) {
1399                 my @diff_tree = qw(git-diff-tree -z -r);
1400                 if ($_cp_similarity) {
1401                         push @diff_tree, "-C$_cp_similarity";
1402                 } else {
1403                         push @diff_tree, '-C';
1404                 }
1405                 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1406                 push @diff_tree, "-l$_l" if defined $_l;
1407                 exec(@diff_tree, $from, $treeish) or croak $!;
1408         }
1409         return parse_diff_tree($diff_fh);
1410 }
1411
1412 sub svn_checkout_tree {
1413         my ($from, $treeish) = @_;
1414         my $mods = get_diff($from->{commit}, $treeish);
1415         return $mods unless (scalar @$mods);
1416         my ($rm, $add) = precommit_check($mods);
1417
1418         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1419         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1420                 if ($m->{chg} eq 'C') {
1421                         svn_ensure_parent_path( $m->{file_b} );
1422                         sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
1423                         apply_mod_line_blob($m);
1424                         svn_check_prop_executable($m);
1425                 } elsif ($m->{chg} eq 'D') {
1426                         sys(qw(svn rm --force), $m->{file_b});
1427                 } elsif ($m->{chg} eq 'R') {
1428                         svn_ensure_parent_path( $m->{file_b} );
1429                         sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1430                         apply_mod_line_blob($m);
1431                         svn_check_prop_executable($m);
1432                 } elsif ($m->{chg} eq 'M') {
1433                         apply_mod_line_blob($m);
1434                         svn_check_prop_executable($m);
1435                 } elsif ($m->{chg} eq 'T') {
1436                         sys(qw(svn rm --force),$m->{file_b});
1437                         apply_mod_line_blob($m);
1438                         sys(qw(svn add), $m->{file_b});
1439                         svn_check_prop_executable($m);
1440                 } elsif ($m->{chg} eq 'A') {
1441                         svn_ensure_parent_path( $m->{file_b} );
1442                         apply_mod_line_blob($m);
1443                         sys(qw(svn add), $m->{file_b});
1444                         svn_check_prop_executable($m);
1445                 } else {
1446                         croak "Invalid chg: $m->{chg}\n";
1447                 }
1448         }
1449
1450         assert_tree($treeish);
1451         if ($_rmdir) { # remove empty directories
1452                 handle_rmdir($rm, $add);
1453         }
1454         assert_tree($treeish);
1455         return $mods;
1456 }
1457
1458 sub libsvn_checkout_tree {
1459         my ($from, $treeish, $ed) = @_;
1460         my $mods = get_diff($from, $treeish);
1461         return $mods unless (scalar @$mods);
1462         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1463         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1464                 my $f = $m->{chg};
1465                 if (defined $o{$f}) {
1466                         $ed->$f($m, $_q);
1467                 } else {
1468                         croak "Invalid change type: $f\n";
1469                 }
1470         }
1471         $ed->rmdirs($_q) if $_rmdir;
1472         return $mods;
1473 }
1474
1475 # svn ls doesn't work with respect to the current working tree, but what's
1476 # in the repository.  There's not even an option for it... *sigh*
1477 # (added files don't show up and removed files remain in the ls listing)
1478 sub svn_ls_current {
1479         my ($dir, $rm, $add) = @_;
1480         chomp(my @ls = safe_qx('svn','ls',$dir));
1481         my @ret = ();
1482         foreach (@ls) {
1483                 s#/$##; # trailing slashes are evil
1484                 push @ret, $_ unless $rm->{$dir}->{$_};
1485         }
1486         if (exists $add->{$dir}) {
1487                 push @ret, keys %{$add->{$dir}};
1488         }
1489         return \@ret;
1490 }
1491
1492 sub handle_rmdir {
1493         my ($rm, $add) = @_;
1494
1495         foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1496                 my $ls = svn_ls_current($dir, $rm, $add);
1497                 next if (scalar @$ls);
1498                 sys(qw(svn rm --force),$dir);
1499
1500                 my $dn = dirname $dir;
1501                 $rm->{ $dn }->{ basename $dir } = 1;
1502                 $ls = svn_ls_current($dn, $rm, $add);
1503                 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1504                         sys(qw(svn rm --force),$dn);
1505                         $dir = basename $dn;
1506                         $dn = dirname $dn;
1507                         $rm->{ $dn }->{ $dir } = 1;
1508                         $ls = svn_ls_current($dn, $rm, $add);
1509                 }
1510         }
1511 }
1512
1513 sub get_commit_message {
1514         my ($commit, $commit_msg) = (@_);
1515         my %log_msg = ( msg => '' );
1516         open my $msg, '>', $commit_msg or croak $!;
1517
1518         chomp(my $type = `git-cat-file -t $commit`);
1519         if ($type eq 'commit' || $type eq 'tag') {
1520                 my $pid = open my $msg_fh, '-|';
1521                 defined $pid or croak $!;
1522
1523                 if ($pid == 0) {
1524                         exec('git-cat-file', $type, $commit) or croak $!;
1525                 }
1526                 my $in_msg = 0;
1527                 while (<$msg_fh>) {
1528                         if (!$in_msg) {
1529                                 $in_msg = 1 if (/^\s*$/);
1530                         } elsif (/^git-svn-id: /) {
1531                                 # skip this, we regenerate the correct one
1532                                 # on re-fetch anyways
1533                         } else {
1534                                 print $msg $_ or croak $!;
1535                         }
1536                 }
1537                 close $msg_fh or croak $?;
1538         }
1539         close $msg or croak $!;
1540
1541         if ($_edit || ($type eq 'tree')) {
1542                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1543                 system($editor, $commit_msg);
1544         }
1545
1546         # file_to_s removes all trailing newlines, so just use chomp() here:
1547         open $msg, '<', $commit_msg or croak $!;
1548         { local $/; chomp($log_msg{msg} = <$msg>); }
1549         close $msg or croak $!;
1550
1551         return \%log_msg;
1552 }
1553
1554 sub set_svn_commit_env {
1555         if (defined $LC_ALL) {
1556                 $ENV{LC_ALL} = $LC_ALL;
1557         } else {
1558                 delete $ENV{LC_ALL};
1559         }
1560 }
1561
1562 sub svn_commit_tree {
1563         my ($last, $commit) = @_;
1564         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1565         my $log_msg = get_commit_message($commit, $commit_msg);
1566         my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1567         print "Committing $commit: $oneline\n";
1568
1569         set_svn_commit_env();
1570         my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1571         $ENV{LC_ALL} = 'C';
1572         unlink $commit_msg;
1573         my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1574         if (!defined $committed) {
1575                 my $out = join("\n",@ci_output);
1576                 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1577                                 $out, "\n\nAssuming English locale...";
1578                 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1579                 defined $committed or die " FAILED!\n",
1580                         "Commit output failed to parse committed revision!\n",
1581                 print STDERR " OK\n";
1582         }
1583
1584         my @svn_up = qw(svn up);
1585         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1586         if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1587                 push @svn_up, "-r$committed";
1588                 sys(@svn_up);
1589                 my $info = svn_info('.');
1590                 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1591                 if ($info->{'Last Changed Rev'} != $committed) {
1592                         croak "$info->{'Last Changed Rev'} != $committed\n"
1593                 }
1594                 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1595                                         /(\d{4})\-(\d\d)\-(\d\d)\s
1596                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1597                                          or croak "Failed to parse date: $date\n";
1598                 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1599                 $log_msg->{author} = $info->{'Last Changed Author'};
1600                 $log_msg->{revision} = $committed;
1601                 $log_msg->{msg} .= "\n";
1602                 $log_msg->{parents} = [ $last->{commit} ];
1603                 $log_msg->{commit} = git_commit($log_msg, $commit);
1604                 return $log_msg;
1605         }
1606         # resync immediately
1607         push @svn_up, "-r$last->{revision}";
1608         sys(@svn_up);
1609         return fetch("$committed=$commit");
1610 }
1611
1612 sub rev_list_raw {
1613         my (@args) = @_;
1614         my $pid = open my $fh, '-|';
1615         defined $pid or croak $!;
1616         if (!$pid) {
1617                 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1618         }
1619         return { fh => $fh, t => { } };
1620 }
1621
1622 sub next_rev_list_entry {
1623         my $rl = shift;
1624         my $fh = $rl->{fh};
1625         my $x = $rl->{t};
1626         while (<$fh>) {
1627                 if (/^commit ($sha1)$/o) {
1628                         if ($x->{c}) {
1629                                 $rl->{t} = { c => $1 };
1630                                 return $x;
1631                         } else {
1632                                 $x->{c} = $1;
1633                         }
1634                 } elsif (/^parent ($sha1)$/o) {
1635                         $x->{p}->{$1} = 1;
1636                 } elsif (s/^    //) {
1637                         $x->{m} ||= '';
1638                         $x->{m} .= $_;
1639                 }
1640         }
1641         return ($x != $rl->{t}) ? $x : undef;
1642 }
1643
1644 # read the entire log into a temporary file (which is removed ASAP)
1645 # and store the file handle + parser state
1646 sub svn_log_raw {
1647         my (@log_args) = @_;
1648         my $log_fh = IO::File->new_tmpfile or croak $!;
1649         my $pid = fork;
1650         defined $pid or croak $!;
1651         if (!$pid) {
1652                 open STDOUT, '>&', $log_fh or croak $!;
1653                 exec (qw(svn log), @log_args) or croak $!
1654         }
1655         waitpid $pid, 0;
1656         croak $? if $?;
1657         seek $log_fh, 0, 0 or croak $!;
1658         return { state => 'sep', fh => $log_fh };
1659 }
1660
1661 sub next_log_entry {
1662         my $log = shift; # retval of svn_log_raw()
1663         my $ret = undef;
1664         my $fh = $log->{fh};
1665
1666         while (<$fh>) {
1667                 chomp;
1668                 if (/^\-{72}$/) {
1669                         if ($log->{state} eq 'msg') {
1670                                 if ($ret->{lines}) {
1671                                         $ret->{msg} .= $_."\n";
1672                                         unless(--$ret->{lines}) {
1673                                                 $log->{state} = 'sep';
1674                                         }
1675                                 } else {
1676                                         croak "Log parse error at: $_\n",
1677                                                 $ret->{revision},
1678                                                 "\n";
1679                                 }
1680                                 next;
1681                         }
1682                         if ($log->{state} ne 'sep') {
1683                                 croak "Log parse error at: $_\n",
1684                                         "state: $log->{state}\n",
1685                                         $ret->{revision},
1686                                         "\n";
1687                         }
1688                         $log->{state} = 'rev';
1689
1690                         # if we have an empty log message, put something there:
1691                         if ($ret) {
1692                                 $ret->{msg} ||= "\n";
1693                                 delete $ret->{lines};
1694                                 return $ret;
1695                         }
1696                         next;
1697                 }
1698                 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1699                         my $rev = $1;
1700                         my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1701                         ($lines) = ($lines =~ /(\d+)/);
1702                         my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1703                                         /(\d{4})\-(\d\d)\-(\d\d)\s
1704                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1705                                          or croak "Failed to parse date: $date\n";
1706                         $ret = {        revision => $rev,
1707                                         date => "$tz $Y-$m-$d $H:$M:$S",
1708                                         author => $author,
1709                                         lines => $lines,
1710                                         msg => '' };
1711                         if (defined $_authors && ! defined $users{$author}) {
1712                                 die "Author: $author not defined in ",
1713                                                 "$_authors file\n";
1714                         }
1715                         $log->{state} = 'msg_start';
1716                         next;
1717                 }
1718                 # skip the first blank line of the message:
1719                 if ($log->{state} eq 'msg_start' && /^$/) {
1720                         $log->{state} = 'msg';
1721                 } elsif ($log->{state} eq 'msg') {
1722                         if ($ret->{lines}) {
1723                                 $ret->{msg} .= $_."\n";
1724                                 unless (--$ret->{lines}) {
1725                                         $log->{state} = 'sep';
1726                                 }
1727                         } else {
1728                                 croak "Log parse error at: $_\n",
1729                                         $ret->{revision},"\n";
1730                         }
1731                 }
1732         }
1733         return $ret;
1734 }
1735
1736 sub svn_info {
1737         my $url = shift || $SVN_URL;
1738
1739         my $pid = open my $info_fh, '-|';
1740         defined $pid or croak $!;
1741
1742         if ($pid == 0) {
1743                 exec(qw(svn info),$url) or croak $!;
1744         }
1745
1746         my $ret = {};
1747         # only single-lines seem to exist in svn info output
1748         while (<$info_fh>) {
1749                 chomp $_;
1750                 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1751                         $ret->{$1} = $2;
1752                         push @{$ret->{-order}}, $1;
1753                 }
1754         }
1755         close $info_fh or croak $?;
1756         return $ret;
1757 }
1758
1759 sub sys { system(@_) == 0 or croak $? }
1760
1761 sub do_update_index {
1762         my ($z_cmd, $cmd, $no_text_base) = @_;
1763
1764         my $z = open my $p, '-|';
1765         defined $z or croak $!;
1766         unless ($z) { exec @$z_cmd or croak $! }
1767
1768         my $pid = open my $ui, '|-';
1769         defined $pid or croak $!;
1770         unless ($pid) {
1771                 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1772         }
1773         local $/ = "\0";
1774         while (my $x = <$p>) {
1775                 chomp $x;
1776                 if (!$no_text_base && lstat $x && ! -l _ &&
1777                                 svn_propget_base('svn:keywords', $x)) {
1778                         my $mode = -x _ ? 0755 : 0644;
1779                         my ($v,$d,$f) = File::Spec->splitpath($x);
1780                         my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1781                                                 'text-base',"$f.svn-base");
1782                         $tb =~ s#^/##;
1783                         unless (-f $tb) {
1784                                 $tb = File::Spec->catfile($d, '.svn',
1785                                                 'text-base',"$f.svn-base");
1786                                 $tb =~ s#^/##;
1787                         }
1788                         my @s = stat($x);
1789                         unlink $x or croak $!;
1790                         copy($tb, $x);
1791                         chmod(($mode &~ umask), $x) or croak $!;
1792                         utime $s[8], $s[9], $x;
1793                 }
1794                 print $ui $x,"\0";
1795         }
1796         close $ui or croak $?;
1797 }
1798
1799 sub index_changes {
1800         return if $_use_lib;
1801
1802         if (!-f "$GIT_SVN_DIR/info/exclude") {
1803                 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1804                 print $fd '.svn',"\n";
1805                 close $fd or croak $!;
1806         }
1807         my $no_text_base = shift;
1808         do_update_index([qw/git-diff-files --name-only -z/],
1809                         'remove',
1810                         $no_text_base);
1811         do_update_index([qw/git-ls-files -z --others/,
1812                                 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1813                         'add',
1814                         $no_text_base);
1815 }
1816
1817 sub s_to_file {
1818         my ($str, $file, $mode) = @_;
1819         open my $fd,'>',$file or croak $!;
1820         print $fd $str,"\n" or croak $!;
1821         close $fd or croak $!;
1822         chmod ($mode &~ umask, $file) if (defined $mode);
1823 }
1824
1825 sub file_to_s {
1826         my $file = shift;
1827         open my $fd,'<',$file or croak "$!: file: $file\n";
1828         local $/;
1829         my $ret = <$fd>;
1830         close $fd or croak $!;
1831         $ret =~ s/\s*$//s;
1832         return $ret;
1833 }
1834
1835 sub assert_revision_unknown {
1836         my $r = shift;
1837         if (my $c = revdb_get($REVDB, $r)) {
1838                 croak "$r = $c already exists! Why are we refetching it?";
1839         }
1840 }
1841
1842 sub trees_eq {
1843         my ($x, $y) = @_;
1844         my @x = safe_qx('git-cat-file','commit',$x);
1845         my @y = safe_qx('git-cat-file','commit',$y);
1846         if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1847                                 || $y[0] !~ /^tree $sha1\n$/) {
1848                 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1849                 return 0
1850         }
1851         return 1;
1852 }
1853
1854 sub git_commit {
1855         my ($log_msg, @parents) = @_;
1856         assert_revision_unknown($log_msg->{revision});
1857         map_tree_joins() if (@_branch_from && !%tree_map);
1858
1859         my (@tmp_parents, @exec_parents, %seen_parent);
1860         if (my $lparents = $log_msg->{parents}) {
1861                 @tmp_parents = @$lparents
1862         }
1863         # commit parents can be conditionally bound to a particular
1864         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1865         foreach my $p (@parents) {
1866                 next unless defined $p;
1867                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1868                         if ($1 == $log_msg->{revision}) {
1869                                 push @tmp_parents, $2;
1870                         }
1871                 } else {
1872                         push @tmp_parents, $p if $p =~ /$sha1_short/o;
1873                 }
1874         }
1875         my $tree = $log_msg->{tree};
1876         if (!defined $tree) {
1877                 my $index = set_index($GIT_SVN_INDEX);
1878                 index_changes();
1879                 chomp($tree = `git-write-tree`);
1880                 croak $? if $?;
1881                 restore_index($index);
1882         }
1883
1884         # just in case we clobber the existing ref, we still want that ref
1885         # as our parent:
1886         if (my $cur = eval { file_to_s("$GIT_DIR/refs/remotes/$GIT_SVN") }) {
1887                 push @tmp_parents, $cur;
1888         }
1889
1890         if (exists $tree_map{$tree}) {
1891                 foreach my $p (@{$tree_map{$tree}}) {
1892                         my $skip;
1893                         foreach (@tmp_parents) {
1894                                 # see if a common parent is found
1895                                 my $mb = eval {
1896                                         safe_qx('git-merge-base', $_, $p)
1897                                 };
1898                                 next if ($@ || $?);
1899                                 $skip = 1;
1900                                 last;
1901                         }
1902                         next if $skip;
1903                         my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1904                         next if (($SVN_UUID eq $uuid_p) &&
1905                                                 ($log_msg->{revision} > $r_p));
1906                         next if (defined $url_p && defined $SVN_URL &&
1907                                                 ($SVN_UUID eq $uuid_p) &&
1908                                                 ($url_p eq $SVN_URL));
1909                         push @tmp_parents, $p;
1910                 }
1911         }
1912         foreach (@tmp_parents) {
1913                 next if $seen_parent{$_};
1914                 $seen_parent{$_} = 1;
1915                 push @exec_parents, $_;
1916                 # MAXPARENT is defined to 16 in commit-tree.c:
1917                 last if @exec_parents > 16;
1918         }
1919
1920         set_commit_env($log_msg);
1921         my @exec = ('git-commit-tree', $tree);
1922         push @exec, '-p', $_  foreach @exec_parents;
1923         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1924                                                                 or croak $!;
1925         print $msg_fh $log_msg->{msg} or croak $!;
1926         unless ($_no_metadata) {
1927                 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision}",
1928                                         " $SVN_UUID\n" or croak $!;
1929         }
1930         $msg_fh->flush == 0 or croak $!;
1931         close $msg_fh or croak $!;
1932         chomp(my $commit = do { local $/; <$out_fh> });
1933         close $out_fh or croak $!;
1934         waitpid $pid, 0;
1935         croak $? if $?;
1936         if ($commit !~ /^$sha1$/o) {
1937                 die "Failed to commit, invalid sha1: $commit\n";
1938         }
1939         sys('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1940         revdb_set($REVDB, $log_msg->{revision}, $commit);
1941
1942         # this output is read via pipe, do not change:
1943         print "r$log_msg->{revision} = $commit\n";
1944         check_repack();
1945         return $commit;
1946 }
1947
1948 sub check_repack {
1949         if ($_repack && (--$_repack_nr == 0)) {
1950                 $_repack_nr = $_repack;
1951                 sys("git repack $_repack_flags");
1952         }
1953 }
1954
1955 sub set_commit_env {
1956         my ($log_msg) = @_;
1957         my $author = $log_msg->{author};
1958         if (!defined $author || length $author == 0) {
1959                 $author = '(no author)';
1960         }
1961         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1962                                 : ($author,"$author\@$SVN_UUID");
1963         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1964         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1965         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1966 }
1967
1968 sub apply_mod_line_blob {
1969         my $m = shift;
1970         if ($m->{mode_b} =~ /^120/) {
1971                 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1972         } else {
1973                 blob_to_file($m->{sha1_b}, $m->{file_b});
1974         }
1975 }
1976
1977 sub blob_to_symlink {
1978         my ($blob, $link) = @_;
1979         defined $link or croak "\$link not defined!\n";
1980         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1981         if (-l $link || -f _) {
1982                 unlink $link or croak $!;
1983         }
1984
1985         my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1986         symlink $dest, $link or croak $!;
1987 }
1988
1989 sub blob_to_file {
1990         my ($blob, $file) = @_;
1991         defined $file or croak "\$file not defined!\n";
1992         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1993         if (-l $file || -f _) {
1994                 unlink $file or croak $!;
1995         }
1996
1997         open my $blob_fh, '>', $file or croak "$!: $file\n";
1998         my $pid = fork;
1999         defined $pid or croak $!;
2000
2001         if ($pid == 0) {
2002                 open STDOUT, '>&', $blob_fh or croak $!;
2003                 exec('git-cat-file','blob',$blob) or croak $!;
2004         }
2005         waitpid $pid, 0;
2006         croak $? if $?;
2007
2008         close $blob_fh or croak $!;
2009 }
2010
2011 sub safe_qx {
2012         my $pid = open my $child, '-|';
2013         defined $pid or croak $!;
2014         if ($pid == 0) {
2015                 exec(@_) or croak $!;
2016         }
2017         my @ret = (<$child>);
2018         close $child or croak $?;
2019         die $? if $?; # just in case close didn't error out
2020         return wantarray ? @ret : join('',@ret);
2021 }
2022
2023 sub svn_compat_check {
2024         if ($_follow_parent) {
2025                 print STDERR 'E: --follow-parent functionality is only ',
2026                                 "available when SVN libraries are used\n";
2027                 exit 1;
2028         }
2029         my @co_help = safe_qx(qw(svn co -h));
2030         unless (grep /ignore-externals/,@co_help) {
2031                 print STDERR "W: Installed svn version does not support ",
2032                                 "--ignore-externals\n";
2033                 $_no_ignore_ext = 1;
2034         }
2035         if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
2036                 $_svn_co_url_revs = 1;
2037         }
2038         if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
2039                 $_svn_pg_peg_revs = 1;
2040         }
2041
2042         # I really, really hope nobody hits this...
2043         unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
2044                 print STDERR <<'';
2045 W: The installed svn version does not support the --stop-on-copy flag in
2046    the log command.
2047    Lets hope the directory you're tracking is not a branch or tag
2048    and was never moved within the repository...
2049
2050                 $_no_stop_copy = 1;
2051         }
2052 }
2053
2054 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
2055 # (and they won't honor URL@<rev> without -r<rev>, too!)
2056 sub svn_cmd_checkout {
2057         my ($url, $rev, $dir) = @_;
2058         my @cmd = ('svn','co', "-r$rev");
2059         push @cmd, '--ignore-externals' unless $_no_ignore_ext;
2060         $url .= "\@$rev" if $_svn_co_url_revs;
2061         sys(@cmd, $url, $dir);
2062 }
2063
2064 sub check_upgrade_needed {
2065         if (!-r $REVDB) {
2066                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2067                 open my $fh, '>>',$REVDB or croak $!;
2068                 close $fh;
2069         }
2070         my $old = eval {
2071                 my $pid = open my $child, '-|';
2072                 defined $pid or croak $!;
2073                 if ($pid == 0) {
2074                         close STDERR;
2075                         exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
2076                 }
2077                 my @ret = (<$child>);
2078                 close $child or croak $?;
2079                 die $? if $?; # just in case close didn't error out
2080                 return wantarray ? @ret : join('',@ret);
2081         };
2082         return unless $old;
2083         my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
2084         if ($@ || !$head) {
2085                 print STDERR "Please run: $0 rebuild --upgrade\n";
2086                 exit 1;
2087         }
2088 }
2089
2090 # fills %tree_map with a reverse mapping of trees to commits.  Useful
2091 # for finding parents to commit on.
2092 sub map_tree_joins {
2093         my %seen;
2094         foreach my $br (@_branch_from) {
2095                 my $pid = open my $pipe, '-|';
2096                 defined $pid or croak $!;
2097                 if ($pid == 0) {
2098                         exec(qw(git-rev-list --topo-order --pretty=raw), $br)
2099                                                                 or croak $!;
2100                 }
2101                 while (<$pipe>) {
2102                         if (/^commit ($sha1)$/o) {
2103                                 my $commit = $1;
2104
2105                                 # if we've seen a commit,
2106                                 # we've seen its parents
2107                                 last if $seen{$commit};
2108                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
2109                                 unless (defined $tree) {
2110                                         die "Failed to parse commit $commit\n";
2111                                 }
2112                                 push @{$tree_map{$tree}}, $commit;
2113                                 $seen{$commit} = 1;
2114                         }
2115                 }
2116                 close $pipe; # we could be breaking the pipe early
2117         }
2118 }
2119
2120 sub load_all_refs {
2121         if (@_branch_from) {
2122                 print STDERR '--branch|-b parameters are ignored when ',
2123                         "--branch-all-refs|-B is passed\n";
2124         }
2125
2126         # don't worry about rev-list on non-commit objects/tags,
2127         # it shouldn't blow up if a ref is a blob or tree...
2128         chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2129 }
2130
2131 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
2132 sub load_authors {
2133         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2134         while (<$authors>) {
2135                 chomp;
2136                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2137                 my ($user, $name, $email) = ($1, $2, $3);
2138                 $users{$user} = [$name, $email];
2139         }
2140         close $authors or croak $!;
2141 }
2142
2143 sub rload_authors {
2144         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2145         while (<$authors>) {
2146                 chomp;
2147                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2148                 my ($user, $name, $email) = ($1, $2, $3);
2149                 $rusers{"$name <$email>"} = $user;
2150         }
2151         close $authors or croak $!;
2152 }
2153
2154 sub svn_propget_base {
2155         my ($p, $f) = @_;
2156         $f .= '@BASE' if $_svn_pg_peg_revs;
2157         return safe_qx(qw/svn propget/, $p, $f);
2158 }
2159
2160 sub git_svn_each {
2161         my $sub = shift;
2162         foreach (`git-rev-parse --symbolic --all`) {
2163                 next unless s#^refs/remotes/##;
2164                 chomp $_;
2165                 next unless -f "$GIT_DIR/svn/$_/info/url";
2166                 &$sub($_);
2167         }
2168 }
2169
2170 sub migrate_revdb {
2171         git_svn_each(sub {
2172                 my $id = shift;
2173                 defined(my $pid = fork) or croak $!;
2174                 if (!$pid) {
2175                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2176                         init_vars();
2177                         exit 0 if -r $REVDB;
2178                         print "Upgrading svn => git mapping...\n";
2179                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2180                         open my $fh, '>>',$REVDB or croak $!;
2181                         close $fh;
2182                         rebuild();
2183                         print "Done upgrading. You may now delete the ",
2184                                 "deprecated $GIT_SVN_DIR/revs directory\n";
2185                         exit 0;
2186                 }
2187                 waitpid $pid, 0;
2188                 croak $? if $?;
2189         });
2190 }
2191
2192 sub migration_check {
2193         migrate_revdb() unless (-e $REVDB);
2194         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2195         print "Upgrading repository...\n";
2196         unless (-d "$GIT_DIR/svn") {
2197                 mkdir "$GIT_DIR/svn" or croak $!;
2198         }
2199         print "Data from a previous version of git-svn exists, but\n\t",
2200                                 "$GIT_SVN_DIR\n\t(required for this version ",
2201                                 "($VERSION) of git-svn) does not.\n";
2202
2203         foreach my $x (`git-rev-parse --symbolic --all`) {
2204                 next unless $x =~ s#^refs/remotes/##;
2205                 chomp $x;
2206                 next unless -f "$GIT_DIR/$x/info/url";
2207                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2208                 next unless $u;
2209                 my $dn = dirname("$GIT_DIR/svn/$x");
2210                 mkpath([$dn]) unless -d $dn;
2211                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2212         }
2213         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2214         print "Done upgrading.\n";
2215 }
2216
2217 sub find_rev_before {
2218         my ($r, $id, $eq_ok) = @_;
2219         my $f = "$GIT_DIR/svn/$id/.rev_db";
2220         return (undef,undef) unless -r $f;
2221         --$r unless $eq_ok;
2222         while ($r > 0) {
2223                 if (my $c = revdb_get($f, $r)) {
2224                         return ($r, $c);
2225                 }
2226                 --$r;
2227         }
2228         return (undef, undef);
2229 }
2230
2231 sub init_vars {
2232         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2233         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2234         $REVDB = "$GIT_SVN_DIR/.rev_db";
2235         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2236         $SVN_URL = undef;
2237         $SVN_WC = "$GIT_SVN_DIR/tree";
2238         %tree_map = ();
2239 }
2240
2241 # convert GetOpt::Long specs for use by git-repo-config
2242 sub read_repo_config {
2243         return unless -d $GIT_DIR;
2244         my $opts = shift;
2245         foreach my $o (keys %$opts) {
2246                 my $v = $opts->{$o};
2247                 my ($key) = ($o =~ /^([a-z\-]+)/);
2248                 $key =~ s/-//g;
2249                 my $arg = 'git-repo-config';
2250                 $arg .= ' --int' if ($o =~ /[:=]i$/);
2251                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2252                 if (ref $v eq 'ARRAY') {
2253                         chomp(my @tmp = `$arg --get-all svn.$key`);
2254                         @$v = @tmp if @tmp;
2255                 } else {
2256                         chomp(my $tmp = `$arg --get svn.$key`);
2257                         if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2258                                 $$v = $tmp;
2259                         }
2260                 }
2261         }
2262 }
2263
2264 sub set_default_vals {
2265         if (defined $_repack) {
2266                 $_repack = 1000 if ($_repack <= 0);
2267                 $_repack_nr = $_repack;
2268                 $_repack_flags ||= '-d';
2269         }
2270 }
2271
2272 sub read_grafts {
2273         my $gr_file = shift;
2274         my ($grafts, $comments) = ({}, {});
2275         if (open my $fh, '<', $gr_file) {
2276                 my @tmp;
2277                 while (<$fh>) {
2278                         if (/^($sha1)\s+/) {
2279                                 my $c = $1;
2280                                 if (@tmp) {
2281                                         @{$comments->{$c}} = @tmp;
2282                                         @tmp = ();
2283                                 }
2284                                 foreach my $p (split /\s+/, $_) {
2285                                         $grafts->{$c}->{$p} = 1;
2286                                 }
2287                         } else {
2288                                 push @tmp, $_;
2289                         }
2290                 }
2291                 close $fh or croak $!;
2292                 @{$comments->{'END'}} = @tmp if @tmp;
2293         }
2294         return ($grafts, $comments);
2295 }
2296
2297 sub write_grafts {
2298         my ($grafts, $comments, $gr_file) = @_;
2299
2300         open my $fh, '>', $gr_file or croak $!;
2301         foreach my $c (sort keys %$grafts) {
2302                 if ($comments->{$c}) {
2303                         print $fh $_ foreach @{$comments->{$c}};
2304                 }
2305                 my $p = $grafts->{$c};
2306                 my %x; # real parents
2307                 delete $p->{$c}; # commits are not self-reproducing...
2308                 my $pid = open my $ch, '-|';
2309                 defined $pid or croak $!;
2310                 if (!$pid) {
2311                         exec(qw/git-cat-file commit/, $c) or croak $!;
2312                 }
2313                 while (<$ch>) {
2314                         if (/^parent ($sha1)/) {
2315                                 $x{$1} = $p->{$1} = 1;
2316                         } else {
2317                                 last unless /^\S/;
2318                         }
2319                 }
2320                 close $ch; # breaking the pipe
2321
2322                 # if real parents are the only ones in the grafts, drop it
2323                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2324
2325                 my (@ip, @jp, $mb);
2326                 my %del = %x;
2327                 @ip = @jp = keys %$p;
2328                 foreach my $i (@ip) {
2329                         next if $del{$i} || $p->{$i} == 2;
2330                         foreach my $j (@jp) {
2331                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
2332                                 $mb = eval { safe_qx('git-merge-base',$i,$j) };
2333                                 next unless $mb;
2334                                 chomp $mb;
2335                                 next if $x{$mb};
2336                                 if ($mb eq $j) {
2337                                         delete $p->{$i};
2338                                         $del{$i} = 1;
2339                                 } elsif ($mb eq $i) {
2340                                         delete $p->{$j};
2341                                         $del{$j} = 1;
2342                                 }
2343                         }
2344                 }
2345
2346                 # if real parents are the only ones in the grafts, drop it
2347                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2348
2349                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2350         }
2351         if ($comments->{'END'}) {
2352                 print $fh $_ foreach @{$comments->{'END'}};
2353         }
2354         close $fh or croak $!;
2355 }
2356
2357 sub read_url_paths_all {
2358         my ($l_map, $pfx, $p) = @_;
2359         my @dir;
2360         foreach (<$p/*>) {
2361                 if (-r "$_/info/url") {
2362                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2363                         my $id = $pfx . basename $_;
2364                         my $url = file_to_s("$_/info/url");
2365                         my ($u, $p) = repo_path_split($url);
2366                         $l_map->{$u}->{$p} = $id;
2367                 } elsif (-d $_) {
2368                         push @dir, $_;
2369                 }
2370         }
2371         foreach (@dir) {
2372                 my $x = $_;
2373                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
2374                 read_url_paths_all($l_map, $x, $_);
2375         }
2376 }
2377
2378 # this one only gets ids that have been imported, not new ones
2379 sub read_url_paths {
2380         my $l_map = {};
2381         git_svn_each(sub { my $x = shift;
2382                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2383                         my ($u, $p) = repo_path_split($url);
2384                         $l_map->{$u}->{$p} = $x;
2385                         });
2386         return $l_map;
2387 }
2388
2389 sub extract_metadata {
2390         my $id = shift or return (undef, undef, undef);
2391         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2392                                                         \s([a-f\d\-]+)$/x);
2393         if (!$rev || !$uuid || !$url) {
2394                 # some of the original repositories I made had
2395                 # identifiers like this:
2396                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2397         }
2398         return ($url, $rev, $uuid);
2399 }
2400
2401 sub cmt_metadata {
2402         return extract_metadata((grep(/^git-svn-id: /,
2403                 safe_qx(qw/git-cat-file commit/, shift)))[-1]);
2404 }
2405
2406 sub get_commit_time {
2407         my $cmt = shift;
2408         defined(my $pid = open my $fh, '-|') or croak $!;
2409         if (!$pid) {
2410                 exec qw/git-rev-list --pretty=raw -n1/, $cmt or croak $!;
2411         }
2412         while (<$fh>) {
2413                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
2414                 my ($s, $tz) = ($1, $2);
2415                 if ($tz =~ s/^\+//) {
2416                         $s += tz_to_s_offset($tz);
2417                 } elsif ($tz =~ s/^\-//) {
2418                         $s -= tz_to_s_offset($tz);
2419                 }
2420                 close $fh;
2421                 return $s;
2422         }
2423         die "Can't get commit time for commit: $cmt\n";
2424 }
2425
2426 sub tz_to_s_offset {
2427         my ($tz) = @_;
2428         $tz =~ s/(\d\d)$//;
2429         return ($1 * 60) + ($tz * 3600);
2430 }
2431
2432 sub setup_pager { # translated to Perl from pager.c
2433         return unless (-t *STDOUT);
2434         my $pager = $ENV{PAGER};
2435         if (!defined $pager) {
2436                 $pager = 'less';
2437         } elsif (length $pager == 0 || $pager eq 'cat') {
2438                 return;
2439         }
2440         pipe my $rfd, my $wfd or return;
2441         defined(my $pid = fork) or croak $!;
2442         if (!$pid) {
2443                 open STDOUT, '>&', $wfd or croak $!;
2444                 return;
2445         }
2446         open STDIN, '<&', $rfd or croak $!;
2447         $ENV{LESS} ||= '-S';
2448         exec $pager or croak "Can't run pager: $!\n";;
2449 }
2450
2451 sub get_author_info {
2452         my ($dest, $author, $t, $tz) = @_;
2453         $author =~ s/(?:^\s*|\s*$)//g;
2454         $dest->{a_raw} = $author;
2455         my $_a;
2456         if ($_authors) {
2457                 $_a = $rusers{$author} || undef;
2458         }
2459         if (!$_a) {
2460                 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2461         }
2462         $dest->{t} = $t;
2463         $dest->{tz} = $tz;
2464         $dest->{a} = $_a;
2465         # Date::Parse isn't in the standard Perl distro :(
2466         if ($tz =~ s/^\+//) {
2467                 $t += tz_to_s_offset($tz);
2468         } elsif ($tz =~ s/^\-//) {
2469                 $t -= tz_to_s_offset($tz);
2470         }
2471         $dest->{t_utc} = $t;
2472 }
2473
2474 sub process_commit {
2475         my ($c, $r_min, $r_max, $defer) = @_;
2476         if (defined $r_min && defined $r_max) {
2477                 if ($r_min == $c->{r} && $r_min == $r_max) {
2478                         show_commit($c);
2479                         return 0;
2480                 }
2481                 return 1 if $r_min == $r_max;
2482                 if ($r_min < $r_max) {
2483                         # we need to reverse the print order
2484                         return 0 if (defined $_limit && --$_limit < 0);
2485                         push @$defer, $c;
2486                         return 1;
2487                 }
2488                 if ($r_min != $r_max) {
2489                         return 1 if ($r_min < $c->{r});
2490                         return 1 if ($r_max > $c->{r});
2491                 }
2492         }
2493         return 0 if (defined $_limit && --$_limit < 0);
2494         show_commit($c);
2495         return 1;
2496 }
2497
2498 sub show_commit {
2499         my $c = shift;
2500         if ($_oneline) {
2501                 my $x = "\n";
2502                 if (my $l = $c->{l}) {
2503                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2504                         $x = $l->[0];
2505                 }
2506                 $_l_fmt ||= 'A' . length($c->{r});
2507                 print 'r',pack($_l_fmt, $c->{r}),' | ';
2508                 print "$c->{c} | " if $_show_commit;
2509                 print $x;
2510         } else {
2511                 show_commit_normal($c);
2512         }
2513 }
2514
2515 sub show_commit_normal {
2516         my ($c) = @_;
2517         print '-' x72, "\nr$c->{r} | ";
2518         print "$c->{c} | " if $_show_commit;
2519         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2520                                  localtime($c->{t_utc})), ' | ';
2521         my $nr_line = 0;
2522
2523         if (my $l = $c->{l}) {
2524                 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2525                         pop @$l;
2526                 }
2527                 $nr_line = scalar @$l;
2528                 if (!$nr_line) {
2529                         print "1 line\n\n\n";
2530                 } else {
2531                         if ($nr_line == 1) {
2532                                 $nr_line = '1 line';
2533                         } else {
2534                                 $nr_line .= ' lines';
2535                         }
2536                         print $nr_line, "\n\n";
2537                         print $_ foreach @$l;
2538                 }
2539         } else {
2540                 print "1 line\n\n";
2541
2542         }
2543         foreach my $x (qw/raw diff/) {
2544                 if ($c->{$x}) {
2545                         print "\n";
2546                         print $_ foreach @{$c->{$x}}
2547                 }
2548         }
2549 }
2550
2551 sub libsvn_load {
2552         return unless $_use_lib;
2553         $_use_lib = eval {
2554                 require SVN::Core;
2555                 if ($SVN::Core::VERSION lt '1.1.0') {
2556                         die "Need SVN::Core 1.1.0 or better ",
2557                                         "(got $SVN::Core::VERSION) ",
2558                                         "Falling back to command-line svn\n";
2559                 }
2560                 require SVN::Ra;
2561                 require SVN::Delta;
2562                 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2563                 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2564                                         $SVN::Node::dir.$SVN::Node::unknown.
2565                                         $SVN::Node::none.$SVN::Node::file.
2566                                         $SVN::Node::dir.$SVN::Node::unknown;
2567                 1;
2568         };
2569 }
2570
2571 sub libsvn_connect {
2572         my ($url) = @_;
2573         my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2574                           SVN::Client::get_ssl_server_trust_file_provider(),
2575                           SVN::Client::get_username_provider()]);
2576         my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2577         return $s;
2578 }
2579
2580 sub libsvn_get_file {
2581         my ($gui, $f, $rev) = @_;
2582         my $p = $f;
2583         if (length $SVN_PATH > 0) {
2584                 return unless ($p =~ s#^\Q$SVN_PATH\E/##);
2585         }
2586
2587         my ($hash, $pid, $in, $out);
2588         my $pool = SVN::Pool->new;
2589         defined($pid = open3($in, $out, '>&STDERR',
2590                                 qw/git-hash-object -w --stdin/)) or croak $!;
2591         # redirect STDOUT for SVN 1.1.x compatibility
2592         open my $stdout, '>&', \*STDOUT or croak $!;
2593         open STDOUT, '>&', $in or croak $!;
2594         my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
2595         $in->flush == 0 or croak $!;
2596         open STDOUT, '>&', $stdout or croak $!;
2597         close $in or croak $!;
2598         close $stdout or croak $!;
2599         $pool->clear;
2600         chomp($hash = do { local $/; <$out> });
2601         close $out or croak $!;
2602         waitpid $pid, 0;
2603         $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2604
2605         my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2606         if (exists $props->{'svn:special'}) {
2607                 $mode = '120000';
2608                 my $link = `git-cat-file blob $hash`;
2609                 $link =~ s/^link // or die "svn:special file with contents: <",
2610                                                 $link, "> is not understood\n";
2611                 defined($pid = open3($in, $out, '>&STDERR',
2612                                 qw/git-hash-object -w --stdin/)) or croak $!;
2613                 print $in $link;
2614                 $in->flush == 0 or croak $!;
2615                 close $in or croak $!;
2616                 chomp($hash = do { local $/; <$out> });
2617                 close $out or croak $!;
2618                 waitpid $pid, 0;
2619                 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2620         }
2621         print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2622 }
2623
2624 sub libsvn_log_entry {
2625         my ($rev, $author, $date, $msg, $parents) = @_;
2626         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2627                                          (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2628                                 or die "Unable to parse date: $date\n";
2629         if (defined $_authors && ! defined $users{$author}) {
2630                 die "Author: $author not defined in $_authors file\n";
2631         }
2632         $msg = '' if ($rev == 0 && !defined $msg);
2633         return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2634                 author => $author, msg => $msg."\n", parents => $parents || [] }
2635 }
2636
2637 sub process_rm {
2638         my ($gui, $last_commit, $f) = @_;
2639         $f =~ s#^\Q$SVN_PATH\E/?## or return;
2640         # remove entire directories.
2641         if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2642                 defined(my $pid = open my $ls, '-|') or croak $!;
2643                 if (!$pid) {
2644                         exec(qw/git-ls-tree -r --name-only -z/,
2645                                 $last_commit,'--',$f) or croak $!;
2646                 }
2647                 local $/ = "\0";
2648                 while (<$ls>) {
2649                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2650                 }
2651                 close $ls or croak $?;
2652         } else {
2653                 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2654         }
2655 }
2656
2657 sub libsvn_fetch {
2658         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2659         open my $gui, '| git-update-index -z --index-info' or croak $!;
2660         my @amr;
2661         foreach my $f (keys %$paths) {
2662                 my $m = $paths->{$f}->action();
2663                 $f =~ s#^/+##;
2664                 if ($m =~ /^[DR]$/) {
2665                         print "\t$m\t$f\n" unless $_q;
2666                         process_rm($gui, $last_commit, $f);
2667                         next if $m eq 'D';
2668                         # 'R' can be file replacements, too, right?
2669                 }
2670                 my $pool = SVN::Pool->new;
2671                 my $t = $SVN->check_path($f, $rev, $pool);
2672                 if ($t == $SVN::Node::file) {
2673                         if ($m =~ /^[AMR]$/) {
2674                                 push @amr, [ $m, $f ];
2675                         } else {
2676                                 die "Unrecognized action: $m, ($f r$rev)\n";
2677                         }
2678                 } elsif ($t == $SVN::Node::dir && $m =~ /^[AR]$/) {
2679                         my @traversed = ();
2680                         libsvn_traverse($gui, '', $f, $rev, \@traversed);
2681                         foreach (@traversed) {
2682                                 push @amr, [ $m, $_ ]
2683                         }
2684                 }
2685                 $pool->clear;
2686         }
2687         foreach (@amr) {
2688                 print "\t$_->[0]\t$_->[1]\n" unless $_q;
2689                 libsvn_get_file($gui, $_->[1], $rev)
2690         }
2691         close $gui or croak $?;
2692         return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2693 }
2694
2695 sub svn_grab_base_rev {
2696         defined(my $pid = open my $fh, '-|') or croak $!;
2697         if (!$pid) {
2698                 open my $null, '>', '/dev/null' or croak $!;
2699                 open STDERR, '>&', $null or croak $!;
2700                 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2701                                                                 or croak $!;
2702         }
2703         chomp(my $c = do { local $/; <$fh> });
2704         close $fh;
2705         if (defined $c && length $c) {
2706                 my ($url, $rev, $uuid) = cmt_metadata($c);
2707                 return ($rev, $c) if defined $rev;
2708         }
2709         if ($_no_metadata) {
2710                 my $offset = -41; # from tail
2711                 my $rl;
2712                 open my $fh, '<', $REVDB or
2713                         die "--no-metadata specified and $REVDB not readable\n";
2714                 seek $fh, $offset, 2;
2715                 $rl = readline $fh;
2716                 defined $rl or return (undef, undef);
2717                 chomp $rl;
2718                 while ($c ne $rl && tell $fh != 0) {
2719                         $offset -= 41;
2720                         seek $fh, $offset, 2;
2721                         $rl = readline $fh;
2722                         defined $rl or return (undef, undef);
2723                         chomp $rl;
2724                 }
2725                 my $rev = tell $fh;
2726                 croak $! if ($rev < -1);
2727                 $rev =  ($rev - 41) / 41;
2728                 close $fh or croak $!;
2729                 return ($rev, $c);
2730         }
2731         return (undef, undef);
2732 }
2733
2734 sub libsvn_parse_revision {
2735         my $base = shift;
2736         my $head = $SVN->get_latest_revnum();
2737         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2738                 return ($base + 1, $head) if (defined $base);
2739                 return (0, $head);
2740         }
2741         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2742         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2743         if ($_revision =~ /^BASE:(\d+)$/) {
2744                 return ($base + 1, $1) if (defined $base);
2745                 return (0, $head);
2746         }
2747         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2748         die "revision argument: $_revision not understood by git-svn\n",
2749                 "Try using the command-line svn client instead\n";
2750 }
2751
2752 sub libsvn_traverse {
2753         my ($gui, $pfx, $path, $rev, $files) = @_;
2754         my $cwd = "$pfx/$path";
2755         my $pool = SVN::Pool->new;
2756         $cwd =~ s#^/+##g;
2757         my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2758         foreach my $d (keys %$dirent) {
2759                 my $t = $dirent->{$d}->kind;
2760                 if ($t == $SVN::Node::dir) {
2761                         libsvn_traverse($gui, $cwd, $d, $rev, $files);
2762                 } elsif ($t == $SVN::Node::file) {
2763                         my $file = "$cwd/$d";
2764                         if (defined $files) {
2765                                 push @$files, $file;
2766                         } else {
2767                                 print "\tA\t$file\n" unless $_q;
2768                                 libsvn_get_file($gui, $file, $rev);
2769                         }
2770                 }
2771         }
2772         $pool->clear;
2773 }
2774
2775 sub libsvn_traverse_ignore {
2776         my ($fh, $path, $r) = @_;
2777         $path =~ s#^/+##g;
2778         my $pool = SVN::Pool->new;
2779         my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2780         my $p = $path;
2781         $p =~ s#^\Q$SVN_PATH\E/?##;
2782         print $fh length $p ? "\n# $p\n" : "\n# /\n";
2783         if (my $s = $props->{'svn:ignore'}) {
2784                 $s =~ s/[\r\n]+/\n/g;
2785                 chomp $s;
2786                 if (length $p == 0) {
2787                         $s =~ s#\n#\n/$p#g;
2788                         print $fh "/$s\n";
2789                 } else {
2790                         $s =~ s#\n#\n/$p/#g;
2791                         print $fh "/$p/$s\n";
2792                 }
2793         }
2794         foreach (sort keys %$dirent) {
2795                 next if $dirent->{$_}->kind != $SVN::Node::dir;
2796                 libsvn_traverse_ignore($fh, "$path/$_", $r);
2797         }
2798         $pool->clear;
2799 }
2800
2801 sub revisions_eq {
2802         my ($path, $r0, $r1) = @_;
2803         return 1 if $r0 == $r1;
2804         my $nr = 0;
2805         if ($_use_lib) {
2806                 # should be OK to use Pool here (r1 - r0) should be small
2807                 my $pool = SVN::Pool->new;
2808                 libsvn_get_log($SVN, "/$path", $r0, $r1,
2809                                 0, 1, 1, sub {$nr++}, $pool);
2810                 $pool->clear;
2811         } else {
2812                 my ($url, undef) = repo_path_split($SVN_URL);
2813                 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2814                 while (next_log_entry($svn_log)) { $nr++ }
2815                 close $svn_log->{fh};
2816         }
2817         return 0 if ($nr > 1);
2818         return 1;
2819 }
2820
2821 sub libsvn_find_parent_branch {
2822         my ($paths, $rev, $author, $date, $msg) = @_;
2823         my $svn_path = '/'.$SVN_PATH;
2824
2825         # look for a parent from another branch:
2826         my $i = $paths->{$svn_path} or return;
2827         my $branch_from = $i->copyfrom_path or return;
2828         my $r = $i->copyfrom_rev;
2829         print STDERR  "Found possible branch point: ",
2830                                 "$branch_from => $svn_path, $r\n";
2831         $branch_from =~ s#^/##;
2832         my $l_map = {};
2833         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2834         my $url = $SVN->{url};
2835         defined $l_map->{$url} or return;
2836         my $id = $l_map->{$url}->{$branch_from};
2837         if (!defined $id && $_follow_parent) {
2838                 print STDERR "Following parent: $branch_from\@$r\n";
2839                 # auto create a new branch and follow it
2840                 $id = basename($branch_from);
2841                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2842                 while (-r "$GIT_DIR/svn/$id") {
2843                         # just grow a tail if we're not unique enough :x
2844                         $id .= '-';
2845                 }
2846         }
2847         return unless defined $id;
2848
2849         my ($r0, $parent) = find_rev_before($r,$id,1);
2850         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2851                 defined(my $pid = fork) or croak $!;
2852                 if (!$pid) {
2853                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2854                         init_vars();
2855                         $SVN_URL = "$url/$branch_from";
2856                         $SVN_LOG = $SVN = undef;
2857                         setup_git_svn();
2858                         # we can't assume SVN_URL exists at r+1:
2859                         $_revision = "0:$r";
2860                         fetch_lib();
2861                         exit 0;
2862                 }
2863                 waitpid $pid, 0;
2864                 croak $? if $?;
2865                 ($r0, $parent) = find_rev_before($r,$id,1);
2866         }
2867         return unless (defined $r0 && defined $parent);
2868         if (revisions_eq($branch_from, $r0, $r)) {
2869                 unlink $GIT_SVN_INDEX;
2870                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2871                 sys(qw/git-read-tree/, $parent);
2872                 return libsvn_fetch($parent, $paths, $rev,
2873                                         $author, $date, $msg);
2874         }
2875         print STDERR "Nope, branch point not imported or unknown\n";
2876         return undef;
2877 }
2878
2879 sub libsvn_get_log {
2880         my ($ra, @args) = @_;
2881         if ($SVN::Core::VERSION le '1.2.0') {
2882                 splice(@args, 3, 1);
2883         }
2884         $ra->get_log(@args);
2885 }
2886
2887 sub libsvn_new_tree {
2888         if (my $log_entry = libsvn_find_parent_branch(@_)) {
2889                 return $log_entry;
2890         }
2891         my ($paths, $rev, $author, $date, $msg) = @_;
2892         open my $gui, '| git-update-index -z --index-info' or croak $!;
2893         libsvn_traverse($gui, '', $SVN_PATH, $rev);
2894         close $gui or croak $?;
2895         return libsvn_log_entry($rev, $author, $date, $msg);
2896 }
2897
2898 sub find_graft_path_commit {
2899         my ($tree_paths, $p1, $r1) = @_;
2900         foreach my $x (keys %$tree_paths) {
2901                 next unless ($p1 =~ /^\Q$x\E/);
2902                 my $i = $tree_paths->{$x};
2903                 my ($r0, $parent) = find_rev_before($r1,$i,1);
2904                 return $parent if (defined $r0 && $r0 == $r1);
2905                 print STDERR "r$r1 of $i not imported\n";
2906                 next;
2907         }
2908         return undef;
2909 }
2910
2911 sub find_graft_path_parents {
2912         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2913         foreach my $x (keys %$tree_paths) {
2914                 next unless ($p0 =~ /^\Q$x\E/);
2915                 my $i = $tree_paths->{$x};
2916                 my ($r, $parent) = find_rev_before($r0, $i, 1);
2917                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2918                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2919                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2920                         next if ($url_a && $url_b && $url_a eq $url_b &&
2921                                                         $uuid_b eq $uuid_a);
2922                         $grafts->{$c}->{$parent} = 1;
2923                 }
2924         }
2925 }
2926
2927 sub libsvn_graft_file_copies {
2928         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2929         foreach (keys %$paths) {
2930                 my $i = $paths->{$_};
2931                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2932                                         $i->copyfrom_rev);
2933                 next unless (defined $p0 && defined $r0);
2934
2935                 my $p1 = $_;
2936                 $p1 =~ s#^/##;
2937                 $p0 =~ s#^/##;
2938                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2939                 next unless $c;
2940                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2941         }
2942 }
2943
2944 sub set_index {
2945         my $old = $ENV{GIT_INDEX_FILE};
2946         $ENV{GIT_INDEX_FILE} = shift;
2947         return $old;
2948 }
2949
2950 sub restore_index {
2951         my ($old) = @_;
2952         if (defined $old) {
2953                 $ENV{GIT_INDEX_FILE} = $old;
2954         } else {
2955                 delete $ENV{GIT_INDEX_FILE};
2956         }
2957 }
2958
2959 sub libsvn_commit_cb {
2960         my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2961         if ($_optimize_commits && $rev == ($r_last + 1)) {
2962                 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2963                 $log->{tree} = get_tree_from_treeish($c);
2964                 my $cmt = git_commit($log, $cmt_last, $c);
2965                 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2966                 if (@diff) {
2967                         print STDERR "Trees differ: $cmt $c\n",
2968                                         join('',@diff),"\n";
2969                         exit 1;
2970                 }
2971         } else {
2972                 fetch("$rev=$c");
2973         }
2974 }
2975
2976 sub libsvn_ls_fullurl {
2977         my $fullurl = shift;
2978         my ($repo, $path) = repo_path_split($fullurl);
2979         $SVN ||= libsvn_connect($repo);
2980         my @ret;
2981         my $pool = SVN::Pool->new;
2982         my ($dirent, undef, undef) = $SVN->get_dir($path,
2983                                                 $SVN->get_latest_revnum, $pool);
2984         foreach my $d (keys %$dirent) {
2985                 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2986                         push @ret, "$d/"; # add '/' for compat with cli svn
2987                 }
2988         }
2989         $pool->clear;
2990         return @ret;
2991 }
2992
2993
2994 sub libsvn_skip_unknown_revs {
2995         my $err = shift;
2996         my $errno = $err->apr_err();
2997         # Maybe the branch we're tracking didn't
2998         # exist when the repo started, so it's
2999         # not an error if it doesn't, just continue
3000         #
3001         # Wonderfully consistent library, eh?
3002         # 160013 - svn:// and file://
3003         # 175002 - http(s)://
3004         #   More codes may be discovered later...
3005         if ($errno == 175002 || $errno == 160013) {
3006                 return;
3007         }
3008         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3009 };
3010
3011 # Tie::File seems to be prone to offset errors if revisions get sparse,
3012 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3013 # one of my favorite modules is out :<  Next up would be one of the DBM
3014 # modules, but I'm not sure which is most portable...  So I'll just
3015 # go with something that's plain-text, but still capable of
3016 # being randomly accessed.  So here's my ultra-simple fixed-width
3017 # database.  All records are 40 characters + "\n", so it's easy to seek
3018 # to a revision: (41 * rev) is the byte offset.
3019 # A record of 40 0s denotes an empty revision.
3020 # And yes, it's still pretty fast (faster than Tie::File).
3021 sub revdb_set {
3022         my ($file, $rev, $commit) = @_;
3023         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
3024         open my $fh, '+<', $file or croak $!;
3025         my $offset = $rev * 41;
3026         # assume that append is the common case:
3027         seek $fh, 0, 2 or croak $!;
3028         my $pos = tell $fh;
3029         if ($pos < $offset) {
3030                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
3031         }
3032         seek $fh, $offset, 0 or croak $!;
3033         print $fh $commit,"\n";
3034         close $fh or croak $!;
3035 }
3036
3037 sub revdb_get {
3038         my ($file, $rev) = @_;
3039         my $ret;
3040         my $offset = $rev * 41;
3041         open my $fh, '<', $file or croak $!;
3042         seek $fh, $offset, 0;
3043         if (tell $fh == $offset) {
3044                 $ret = readline $fh;
3045                 if (defined $ret) {
3046                         chomp $ret;
3047                         $ret = undef if ($ret =~ /^0{40}$/);
3048                 }
3049         }
3050         close $fh or croak $!;
3051         return $ret;
3052 }
3053
3054 sub copy_remote_ref {
3055         my $origin = $_cp_remote ? $_cp_remote : 'origin';
3056         my $ref = "refs/remotes/$GIT_SVN";
3057         if (safe_qx('git-ls-remote', $origin, $ref)) {
3058                 sys(qw/git fetch/, $origin, "$ref:$ref");
3059         } else {
3060                 die "Unable to find remote reference: ",
3061                                 "refs/remotes/$GIT_SVN on $origin\n";
3062         }
3063 }
3064
3065 package SVN::Git::Editor;
3066 use vars qw/@ISA/;
3067 use strict;
3068 use warnings;
3069 use Carp qw/croak/;
3070 use IO::File;
3071
3072 sub new {
3073         my $class = shift;
3074         my $git_svn = shift;
3075         my $self = SVN::Delta::Editor->new(@_);
3076         bless $self, $class;
3077         foreach (qw/svn_path c r ra /) {
3078                 die "$_ required!\n" unless (defined $git_svn->{$_});
3079                 $self->{$_} = $git_svn->{$_};
3080         }
3081         $self->{pool} = SVN::Pool->new;
3082         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3083         $self->{rm} = { };
3084         require Digest::MD5;
3085         return $self;
3086 }
3087
3088 sub split_path {
3089         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3090 }
3091
3092 sub repo_path {
3093         (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
3094                                         : $_[0]->{svn_path}
3095 }
3096
3097 sub url_path {
3098         my ($self, $path) = @_;
3099         $self->{ra}->{url} . '/' . $self->repo_path($path);
3100 }
3101
3102 sub rmdirs {
3103         my ($self, $q) = @_;
3104         my $rm = $self->{rm};
3105         delete $rm->{''}; # we never delete the url we're tracking
3106         return unless %$rm;
3107
3108         foreach (keys %$rm) {
3109                 my @d = split m#/#, $_;
3110                 my $c = shift @d;
3111                 $rm->{$c} = 1;
3112                 while (@d) {
3113                         $c .= '/' . shift @d;
3114                         $rm->{$c} = 1;
3115                 }
3116         }
3117         delete $rm->{$self->{svn_path}};
3118         delete $rm->{''}; # we never delete the url we're tracking
3119         return unless %$rm;
3120
3121         defined(my $pid = open my $fh,'-|') or croak $!;
3122         if (!$pid) {
3123                 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
3124         }
3125         local $/ = "\0";
3126         my @svn_path = split m#/#, $self->{svn_path};
3127         while (<$fh>) {
3128                 chomp;
3129                 my @dn = (@svn_path, (split m#/#, $_));
3130                 while (pop @dn) {
3131                         delete $rm->{join '/', @dn};
3132                 }
3133                 unless (%$rm) {
3134                         close $fh;
3135                         return;
3136                 }
3137         }
3138         close $fh;
3139
3140         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3141         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3142                 $self->close_directory($bat->{$d}, $p);
3143                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3144                 print "\tD+\t/$d/\n" unless $q;
3145                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3146                 delete $bat->{$d};
3147         }
3148 }
3149
3150 sub open_or_add_dir {
3151         my ($self, $full_path, $baton) = @_;
3152         my $p = SVN::Pool->new;
3153         my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
3154         $p->clear;
3155         if ($t == $SVN::Node::none) {
3156                 return $self->add_directory($full_path, $baton,
3157                                                 undef, -1, $self->{pool});
3158         } elsif ($t == $SVN::Node::dir) {
3159                 return $self->open_directory($full_path, $baton,
3160                                                 $self->{r}, $self->{pool});
3161         }
3162         print STDERR "$full_path already exists in repository at ",
3163                 "r$self->{r} and it is not a directory (",
3164                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3165         exit 1;
3166 }
3167
3168 sub ensure_path {
3169         my ($self, $path) = @_;
3170         my $bat = $self->{bat};
3171         $path = $self->repo_path($path);
3172         return $bat->{''} unless (length $path);
3173         my @p = split m#/+#, $path;
3174         my $c = shift @p;
3175         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3176         while (@p) {
3177                 my $c0 = $c;
3178                 $c .= '/' . shift @p;
3179                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3180         }
3181         return $bat->{$c};
3182 }
3183
3184 sub A {
3185         my ($self, $m, $q) = @_;
3186         my ($dir, $file) = split_path($m->{file_b});
3187         my $pbat = $self->ensure_path($dir);
3188         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3189                                         undef, -1);
3190         print "\tA\t$m->{file_b}\n" unless $q;
3191         $self->chg_file($fbat, $m);
3192         $self->close_file($fbat,undef,$self->{pool});
3193 }
3194
3195 sub C {
3196         my ($self, $m, $q) = @_;
3197         my ($dir, $file) = split_path($m->{file_b});
3198         my $pbat = $self->ensure_path($dir);
3199         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3200                                 $self->url_path($m->{file_a}), $self->{r});
3201         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3202         $self->chg_file($fbat, $m);
3203         $self->close_file($fbat,undef,$self->{pool});
3204 }
3205
3206 sub delete_entry {
3207         my ($self, $path, $pbat) = @_;
3208         my $rpath = $self->repo_path($path);
3209         my ($dir, $file) = split_path($rpath);
3210         $self->{rm}->{$dir} = 1;
3211         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3212 }
3213
3214 sub R {
3215         my ($self, $m, $q) = @_;
3216         my ($dir, $file) = split_path($m->{file_b});
3217         my $pbat = $self->ensure_path($dir);
3218         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3219                                 $self->url_path($m->{file_a}), $self->{r});
3220         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3221         $self->chg_file($fbat, $m);
3222         $self->close_file($fbat,undef,$self->{pool});
3223
3224         ($dir, $file) = split_path($m->{file_a});
3225         $pbat = $self->ensure_path($dir);
3226         $self->delete_entry($m->{file_a}, $pbat);
3227 }
3228
3229 sub M {
3230         my ($self, $m, $q) = @_;
3231         my ($dir, $file) = split_path($m->{file_b});
3232         my $pbat = $self->ensure_path($dir);
3233         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3234                                 $pbat,$self->{r},$self->{pool});
3235         print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3236         $self->chg_file($fbat, $m);
3237         $self->close_file($fbat,undef,$self->{pool});
3238 }
3239
3240 sub T { shift->M(@_) }
3241
3242 sub change_file_prop {
3243         my ($self, $fbat, $pname, $pval) = @_;
3244         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3245 }
3246
3247 sub chg_file {
3248         my ($self, $fbat, $m) = @_;
3249         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3250                 $self->change_file_prop($fbat,'svn:executable','*');
3251         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3252                 $self->change_file_prop($fbat,'svn:executable',undef);
3253         }
3254         my $fh = IO::File->new_tmpfile or croak $!;
3255         if ($m->{mode_b} =~ /^120/) {
3256                 print $fh 'link ' or croak $!;
3257                 $self->change_file_prop($fbat,'svn:special','*');
3258         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3259                 $self->change_file_prop($fbat,'svn:special',undef);
3260         }
3261         defined(my $pid = fork) or croak $!;
3262         if (!$pid) {
3263                 open STDOUT, '>&', $fh or croak $!;
3264                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3265         }
3266         waitpid $pid, 0;
3267         croak $? if $?;
3268         $fh->flush == 0 or croak $!;
3269         seek $fh, 0, 0 or croak $!;
3270
3271         my $md5 = Digest::MD5->new;
3272         $md5->addfile($fh) or croak $!;
3273         seek $fh, 0, 0 or croak $!;
3274
3275         my $exp = $md5->hexdigest;
3276         my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
3277         my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
3278         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3279
3280         close $fh or croak $!;
3281 }
3282
3283 sub D {
3284         my ($self, $m, $q) = @_;
3285         my ($dir, $file) = split_path($m->{file_b});
3286         my $pbat = $self->ensure_path($dir);
3287         print "\tD\t$m->{file_b}\n" unless $q;
3288         $self->delete_entry($m->{file_b}, $pbat);
3289 }
3290
3291 sub close_edit {
3292         my ($self) = @_;
3293         my ($p,$bat) = ($self->{pool}, $self->{bat});
3294         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3295                 $self->close_directory($bat->{$_}, $p);
3296         }
3297         $self->SUPER::close_edit($p);
3298         $p->clear;
3299 }
3300
3301 sub abort_edit {
3302         my ($self) = @_;
3303         $self->SUPER::abort_edit($self->{pool});
3304         $self->{pool}->clear;
3305 }
3306
3307 __END__
3308
3309 Data structures:
3310
3311 $svn_log hashref (as returned by svn_log_raw)
3312 {
3313         fh => file handle of the log file,
3314         state => state of the log file parser (sep/msg/rev/msg_start...)
3315 }
3316
3317 $log_msg hashref as returned by next_log_entry($svn_log)
3318 {
3319         msg => 'whitespace-formatted log entry
3320 ',                                              # trailing newline is preserved
3321         revision => '8',                        # integer
3322         date => '2004-02-24T17:01:44.108345Z',  # commit date
3323         author => 'committer name'
3324 };
3325
3326
3327 @mods = array of diff-index line hashes, each element represents one line
3328         of diff-index output
3329
3330 diff-index line ($m hash)
3331 {
3332         mode_a => first column of diff-index output, no leading ':',
3333         mode_b => second column of diff-index output,
3334         sha1_b => sha1sum of the final blob,
3335         chg => change type [MCRADT],
3336         file_a => original file name of a file (iff chg is 'C' or 'R')
3337         file_b => new/current file name of a file (any chg)
3338 }
3339 ;
3340
3341 # retval of read_url_paths{,_all}();
3342 $l_map = {
3343         # repository root url
3344         'https://svn.musicpd.org' => {
3345                 # repository path               # GIT_SVN_ID
3346                 'mpd/trunk'             =>      'trunk',
3347                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3348         },
3349 }
3350
3351 Notes:
3352         I don't trust the each() function on unless I created %hash myself
3353         because the internal iterator may not have started at base.