Code

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