Code

f453c9ab98ab6d020f9cb95dedd3dfc2a086e665
[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 # properties that we do not log:
25 my %SKIP = ( 'svn:wc:ra_dav:version-url' => 1,
26              'svn:special' => 1,
27              'svn:executable' => 1,
28              'svn:entry:committed-rev' => 1,
29              'svn:entry:last-author' => 1,
30              'svn:entry:uuid' => 1,
31              'svn:entry:committed-date' => 1,
32 );
34 sub fatal (@) { print STDERR @_; exit 1 }
35 # If SVN:: library support is added, please make the dependencies
36 # optional and preserve the capability to use the command-line client.
37 # use eval { require SVN::... } to make it lazy load
38 # We don't use any modules not in the standard Perl distribution:
39 use Carp qw/croak/;
40 use IO::File qw//;
41 use File::Basename qw/dirname basename/;
42 use File::Path qw/mkpath/;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
44 use File::Spec qw//;
45 use File::Copy qw/copy/;
46 use POSIX qw/strftime/;
47 use IPC::Open3;
48 use Memoize;
49 use Git qw/command command_oneline command_noisy
50            command_output_pipe command_input_pipe command_close_pipe/;
51 memoize('revisions_eq');
52 memoize('cmt_metadata');
53 memoize('get_commit_time');
55 my ($SVN, $_use_lib);
57 sub nag_lib {
58         print STDERR <<EOF;
59 ! Please consider installing the SVN Perl libraries (version 1.1.0 or
60 ! newer).  You will generally get better performance and fewer bugs,
61 ! especially if you:
62 ! 1) have a case-insensitive filesystem
63 ! 2) replace symlinks with files (and vice-versa) in commits
65 EOF
66 }
68 $_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
69 libsvn_load();
70 nag_lib() unless $_use_lib;
72 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
73 my $sha1 = qr/[a-f\d]{40}/;
74 my $sha1_short = qr/[a-f\d]{4,40}/;
75 my $_esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
76 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
77         $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
78         $_repack, $_repack_nr, $_repack_flags, $_q,
79         $_message, $_file, $_follow_parent, $_no_metadata,
80         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
81         $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
82         $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
83         $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
84         $_username, $_config_dir, $_no_auth_cache, $_xfer_delta,
85         $_pager, $_color);
86 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
87 my ($_svn_co_url_revs, $_svn_pg_peg_revs, $_svn_can_do_switch);
88 my @repo_path_split_cache;
90 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
91                 'branch|b=s' => \@_branch_from,
92                 'follow-parent|follow' => \$_follow_parent,
93                 'branch-all-refs|B' => \$_branch_all_refs,
94                 'authors-file|A=s' => \$_authors,
95                 'repack:i' => \$_repack,
96                 'no-metadata' => \$_no_metadata,
97                 'quiet|q' => \$_q,
98                 'username=s' => \$_username,
99                 'config-dir=s' => \$_config_dir,
100                 'no-auth-cache' => \$_no_auth_cache,
101                 'ignore-nodate' => \$_ignore_nodate,
102                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
104 my ($_trunk, $_tags, $_branches);
105 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
106                 'tags|t=s' => \$_tags,
107                 'branches|b=s' => \$_branches );
108 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
109 my %cmt_opts = ( 'edit|e' => \$_edit,
110                 'rmdir' => \$_rmdir,
111                 'find-copies-harder' => \$_find_copies_harder,
112                 'l=i' => \$_l,
113                 'copy-similarity|C=i'=> \$_cp_similarity
114 );
116 my %cmd = (
117         fetch => [ \&fetch, "Download new revisions from SVN",
118                         { 'revision|r=s' => \$_revision, %fc_opts } ],
119         init => [ \&init, "Initialize a repo for tracking" .
120                           " (requires URL argument)",
121                           \%init_opts ],
122         commit => [ \&commit, "Commit git revisions to SVN",
123                         {       'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
124         'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
125                         { 'revision|r=i' => \$_revision } ],
126         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
127                         { 'no-ignore-externals' => \$_no_ignore_ext,
128                           'copy-remote|remote=s' => \$_cp_remote,
129                           'upgrade' => \$_upgrade } ],
130         'graft-branches' => [ \&graft_branches,
131                         'Detect merges/branches from already imported history',
132                         { 'merge-rx|m' => \@_opt_m,
133                           'branch|b=s' => \@_branch_from,
134                           'branch-all-refs|B' => \$_branch_all_refs,
135                           'no-default-regex' => \$_no_default_regex,
136                           'no-graft-copy' => \$_no_graft_copy } ],
137         'multi-init' => [ \&multi_init,
138                         'Initialize multiple trees (like git-svnimport)',
139                         { %multi_opts, %init_opts,
140                          'revision|r=i' => \$_revision,
141                          'username=s' => \$_username,
142                          'config-dir=s' => \$_config_dir,
143                          'no-auth-cache' => \$_no_auth_cache,
144                         } ],
145         'multi-fetch' => [ \&multi_fetch,
146                         'Fetch multiple trees (like git-svnimport)',
147                         \%fc_opts ],
148         'log' => [ \&show_log, 'Show commit logs',
149                         { 'limit=i' => \$_limit,
150                           'revision|r=s' => \$_revision,
151                           'verbose|v' => \$_verbose,
152                           'incremental' => \$_incremental,
153                           'oneline' => \$_oneline,
154                           'show-commit' => \$_show_commit,
155                           'non-recursive' => \$_non_recursive,
156                           'authors-file|A=s' => \$_authors,
157                           'color' => \$_color,
158                           'pager=s' => \$_pager,
159                         } ],
160         'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
161                         { 'message|m=s' => \$_message,
162                           'file|F=s' => \$_file,
163                           'revision|r=s' => \$_revision,
164                         %cmt_opts } ],
165         dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
166                         { 'merge|m|M' => \$_merge,
167                           'strategy|s=s' => \$_strategy,
168                           'dry-run|n' => \$_dry_run,
169                         %cmt_opts } ],
170 );
172 my $cmd;
173 for (my $i = 0; $i < @ARGV; $i++) {
174         if (defined $cmd{$ARGV[$i]}) {
175                 $cmd = $ARGV[$i];
176                 splice @ARGV, $i, 1;
177                 last;
178         }
179 };
181 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
183 read_repo_config(\%opts);
184 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
185                                 'version|V' => \$_version,
186                                 'id|i=s' => \$GIT_SVN);
187 exit 1 if (!$rv && $cmd ne 'log');
189 set_default_vals();
190 usage(0) if $_help;
191 version() if $_version;
192 usage(1) unless defined $cmd;
193 init_vars();
194 load_authors() if $_authors;
195 load_all_refs() if $_branch_all_refs;
196 svn_compat_check() unless $_use_lib;
197 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
198 $cmd{$cmd}->[0]->(@ARGV);
199 exit 0;
201 ####################### primary functions ######################
202 sub usage {
203         my $exit = shift || 0;
204         my $fd = $exit ? \*STDERR : \*STDOUT;
205         print $fd <<"";
206 git-svn - bidirectional operations between a single Subversion tree and git
207 Usage: $0 <command> [options] [arguments]\n
209         print $fd "Available commands:\n" unless $cmd;
211         foreach (sort keys %cmd) {
212                 next if $cmd && $cmd ne $_;
213                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
214                 foreach (keys %{$cmd{$_}->[2]}) {
215                         # prints out arguments as they should be passed:
216                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
217                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
218                                                         "--$_" : "-$_" }
219                                                 split /\|/,$_)," $x\n";
220                 }
221         }
222         print $fd <<"";
223 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
224 arbitrary identifier if you're tracking multiple SVN branches/repositories in
225 one git repository and want to keep them separate.  See git-svn(1) for more
226 information.
228         exit $exit;
231 sub version {
232         print "git-svn version $VERSION\n";
233         exit 0;
236 sub rebuild {
237         if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
238                 copy_remote_ref();
239         }
240         $SVN_URL = shift or undef;
241         my $newest_rev = 0;
242         if ($_upgrade) {
243                 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
244                               $GIT_SVN-HEAD");
245         } else {
246                 check_upgrade_needed();
247         }
249         my ($rev_list, $ctx) = command_output_pipe("rev-list",
250                                                    "refs/remotes/$GIT_SVN");
251         my $latest;
252         while (<$rev_list>) {
253                 chomp;
254                 my $c = $_;
255                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
256                 my @commit = grep(/^git-svn-id: /,
257                                   command(qw/cat-file commit/, $c));
258                 next if (!@commit); # skip merges
259                 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
260                 if (!defined $rev || !$uuid) {
261                         croak "Unable to extract revision or UUID from ",
262                                 "$c, $commit[$#commit]\n";
263                 }
265                 # if we merged or otherwise started elsewhere, this is
266                 # how we break out of it
267                 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
268                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
270                 unless (defined $latest) {
271                         if (!$SVN_URL && !$url) {
272                                 croak "SVN repository location required: $url\n";
273                         }
274                         $SVN_URL ||= $url;
275                         $SVN_UUID ||= $uuid;
276                         setup_git_svn();
277                         $latest = $rev;
278                 }
279                 revdb_set($REVDB, $rev, $c);
280                 print "r$rev = $c\n";
281                 $newest_rev = $rev if ($rev > $newest_rev);
282         }
283         command_close_pipe($rev_list, $ctx);
285         goto out if $_use_lib;
286         if (!chdir $SVN_WC) {
287                 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
288                 chdir $SVN_WC or croak $!;
289         }
291         my $pid = fork;
292         defined $pid or croak $!;
293         if ($pid == 0) {
294                 my @svn_up = qw(svn up);
295                 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
296                 sys(@svn_up,"-r$newest_rev");
297                 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
298                 index_changes();
299                 exec('git-write-tree') or croak $!;
300         }
301         waitpid $pid, 0;
302         croak $? if $?;
303 out:
304         if ($_upgrade) {
305                 print STDERR <<"";
306 Keeping deprecated refs/head/$GIT_SVN-HEAD for now.  Please remove it
307 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
309         }
312 sub init {
313         my $url = shift or die "SVN repository location required " .
314                                 "as a command-line argument\n";
315         $url =~ s!/+$!!; # strip trailing slash
317         if (my $repo_path = shift) {
318                 unless (-d $repo_path) {
319                         mkpath([$repo_path]);
320                 }
321                 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
322                 init_vars();
323         }
325         $SVN_URL = $url;
326         unless (-d $GIT_DIR) {
327                 my @init_db = ('init-db');
328                 push @init_db, "--template=$_template" if defined $_template;
329                 push @init_db, "--shared" if defined $_shared;
330                 command_noisy(@init_db);
331         }
332         setup_git_svn();
335 sub fetch {
336         check_upgrade_needed();
337         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
338         my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
339         if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
340                 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
341         }
342         return $ret;
345 sub fetch_cmd {
346         my (@parents) = @_;
347         my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
348         unless ($_revision) {
349                 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
350         }
351         push @log_args, "-r$_revision";
352         push @log_args, '--stop-on-copy' unless $_no_stop_copy;
354         my $svn_log = svn_log_raw(@log_args);
356         my $base = next_log_entry($svn_log) or croak "No base revision!\n";
357         # don't need last_revision from grab_base_rev() because
358         # user could've specified a different revision to skip (they
359         # didn't want to import certain revisions into git for whatever
360         # reason, so trust $base->{revision} instead.
361         my (undef, $last_commit) = svn_grab_base_rev();
362         unless (-d $SVN_WC) {
363                 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
364                 chdir $SVN_WC or croak $!;
365                 read_uuid();
366                 $last_commit = git_commit($base, @parents);
367                 assert_tree($last_commit);
368         } else {
369                 chdir $SVN_WC or croak $!;
370                 read_uuid();
371                 # looks like a user manually cp'd and svn switch'ed
372                 unless ($last_commit) {
373                         sys(qw/svn revert -R ./);
374                         assert_svn_wc_clean($base->{revision});
375                         $last_commit = git_commit($base, @parents);
376                         assert_tree($last_commit);
377                 }
378         }
379         my @svn_up = qw(svn up);
380         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
381         my $last = $base;
382         while (my $log_msg = next_log_entry($svn_log)) {
383                 if ($last->{revision} >= $log_msg->{revision}) {
384                         croak "Out of order: last >= current: ",
385                                 "$last->{revision} >= $log_msg->{revision}\n";
386                 }
387                 # Revert is needed for cases like:
388                 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
389                 # I can't seem to reproduce something like that on a test...
390                 sys(qw/svn revert -R ./);
391                 assert_svn_wc_clean($last->{revision});
392                 sys(@svn_up,"-r$log_msg->{revision}");
393                 $last_commit = git_commit($log_msg, $last_commit, @parents);
394                 $last = $log_msg;
395         }
396         close $svn_log->{fh};
397         $last->{commit} = $last_commit;
398         return $last;
401 sub fetch_lib {
402         my (@parents) = @_;
403         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
404         $SVN ||= libsvn_connect($SVN_URL);
405         my ($last_rev, $last_commit) = svn_grab_base_rev();
406         my ($base, $head) = libsvn_parse_revision($last_rev);
407         if ($base > $head) {
408                 return { revision => $last_rev, commit => $last_commit }
409         }
410         my $index = set_index($GIT_SVN_INDEX);
412         # limit ourselves and also fork() since get_log won't release memory
413         # after processing a revision and SVN stuff seems to leak
414         my $inc = 1000;
415         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
416         read_uuid();
417         if (defined $last_commit) {
418                 unless (-e $GIT_SVN_INDEX) {
419                         command_noisy('read-tree', $last_commit);
420                 }
421                 my $x = command_oneline('write-tree');
422                 my ($y) = (command(qw/cat-file commit/, $last_commit)
423                                                         =~ /^tree ($sha1)/m);
424                 if ($y ne $x) {
425                         unlink $GIT_SVN_INDEX or croak $!;
426                         command_noisy('read-tree', $last_commit);
427                 }
428                 $x = command_oneline('write-tree');
429                 if ($y ne $x) {
430                         print STDERR "trees ($last_commit) $y != $x\n",
431                                  "Something is seriously wrong...\n";
432                 }
433         }
434         while (1) {
435                 # fork, because using SVN::Pool with get_log() still doesn't
436                 # seem to help enough to keep memory usage down.
437                 defined(my $pid = fork) or croak $!;
438                 if (!$pid) {
439                         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
441                         # Yes I'm perfectly aware that the fourth argument
442                         # below is the limit revisions number.  Unfortunately
443                         # performance sucks with it enabled, so it's much
444                         # faster to fetch revision ranges instead of relying
445                         # on the limiter.
446                         libsvn_get_log(libsvn_dup_ra($SVN), [''],
447                                         $min, $max, 0, 1, 1,
448                                 sub {
449                                         my $log_msg;
450                                         if ($last_commit) {
451                                                 $log_msg = libsvn_fetch(
452                                                         $last_commit, @_);
453                                                 $last_commit = git_commit(
454                                                         $log_msg,
455                                                         $last_commit,
456                                                         @parents);
457                                         } else {
458                                                 $log_msg = libsvn_new_tree(@_);
459                                                 $last_commit = git_commit(
460                                                         $log_msg, @parents);
461                                         }
462                                 });
463                         exit 0;
464                 }
465                 waitpid $pid, 0;
466                 croak $? if $?;
467                 ($last_rev, $last_commit) = svn_grab_base_rev();
468                 last if ($max >= $head);
469                 $min = $max + 1;
470                 $max += $inc;
471                 $max = $head if ($max > $head);
472                 $SVN = libsvn_connect($SVN_URL);
473         }
474         restore_index($index);
475         return { revision => $last_rev, commit => $last_commit };
478 sub commit {
479         my (@commits) = @_;
480         check_upgrade_needed();
481         if ($_stdin || !@commits) {
482                 print "Reading from stdin...\n";
483                 @commits = ();
484                 while (<STDIN>) {
485                         if (/\b($sha1_short)\b/o) {
486                                 unshift @commits, $1;
487                         }
488                 }
489         }
490         my @revs;
491         foreach my $c (@commits) {
492                 my @tmp = command('rev-parse',$c);
493                 if (scalar @tmp == 1) {
494                         push @revs, $tmp[0];
495                 } elsif (scalar @tmp > 1) {
496                         push @revs, reverse(command('rev-list',@tmp));
497                 } else {
498                         die "Failed to rev-parse $c\n";
499                 }
500         }
501         $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
502         print "Done committing ",scalar @revs," revisions to SVN\n";
505 sub commit_cmd {
506         my (@revs) = @_;
508         chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
509         my $info = svn_info('.');
510         my $fetched = fetch();
511         if ($info->{Revision} != $fetched->{revision}) {
512                 print STDERR "There are new revisions that were fetched ",
513                                 "and need to be merged (or acknowledged) ",
514                                 "before committing.\n";
515                 exit 1;
516         }
517         $info = svn_info('.');
518         read_uuid($info);
519         my $last = $fetched;
520         foreach my $c (@revs) {
521                 my $mods = svn_checkout_tree($last, $c);
522                 if (scalar @$mods == 0) {
523                         print "Skipping, no changes detected\n";
524                         next;
525                 }
526                 $last = svn_commit_tree($last, $c);
527         }
530 sub commit_lib {
531         my (@revs) = @_;
532         my ($r_last, $cmt_last) = svn_grab_base_rev();
533         defined $r_last or die "Must have an existing revision to commit\n";
534         my $fetched = fetch();
535         if ($r_last != $fetched->{revision}) {
536                 print STDERR "There are new revisions that were fetched ",
537                                 "and need to be merged (or acknowledged) ",
538                                 "before committing.\n",
539                                 "last rev: $r_last\n",
540                                 " current: $fetched->{revision}\n";
541                 exit 1;
542         }
543         read_uuid();
544         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
545         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
547         my $repo;
548         set_svn_commit_env();
549         foreach my $c (@revs) {
550                 my $log_msg = get_commit_message($c, $commit_msg);
552                 # fork for each commit because there's a memory leak I
553                 # can't track down... (it's probably in the SVN code)
554                 defined(my $pid = open my $fh, '-|') or croak $!;
555                 if (!$pid) {
556                         my $ed = SVN::Git::Editor->new(
557                                         {       r => $r_last,
558                                                 ra => libsvn_dup_ra($SVN),
559                                                 c => $c,
560                                                 svn_path => $SVN->{svn_path},
561                                         },
562                                         $SVN->get_commit_editor(
563                                                 $log_msg->{msg},
564                                                 sub {
565                                                         libsvn_commit_cb(
566                                                                 @_, $c,
567                                                                 $log_msg->{msg},
568                                                                 $r_last,
569                                                                 $cmt_last)
570                                                 },
571                                                 @lock)
572                                         );
573                         my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
574                         if (@$mods == 0) {
575                                 print "No changes\nr$r_last = $cmt_last\n";
576                                 $ed->abort_edit;
577                         } else {
578                                 $ed->close_edit;
579                         }
580                         exit 0;
581                 }
582                 my ($r_new, $cmt_new, $no);
583                 while (<$fh>) {
584                         print $_;
585                         chomp;
586                         if (/^r(\d+) = ($sha1)$/o) {
587                                 ($r_new, $cmt_new) = ($1, $2);
588                         } elsif ($_ eq 'No changes') {
589                                 $no = 1;
590                         }
591                 }
592                 close $fh or exit 1;
593                 if (! defined $r_new && ! defined $cmt_new) {
594                         unless ($no) {
595                                 die "Failed to parse revision information\n";
596                         }
597                 } else {
598                         ($r_last, $cmt_last) = ($r_new, $cmt_new);
599                 }
600         }
601         $ENV{LC_ALL} = 'C';
602         unlink $commit_msg;
605 sub dcommit {
606         my $head = shift || 'HEAD';
607         my $gs = "refs/remotes/$GIT_SVN";
608         my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
609         my $last_rev;
610         foreach my $d (reverse @refs) {
611                 if (!verify_ref("$d~1")) {
612                         die "Commit $d\n",
613                             "has no parent commit, and therefore ",
614                             "nothing to diff against.\n",
615                             "You should be working from a repository ",
616                             "originally created by git-svn\n";
617                 }
618                 unless (defined $last_rev) {
619                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
620                         unless (defined $last_rev) {
621                                 die "Unable to extract revision information ",
622                                     "from commit $d~1\n";
623                         }
624                 }
625                 if ($_dry_run) {
626                         print "diff-tree $d~1 $d\n";
627                 } else {
628                         if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
629                                 $last_rev = $r;
630                         } # else: no changes, same $last_rev
631                 }
632         }
633         return if $_dry_run;
634         fetch();
635         my @diff = command('diff-tree', $head, $gs, '--');
636         my @finish;
637         if (@diff) {
638                 @finish = qw/rebase/;
639                 push @finish, qw/--merge/ if $_merge;
640                 push @finish, "--strategy=$_strategy" if $_strategy;
641                 print STDERR "W: $head and $gs differ, using @finish:\n", @diff;
642         } else {
643                 print "No changes between current $head and $gs\n",
644                       "Resetting to the latest $gs\n";
645                 @finish = qw/reset --mixed/;
646         }
647         command_noisy(@finish, $gs);
650 sub show_ignore {
651         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
652         $_use_lib ? show_ignore_lib() : show_ignore_cmd();
655 sub show_ignore_cmd {
656         require File::Find or die $!;
657         if (defined $_revision) {
658                 die "-r/--revision option doesn't work unless the Perl SVN ",
659                         "libraries are used\n";
660         }
661         chdir $SVN_WC or croak $!;
662         my %ign;
663         File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
664                 s#^\./##;
665                 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
666                 }}, no_chdir=>1},'.');
668         print "\n# /\n";
669         foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
670         delete $ign{'.'};
671         foreach my $i (sort keys %ign) {
672                 print "\n# ",$i,"\n";
673                 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
674         }
677 sub show_ignore_lib {
678         my $repo;
679         $SVN ||= libsvn_connect($SVN_URL);
680         my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
681         libsvn_traverse_ignore(\*STDOUT, $SVN->{svn_path}, $r);
684 sub graft_branches {
685         my $gr_file = "$GIT_DIR/info/grafts";
686         my ($grafts, $comments) = read_grafts($gr_file);
687         my $gr_sha1;
689         if (%$grafts) {
690                 # temporarily disable our grafts file to make this idempotent
691                 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
692                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
693         }
695         my $l_map = read_url_paths();
696         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
697         unless ($_no_default_regex) {
698                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
699                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
700                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
701         }
702         foreach my $u (keys %$l_map) {
703                 if (@re) {
704                         foreach my $p (keys %{$l_map->{$u}}) {
705                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
706                         }
707                 }
708                 unless ($_no_graft_copy) {
709                         if ($_use_lib) {
710                                 graft_file_copy_lib($grafts,$l_map,$u);
711                         } else {
712                                 graft_file_copy_cmd($grafts,$l_map,$u);
713                         }
714                 }
715         }
716         graft_tree_joins($grafts);
718         write_grafts($grafts, $comments, $gr_file);
719         unlink "$gr_file~$gr_sha1" if $gr_sha1;
722 sub multi_init {
723         my $url = shift;
724         $_trunk ||= 'trunk';
725         $_trunk =~ s#/+$##;
726         $url =~ s#/+$## if $url;
727         if ($_trunk !~ m#^[a-z\+]+://#) {
728                 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
729                 unless ($url) {
730                         print STDERR "E: '$_trunk' is not a complete URL ",
731                                 "and a separate URL is not specified\n";
732                         exit 1;
733                 }
734                 $_trunk = $url . $_trunk;
735         }
736         my $ch_id;
737         if ($GIT_SVN eq 'git-svn') {
738                 $ch_id = 1;
739                 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
740         }
741         init_vars();
742         unless (-d $GIT_SVN_DIR) {
743                 print "GIT_SVN_ID set to 'trunk' for $_trunk\n" if $ch_id;
744                 init($_trunk);
745                 command_noisy('repo-config', 'svn.trunk', $_trunk);
746         }
747         complete_url_ls_init($url, $_branches, '--branches/-b', '');
748         complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
751 sub multi_fetch {
752         # try to do trunk first, since branches/tags
753         # may be descended from it.
754         if (-e "$GIT_DIR/svn/trunk/info/url") {
755                 fetch_child_id('trunk', @_);
756         }
757         rec_fetch('', "$GIT_DIR/svn", @_);
760 sub show_log {
761         my (@args) = @_;
762         my ($r_min, $r_max);
763         my $r_last = -1; # prevent dupes
764         rload_authors() if $_authors;
765         if (defined $TZ) {
766                 $ENV{TZ} = $TZ;
767         } else {
768                 delete $ENV{TZ};
769         }
770         if (defined $_revision) {
771                 if ($_revision =~ /^(\d+):(\d+)$/) {
772                         ($r_min, $r_max) = ($1, $2);
773                 } elsif ($_revision =~ /^\d+$/) {
774                         $r_min = $r_max = $_revision;
775                 } else {
776                         print STDERR "-r$_revision is not supported, use ",
777                                 "standard \'git log\' arguments instead\n";
778                         exit 1;
779                 }
780         }
782         config_pager();
783         @args = (git_svn_log_cmd($r_min, $r_max), @args);
784         my $log = command_output_pipe(@args);
785         run_pager();
786         my (@k, $c, $d);
788         while (<$log>) {
789                 if (/^${_esc_color}commit ($sha1_short)/o) {
790                         my $cmt = $1;
791                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
792                                 $r_last = $c->{r};
793                                 process_commit($c, $r_min, $r_max, \@k) or
794                                                                 goto out;
795                         }
796                         $d = undef;
797                         $c = { c => $cmt };
798                 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
799                         get_author_info($c, $1, $2, $3);
800                 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
801                         # ignore
802                 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
803                         push @{$c->{raw}}, $_;
804                 } elsif (/^${_esc_color}[ACRMDT]\t/) {
805                         # we could add $SVN->{svn_path} here, but that requires
806                         # remote access at the moment (repo_path_split)...
807                         s#^(${_esc_color})([ACRMDT])\t#$1   $2 #;
808                         push @{$c->{changed}}, $_;
809                 } elsif (/^${_esc_color}diff /) {
810                         $d = 1;
811                         push @{$c->{diff}}, $_;
812                 } elsif ($d) {
813                         push @{$c->{diff}}, $_;
814                 } elsif (/^${_esc_color}    (git-svn-id:.+)$/) {
815                         ($c->{url}, $c->{r}, undef) = extract_metadata($1);
816                 } elsif (s/^${_esc_color}    //) {
817                         push @{$c->{l}}, $_;
818                 }
819         }
820         if ($c && defined $c->{r} && $c->{r} != $r_last) {
821                 $r_last = $c->{r};
822                 process_commit($c, $r_min, $r_max, \@k);
823         }
824         if (@k) {
825                 my $swap = $r_max;
826                 $r_max = $r_min;
827                 $r_min = $swap;
828                 process_commit($_, $r_min, $r_max) foreach reverse @k;
829         }
830 out:
831         eval { command_close_pipe($log) };
832         print '-' x72,"\n" unless $_incremental || $_oneline;
835 sub commit_diff_usage {
836         print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
837         exit 1
840 sub commit_diff {
841         if (!$_use_lib) {
842                 print STDERR "commit-diff must be used with SVN libraries\n";
843                 exit 1;
844         }
845         my $ta = shift or commit_diff_usage();
846         my $tb = shift or commit_diff_usage();
847         if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
848                 print STDERR "Needed URL or usable git-svn id command-line\n";
849                 commit_diff_usage();
850         }
851         my $r = shift;
852         unless (defined $r) {
853                 if (defined $_revision) {
854                         $r = $_revision
855                 } else {
856                         die "-r|--revision is a required argument\n";
857                 }
858         }
859         if (defined $_message && defined $_file) {
860                 print STDERR "Both --message/-m and --file/-F specified ",
861                                 "for the commit message.\n",
862                                 "I have no idea what you mean\n";
863                 exit 1;
864         }
865         if (defined $_file) {
866                 $_message = file_to_s($_file);
867         } else {
868                 $_message ||= get_commit_message($tb,
869                                         "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
870         }
871         $SVN ||= libsvn_connect($SVN_URL);
872         if ($r eq 'HEAD') {
873                 $r = $SVN->get_latest_revnum;
874         } elsif ($r !~ /^\d+$/) {
875                 die "revision argument: $r not understood by git-svn\n";
876         }
877         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
878         my $rev_committed;
879         my $ed = SVN::Git::Editor->new({        r => $r,
880                                                 ra => libsvn_dup_ra($SVN),
881                                                 c => $tb,
882                                                 svn_path => $SVN->{svn_path}
883                                         },
884                                 $SVN->get_commit_editor($_message,
885                                         sub {
886                                                 $rev_committed = $_[0];
887                                                 print "Committed $_[0]\n";
888                                         }, @lock)
889                                 );
890         eval {
891                 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
892                 if (@$mods == 0) {
893                         print "No changes\n$ta == $tb\n";
894                         $ed->abort_edit;
895                 } else {
896                         $ed->close_edit;
897                 }
898         };
899         fatal "$@\n" if $@;
900         $_message = $_file = undef;
901         return $rev_committed;
904 ########################### utility functions #########################
906 sub cmt_showable {
907         my ($c) = @_;
908         return 1 if defined $c->{r};
909         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
910                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
911                 my @msg = command(qw/cat-file commit/, $c->{c});
912                 shift @msg while ($msg[0] ne "\n");
913                 shift @msg;
914                 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
916                 (undef, $c->{r}, undef) = extract_metadata(
917                                 (grep(/^git-svn-id: /, @msg))[-1]);
918         }
919         return defined $c->{r};
922 sub log_use_color {
923         return 1 if $_color;
924         my ($dc, $dcvar);
925         $dcvar = 'color.diff';
926         $dc = `git-repo-config --get $dcvar`;
927         if ($dc eq '') {
928                 # nothing at all; fallback to "diff.color"
929                 $dcvar = 'diff.color';
930                 $dc = `git-repo-config --get $dcvar`;
931         }
932         chomp($dc);
933         if ($dc eq 'auto') {
934                 my $pc;
935                 $pc = `git-repo-config --get color.pager`;
936                 if ($pc eq '') {
937                         # does not have it -- fallback to pager.color
938                         $pc = `git-repo-config --bool --get pager.color`;
939                 }
940                 else {
941                         $pc = `git-repo-config --bool --get color.pager`;
942                         if ($?) {
943                                 $pc = 'false';
944                         }
945                 }
946                 chomp($pc);
947                 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
948                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
949                 }
950                 return 0;
951         }
952         return 0 if $dc eq 'never';
953         return 1 if $dc eq 'always';
954         chomp($dc = `git-repo-config --bool --get $dcvar`);
955         return ($dc eq 'true');
958 sub git_svn_log_cmd {
959         my ($r_min, $r_max) = @_;
960         my @cmd = (qw/log --abbrev-commit --pretty=raw
961                         --default/, "refs/remotes/$GIT_SVN");
962         push @cmd, '-r' unless $_non_recursive;
963         push @cmd, qw/--raw --name-status/ if $_verbose;
964         push @cmd, '--color' if log_use_color();
965         return @cmd unless defined $r_max;
966         if ($r_max == $r_min) {
967                 push @cmd, '--max-count=1';
968                 if (my $c = revdb_get($REVDB, $r_max)) {
969                         push @cmd, $c;
970                 }
971         } else {
972                 my ($c_min, $c_max);
973                 $c_max = revdb_get($REVDB, $r_max);
974                 $c_min = revdb_get($REVDB, $r_min);
975                 if (defined $c_min && defined $c_max) {
976                         if ($r_max > $r_max) {
977                                 push @cmd, "$c_min..$c_max";
978                         } else {
979                                 push @cmd, "$c_max..$c_min";
980                         }
981                 } elsif ($r_max > $r_min) {
982                         push @cmd, $c_max;
983                 } else {
984                         push @cmd, $c_min;
985                 }
986         }
987         return @cmd;
990 sub fetch_child_id {
991         my $id = shift;
992         print "Fetching $id\n";
993         my $ref = "$GIT_DIR/refs/remotes/$id";
994         defined(my $pid = open my $fh, '-|') or croak $!;
995         if (!$pid) {
996                 $_repack = undef;
997                 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
998                 init_vars();
999                 fetch(@_);
1000                 exit 0;
1001         }
1002         while (<$fh>) {
1003                 print $_;
1004                 check_repack() if (/^r\d+ = $sha1/);
1005         }
1006         close $fh or croak $?;
1009 sub rec_fetch {
1010         my ($pfx, $p, @args) = @_;
1011         my @dir;
1012         foreach (sort <$p/*>) {
1013                 if (-r "$_/info/url") {
1014                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1015                         my $id = $pfx . basename $_;
1016                         next if $id eq 'trunk';
1017                         fetch_child_id($id, @args);
1018                 } elsif (-d $_) {
1019                         push @dir, $_;
1020                 }
1021         }
1022         foreach (@dir) {
1023                 my $x = $_;
1024                 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
1025                 rec_fetch($x, $_);
1026         }
1029 sub complete_url_ls_init {
1030         my ($url, $var, $switch, $pfx) = @_;
1031         unless ($var) {
1032                 print STDERR "W: $switch not specified\n";
1033                 return;
1034         }
1035         $var =~ s#/+$##;
1036         if ($var !~ m#^[a-z\+]+://#) {
1037                 $var = '/' . $var if ($var !~ m#^/#);
1038                 unless ($url) {
1039                         print STDERR "E: '$var' is not a complete URL ",
1040                                 "and a separate URL is not specified\n";
1041                         exit 1;
1042                 }
1043                 $var = $url . $var;
1044         }
1045         chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
1046                                 : safe_qx(qw/svn ls --non-interactive/, $var));
1047         my $old = $GIT_SVN;
1048         defined(my $pid = fork) or croak $!;
1049         if (!$pid) {
1050                 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
1051                         $u =~ s#/+$##;
1052                         if ($u !~ m!\Q$var\E/(.+)$!) {
1053                                 print STDERR "W: Unrecognized URL: $u\n";
1054                                 die "This should never happen\n";
1055                         }
1056                         # don't try to init already existing refs
1057                         my $id = $pfx.$1;
1058                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1059                         init_vars();
1060                         unless (-d $GIT_SVN_DIR) {
1061                                 print "init $u => $id\n";
1062                                 init($u);
1063                         }
1064                 }
1065                 exit 0;
1066         }
1067         waitpid $pid, 0;
1068         croak $? if $?;
1069         my ($n) = ($switch =~ /^--(\w+)/);
1070         command_noisy('repo-config', "svn.$n", $var);
1073 sub common_prefix {
1074         my $paths = shift;
1075         my %common;
1076         foreach (@$paths) {
1077                 my @tmp = split m#/#, $_;
1078                 my $p = '';
1079                 while (my $x = shift @tmp) {
1080                         $p .= "/$x";
1081                         $common{$p} ||= 0;
1082                         $common{$p}++;
1083                 }
1084         }
1085         foreach (sort {length $b <=> length $a} keys %common) {
1086                 if ($common{$_} == @$paths) {
1087                         return $_;
1088                 }
1089         }
1090         return '';
1093 # grafts set here are 'stronger' in that they're based on actual tree
1094 # matches, and won't be deleted from merge-base checking in write_grafts()
1095 sub graft_tree_joins {
1096         my $grafts = shift;
1097         map_tree_joins() if (@_branch_from && !%tree_map);
1098         return unless %tree_map;
1100         git_svn_each(sub {
1101                 my $i = shift;
1102                 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
1103                 my ($fh, $ctx) = command_output_pipe(@args);
1104                 while (<$fh>) {
1105                         next unless /^commit ($sha1)$/o;
1106                         my $c = $1;
1107                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
1108                         next unless $tree_map{$t};
1110                         my $l;
1111                         do {
1112                                 $l = readline $fh;
1113                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
1115                         my ($s, $tz) = ($1, $2);
1116                         if ($tz =~ s/^\+//) {
1117                                 $s += tz_to_s_offset($tz);
1118                         } elsif ($tz =~ s/^\-//) {
1119                                 $s -= tz_to_s_offset($tz);
1120                         }
1122                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
1124                         foreach my $p (@{$tree_map{$t}}) {
1125                                 next if $p eq $c;
1126                                 my $mb = eval { command('merge-base', $c, $p) };
1127                                 next unless ($@ || $?);
1128                                 if (defined $r_a) {
1129                                         # see if SVN says it's a relative
1130                                         my ($url_b, $r_b, $uuid_b) =
1131                                                         cmt_metadata($p);
1132                                         next if (defined $url_b &&
1133                                                         defined $url_a &&
1134                                                         ($url_a eq $url_b) &&
1135                                                         ($uuid_a eq $uuid_b));
1136                                         if ($uuid_a eq $uuid_b) {
1137                                                 if ($r_b < $r_a) {
1138                                                         $grafts->{$c}->{$p} = 2;
1139                                                         next;
1140                                                 } elsif ($r_b > $r_a) {
1141                                                         $grafts->{$p}->{$c} = 2;
1142                                                         next;
1143                                                 }
1144                                         }
1145                                 }
1146                                 my $ct = get_commit_time($p);
1147                                 if ($ct < $s) {
1148                                         $grafts->{$c}->{$p} = 2;
1149                                 } elsif ($ct > $s) {
1150                                         $grafts->{$p}->{$c} = 2;
1151                                 }
1152                                 # what should we do when $ct == $s ?
1153                         }
1154                 }
1155                 command_close_pipe($fh, $ctx);
1156         });
1159 # this isn't funky-filename safe, but good enough for now...
1160 sub graft_file_copy_cmd {
1161         my ($grafts, $l_map, $u) = @_;
1162         my $paths = $l_map->{$u};
1163         my $pfx = common_prefix([keys %$paths]);
1164         $SVN_URL ||= $u.$pfx;
1165         my $pid = open my $fh, '-|';
1166         defined $pid or croak $!;
1167         unless ($pid) {
1168                 my @exec = qw/svn log -v/;
1169                 push @exec, "-r$_revision" if defined $_revision;
1170                 exec @exec, $u.$pfx or croak $!;
1171         }
1172         my ($r, $mp) = (undef, undef);
1173         while (<$fh>) {
1174                 chomp;
1175                 if (/^\-{72}$/) {
1176                         $mp = $r = undef;
1177                 } elsif (/^r(\d+) \| /) {
1178                         $r = $1 unless defined $r;
1179                 } elsif (/^Changed paths:/) {
1180                         $mp = 1;
1181                 } elsif ($mp && m#^   [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
1182                         my ($p1, $p0, $r0) = ($1, $2, $3);
1183                         my $c = find_graft_path_commit($paths, $p1, $r);
1184                         next unless $c;
1185                         find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
1186                 }
1187         }
1190 sub graft_file_copy_lib {
1191         my ($grafts, $l_map, $u) = @_;
1192         my $tree_paths = $l_map->{$u};
1193         my $pfx = common_prefix([keys %$tree_paths]);
1194         my ($repo, $path) = repo_path_split($u.$pfx);
1195         $SVN = libsvn_connect($repo);
1197         my ($base, $head) = libsvn_parse_revision();
1198         my $inc = 1000;
1199         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1200         my $eh = $SVN::Error::handler;
1201         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1202         while (1) {
1203                 my $pool = SVN::Pool->new;
1204                 libsvn_get_log(libsvn_dup_ra($SVN), [$path],
1205                                $min, $max, 0, 2, 1,
1206                         sub {
1207                                 libsvn_graft_file_copies($grafts, $tree_paths,
1208                                                         $path, @_);
1209                         }, $pool);
1210                 $pool->clear;
1211                 last if ($max >= $head);
1212                 $min = $max + 1;
1213                 $max += $inc;
1214                 $max = $head if ($max > $head);
1215         }
1216         $SVN::Error::handler = $eh;
1219 sub process_merge_msg_matches {
1220         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1221         my (@strong, @weak);
1222         foreach (@matches) {
1223                 # merging with ourselves is not interesting
1224                 next if $_ eq $p;
1225                 if ($l_map->{$u}->{$_}) {
1226                         push @strong, $_;
1227                 } else {
1228                         push @weak, $_;
1229                 }
1230         }
1231         foreach my $w (@weak) {
1232                 last if @strong;
1233                 # no exact match, use branch name as regexp.
1234                 my $re = qr/\Q$w\E/i;
1235                 foreach (keys %{$l_map->{$u}}) {
1236                         if (/$re/) {
1237                                 push @strong, $l_map->{$u}->{$_};
1238                                 last;
1239                         }
1240                 }
1241                 last if @strong;
1242                 $w = basename($w);
1243                 $re = qr/\Q$w\E/i;
1244                 foreach (keys %{$l_map->{$u}}) {
1245                         if (/$re/) {
1246                                 push @strong, $l_map->{$u}->{$_};
1247                                 last;
1248                         }
1249                 }
1250         }
1251         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1252                                         \s(?:[a-f\d\-]+)$/xsm);
1253         unless (defined $rev) {
1254                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1255                                         \@(?:[a-f\d\-]+)/xsm);
1256                 return unless defined $rev;
1257         }
1258         foreach my $m (@strong) {
1259                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1260                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1261         }
1264 sub graft_merge_msg {
1265         my ($grafts, $l_map, $u, $p, @re) = @_;
1267         my $x = $l_map->{$u}->{$p};
1268         my $rl = rev_list_raw($x);
1269         while (my $c = next_rev_list_entry($rl)) {
1270                 foreach my $re (@re) {
1271                         my (@br) = ($c->{m} =~ /$re/g);
1272                         next unless @br;
1273                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1274                 }
1275         }
1278 sub read_uuid {
1279         return if $SVN_UUID;
1280         if ($_use_lib) {
1281                 my $pool = SVN::Pool->new;
1282                 $SVN_UUID = $SVN->get_uuid($pool);
1283                 $pool->clear;
1284         } else {
1285                 my $info = shift || svn_info('.');
1286                 $SVN_UUID = $info->{'Repository UUID'} or
1287                                         croak "Repository UUID unreadable\n";
1288         }
1291 sub verify_ref {
1292         my ($ref) = @_;
1293         eval { command_oneline([ 'rev-parse', $ref ], { STDERR => 0 }) };
1296 sub quiet_run {
1297         my $pid = fork;
1298         defined $pid or croak $!;
1299         if (!$pid) {
1300                 open my $null, '>', '/dev/null' or croak $!;
1301                 open STDERR, '>&', $null or croak $!;
1302                 open STDOUT, '>&', $null or croak $!;
1303                 exec @_ or croak $!;
1304         }
1305         waitpid $pid, 0;
1306         return $?;
1309 sub repo_path_split {
1310         my $full_url = shift;
1311         $full_url =~ s#/+$##;
1313         foreach (@repo_path_split_cache) {
1314                 if ($full_url =~ s#$_##) {
1315                         my $u = $1;
1316                         $full_url =~ s#^/+##;
1317                         return ($u, $full_url);
1318                 }
1319         }
1320         if ($_use_lib) {
1321                 my $tmp = libsvn_connect($full_url);
1322                 return ($tmp->{repos_root}, $tmp->{svn_path});
1323         } else {
1324                 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1325                 $path =~ s#^/+##;
1326                 my @paths = split(m#/+#, $path);
1327                 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1328                         my $n = shift @paths || last;
1329                         $url .= "/$n";
1330                 }
1331                 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1332                 $path = join('/',@paths);
1333                 return ($url, $path);
1334         }
1337 sub setup_git_svn {
1338         defined $SVN_URL or croak "SVN repository location required\n";
1339         unless (-d $GIT_DIR) {
1340                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1341         }
1342         mkpath([$GIT_SVN_DIR]);
1343         mkpath(["$GIT_SVN_DIR/info"]);
1344         open my $fh, '>>',$REVDB or croak $!;
1345         close $fh;
1346         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1350 sub assert_svn_wc_clean {
1351         return if $_use_lib;
1352         my ($svn_rev) = @_;
1353         croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1354         my $lcr = svn_info('.')->{'Last Changed Rev'};
1355         if ($svn_rev != $lcr) {
1356                 print STDERR "Checking for copy-tree ... ";
1357                 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1358                                                 "-r$lcr:$svn_rev")));
1359                 if (@diff) {
1360                         croak "Nope!  Expected r$svn_rev, got r$lcr\n";
1361                 } else {
1362                         print STDERR "OK!\n";
1363                 }
1364         }
1365         my @status = grep(!/^Performing status on external/,(`svn status`));
1366         @status = grep(!/^\s*$/,@status);
1367         @status = grep(!/^X/,@status) if $_no_ignore_ext;
1368         if (scalar @status) {
1369                 print STDERR "Tree ($SVN_WC) is not clean:\n";
1370                 print STDERR $_ foreach @status;
1371                 croak;
1372         }
1375 sub get_tree_from_treeish {
1376         my ($treeish) = @_;
1377         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1378         my $type = command_oneline(qw/cat-file -t/, $treeish);
1379         my $expected;
1380         while ($type eq 'tag') {
1381                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1382         }
1383         if ($type eq 'commit') {
1384                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1385                                                     $treeish))[0];
1386                 ($expected) = ($expected =~ /^tree ($sha1)$/);
1387                 die "Unable to get tree from $treeish\n" unless $expected;
1388         } elsif ($type eq 'tree') {
1389                 $expected = $treeish;
1390         } else {
1391                 die "$treeish is a $type, expected tree, tag or commit\n";
1392         }
1393         return $expected;
1396 sub assert_tree {
1397         return if $_use_lib;
1398         my ($treeish) = @_;
1399         my $expected = get_tree_from_treeish($treeish);
1401         my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1402         if (-e $tmpindex) {
1403                 unlink $tmpindex or croak $!;
1404         }
1405         my $old_index = set_index($tmpindex);
1406         index_changes(1);
1407         my $tree = command_oneline('write-tree');
1408         restore_index($old_index);
1409         if ($tree ne $expected) {
1410                 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1411         }
1412         unlink $tmpindex;
1415 sub get_diff {
1416         my ($from, $treeish) = @_;
1417         assert_tree($from);
1418         print "diff-tree $from $treeish\n";
1419         my @diff_tree = qw(diff-tree -z -r);
1420         if ($_cp_similarity) {
1421                 push @diff_tree, "-C$_cp_similarity";
1422         } else {
1423                 push @diff_tree, '-C';
1424         }
1425         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1426         push @diff_tree, "-l$_l" if defined $_l;
1427         push @diff_tree, $from, $treeish;
1428         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1429         local $/ = "\0";
1430         my $state = 'meta';
1431         my @mods;
1432         while (<$diff_fh>) {
1433                 chomp $_; # this gets rid of the trailing "\0"
1434                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1435                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1436                         push @mods, {   mode_a => $1, mode_b => $2,
1437                                         sha1_b => $3, chg => $4 };
1438                         if ($4 =~ /^(?:C|R)$/) {
1439                                 $state = 'file_a';
1440                         } else {
1441                                 $state = 'file_b';
1442                         }
1443                 } elsif ($state eq 'file_a') {
1444                         my $x = $mods[$#mods] or croak "Empty array\n";
1445                         if ($x->{chg} !~ /^(?:C|R)$/) {
1446                                 croak "Error parsing $_, $x->{chg}\n";
1447                         }
1448                         $x->{file_a} = $_;
1449                         $state = 'file_b';
1450                 } elsif ($state eq 'file_b') {
1451                         my $x = $mods[$#mods] or croak "Empty array\n";
1452                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1453                                 croak "Error parsing $_, $x->{chg}\n";
1454                         }
1455                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1456                                 croak "Error parsing $_, $x->{chg}\n";
1457                         }
1458                         $x->{file_b} = $_;
1459                         $state = 'meta';
1460                 } else {
1461                         croak "Error parsing $_\n";
1462                 }
1463         }
1464         command_close_pipe($diff_fh, $ctx);
1465         return \@mods;
1468 sub svn_check_prop_executable {
1469         my $m = shift;
1470         return if -l $m->{file_b};
1471         if ($m->{mode_b} =~ /755$/) {
1472                 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1473                 if ($m->{mode_a} !~ /755$/) {
1474                         sys(qw(svn propset svn:executable 1), $m->{file_b});
1475                 }
1476                 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1477         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1478                 sys(qw(svn propdel svn:executable), $m->{file_b});
1479                 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1480                 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1481         }
1484 sub svn_ensure_parent_path {
1485         my $dir_b = dirname(shift);
1486         svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1487         mkpath([$dir_b]) unless (-d $dir_b);
1488         sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1491 sub precommit_check {
1492         my $mods = shift;
1493         my (%rm_file, %rmdir_check, %added_check);
1495         my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1496         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1497                 if ($m->{chg} eq 'R') {
1498                         if (-d $m->{file_b}) {
1499                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1500                         }
1501                         # dir/$file => dir/file/$file
1502                         my $dirname = dirname($m->{file_b});
1503                         while ($dirname ne File::Spec->curdir) {
1504                                 if ($dirname ne $m->{file_a}) {
1505                                         $dirname = dirname($dirname);
1506                                         next;
1507                                 }
1508                                 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1509                         }
1510                         # baz/zzz => baz (baz is a file)
1511                         $dirname = dirname($m->{file_a});
1512                         while ($dirname ne File::Spec->curdir) {
1513                                 if ($dirname ne $m->{file_b}) {
1514                                         $dirname = dirname($dirname);
1515                                         next;
1516                                 }
1517                                 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1518                         }
1519                 }
1520                 if ($m->{chg} =~ /^(D|R)$/) {
1521                         my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1522                         $rm_file{ $m->{$t} } = 1;
1523                         my $dirname = dirname( $m->{$t} );
1524                         my $basename = basename( $m->{$t} );
1525                         $rmdir_check{$dirname}->{$basename} = 1;
1526                 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1527                         if (-d $m->{file_b}) {
1528                                 err_dir_to_file($m->{file_b});
1529                         }
1530                         my $dirname = dirname( $m->{file_b} );
1531                         my $basename = basename( $m->{file_b} );
1532                         $added_check{$dirname}->{$basename} = 1;
1533                         while ($dirname ne File::Spec->curdir) {
1534                                 if ($rm_file{$dirname}) {
1535                                         err_file_to_dir($m->{file_b});
1536                                 }
1537                                 $dirname = dirname $dirname;
1538                         }
1539                 }
1540         }
1541         return (\%rmdir_check, \%added_check);
1543         sub err_dir_to_file {
1544                 my $file = shift;
1545                 print STDERR "Node change from directory to file ",
1546                                 "is not supported by Subversion: ",$file,"\n";
1547                 exit 1;
1548         }
1549         sub err_file_to_dir {
1550                 my $file = shift;
1551                 print STDERR "Node change from file to directory ",
1552                                 "is not supported by Subversion: ",$file,"\n";
1553                 exit 1;
1554         }
1558 sub svn_checkout_tree {
1559         my ($from, $treeish) = @_;
1560         my $mods = get_diff($from->{commit}, $treeish);
1561         return $mods unless (scalar @$mods);
1562         my ($rm, $add) = precommit_check($mods);
1564         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1565         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1566                 if ($m->{chg} eq 'C') {
1567                         svn_ensure_parent_path( $m->{file_b} );
1568                         sys(qw(svn cp),         $m->{file_a}, $m->{file_b});
1569                         apply_mod_line_blob($m);
1570                         svn_check_prop_executable($m);
1571                 } elsif ($m->{chg} eq 'D') {
1572                         sys(qw(svn rm --force), $m->{file_b});
1573                 } elsif ($m->{chg} eq 'R') {
1574                         svn_ensure_parent_path( $m->{file_b} );
1575                         sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1576                         apply_mod_line_blob($m);
1577                         svn_check_prop_executable($m);
1578                 } elsif ($m->{chg} eq 'M') {
1579                         apply_mod_line_blob($m);
1580                         svn_check_prop_executable($m);
1581                 } elsif ($m->{chg} eq 'T') {
1582                         svn_check_prop_executable($m);
1583                         apply_mod_line_blob($m);
1584                         if ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1585                                 sys(qw(svn propdel svn:special), $m->{file_b});
1586                         } else {
1587                                 sys(qw(svn propset svn:special *),$m->{file_b});
1588                         }
1589                 } elsif ($m->{chg} eq 'A') {
1590                         svn_ensure_parent_path( $m->{file_b} );
1591                         apply_mod_line_blob($m);
1592                         sys(qw(svn add), $m->{file_b});
1593                         svn_check_prop_executable($m);
1594                 } else {
1595                         croak "Invalid chg: $m->{chg}\n";
1596                 }
1597         }
1599         assert_tree($treeish);
1600         if ($_rmdir) { # remove empty directories
1601                 handle_rmdir($rm, $add);
1602         }
1603         assert_tree($treeish);
1604         return $mods;
1607 sub libsvn_checkout_tree {
1608         my ($from, $treeish, $ed) = @_;
1609         my $mods = get_diff($from, $treeish);
1610         return $mods unless (scalar @$mods);
1611         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1612         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1613                 my $f = $m->{chg};
1614                 if (defined $o{$f}) {
1615                         $ed->$f($m, $_q);
1616                 } else {
1617                         croak "Invalid change type: $f\n";
1618                 }
1619         }
1620         $ed->rmdirs($_q) if $_rmdir;
1621         return $mods;
1624 # svn ls doesn't work with respect to the current working tree, but what's
1625 # in the repository.  There's not even an option for it... *sigh*
1626 # (added files don't show up and removed files remain in the ls listing)
1627 sub svn_ls_current {
1628         my ($dir, $rm, $add) = @_;
1629         chomp(my @ls = safe_qx('svn','ls',$dir));
1630         my @ret = ();
1631         foreach (@ls) {
1632                 s#/$##; # trailing slashes are evil
1633                 push @ret, $_ unless $rm->{$dir}->{$_};
1634         }
1635         if (exists $add->{$dir}) {
1636                 push @ret, keys %{$add->{$dir}};
1637         }
1638         return \@ret;
1641 sub handle_rmdir {
1642         my ($rm, $add) = @_;
1644         foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1645                 my $ls = svn_ls_current($dir, $rm, $add);
1646                 next if (scalar @$ls);
1647                 sys(qw(svn rm --force),$dir);
1649                 my $dn = dirname $dir;
1650                 $rm->{ $dn }->{ basename $dir } = 1;
1651                 $ls = svn_ls_current($dn, $rm, $add);
1652                 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1653                         sys(qw(svn rm --force),$dn);
1654                         $dir = basename $dn;
1655                         $dn = dirname $dn;
1656                         $rm->{ $dn }->{ $dir } = 1;
1657                         $ls = svn_ls_current($dn, $rm, $add);
1658                 }
1659         }
1662 sub get_commit_message {
1663         my ($commit, $commit_msg) = (@_);
1664         my %log_msg = ( msg => '' );
1665         open my $msg, '>', $commit_msg or croak $!;
1667         my $type = command_oneline(qw/cat-file -t/, $commit);
1668         if ($type eq 'commit' || $type eq 'tag') {
1669                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1670                                                          $type, $commit);
1671                 my $in_msg = 0;
1672                 while (<$msg_fh>) {
1673                         if (!$in_msg) {
1674                                 $in_msg = 1 if (/^\s*$/);
1675                         } elsif (/^git-svn-id: /) {
1676                                 # skip this, we regenerate the correct one
1677                                 # on re-fetch anyways
1678                         } else {
1679                                 print $msg $_ or croak $!;
1680                         }
1681                 }
1682                 command_close_pipe($msg_fh, $ctx);
1683         }
1684         close $msg or croak $!;
1686         if ($_edit || ($type eq 'tree')) {
1687                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1688                 system($editor, $commit_msg);
1689         }
1691         # file_to_s removes all trailing newlines, so just use chomp() here:
1692         open $msg, '<', $commit_msg or croak $!;
1693         { local $/; chomp($log_msg{msg} = <$msg>); }
1694         close $msg or croak $!;
1696         return \%log_msg;
1699 sub set_svn_commit_env {
1700         if (defined $LC_ALL) {
1701                 $ENV{LC_ALL} = $LC_ALL;
1702         } else {
1703                 delete $ENV{LC_ALL};
1704         }
1707 sub svn_commit_tree {
1708         my ($last, $commit) = @_;
1709         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1710         my $log_msg = get_commit_message($commit, $commit_msg);
1711         my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1712         print "Committing $commit: $oneline\n";
1714         set_svn_commit_env();
1715         my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1716         $ENV{LC_ALL} = 'C';
1717         unlink $commit_msg;
1718         my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1719         if (!defined $committed) {
1720                 my $out = join("\n",@ci_output);
1721                 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1722                                 $out, "\n\nAssuming English locale...";
1723                 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1724                 defined $committed or die " FAILED!\n",
1725                         "Commit output failed to parse committed revision!\n",
1726                 print STDERR " OK\n";
1727         }
1729         my @svn_up = qw(svn up);
1730         push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1731         if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1732                 push @svn_up, "-r$committed";
1733                 sys(@svn_up);
1734                 my $info = svn_info('.');
1735                 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1736                 if ($info->{'Last Changed Rev'} != $committed) {
1737                         croak "$info->{'Last Changed Rev'} != $committed\n"
1738                 }
1739                 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1740                                         /(\d{4})\-(\d\d)\-(\d\d)\s
1741                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1742                                          or croak "Failed to parse date: $date\n";
1743                 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1744                 $log_msg->{author} = $info->{'Last Changed Author'};
1745                 $log_msg->{revision} = $committed;
1746                 $log_msg->{msg} .= "\n";
1747                 $log_msg->{parents} = [ $last->{commit} ];
1748                 $log_msg->{commit} = git_commit($log_msg, $commit);
1749                 return $log_msg;
1750         }
1751         # resync immediately
1752         push @svn_up, "-r$last->{revision}";
1753         sys(@svn_up);
1754         return fetch("$committed=$commit");
1757 sub rev_list_raw {
1758         my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1759         return { fh => $fh, ctx => $c, t => { } };
1762 sub next_rev_list_entry {
1763         my $rl = shift;
1764         my $fh = $rl->{fh};
1765         my $x = $rl->{t};
1766         while (<$fh>) {
1767                 if (/^commit ($sha1)$/o) {
1768                         if ($x->{c}) {
1769                                 $rl->{t} = { c => $1 };
1770                                 return $x;
1771                         } else {
1772                                 $x->{c} = $1;
1773                         }
1774                 } elsif (/^parent ($sha1)$/o) {
1775                         $x->{p}->{$1} = 1;
1776                 } elsif (s/^    //) {
1777                         $x->{m} ||= '';
1778                         $x->{m} .= $_;
1779                 }
1780         }
1781         command_close_pipe($fh, $rl->{ctx});
1782         return ($x != $rl->{t}) ? $x : undef;
1785 # read the entire log into a temporary file (which is removed ASAP)
1786 # and store the file handle + parser state
1787 sub svn_log_raw {
1788         my (@log_args) = @_;
1789         my $log_fh = IO::File->new_tmpfile or croak $!;
1790         my $pid = fork;
1791         defined $pid or croak $!;
1792         if (!$pid) {
1793                 open STDOUT, '>&', $log_fh or croak $!;
1794                 exec (qw(svn log), @log_args) or croak $!
1795         }
1796         waitpid $pid, 0;
1797         croak $? if $?;
1798         seek $log_fh, 0, 0 or croak $!;
1799         return { state => 'sep', fh => $log_fh };
1802 sub next_log_entry {
1803         my $log = shift; # retval of svn_log_raw()
1804         my $ret = undef;
1805         my $fh = $log->{fh};
1807         while (<$fh>) {
1808                 chomp;
1809                 if (/^\-{72}$/) {
1810                         if ($log->{state} eq 'msg') {
1811                                 if ($ret->{lines}) {
1812                                         $ret->{msg} .= $_."\n";
1813                                         unless(--$ret->{lines}) {
1814                                                 $log->{state} = 'sep';
1815                                         }
1816                                 } else {
1817                                         croak "Log parse error at: $_\n",
1818                                                 $ret->{revision},
1819                                                 "\n";
1820                                 }
1821                                 next;
1822                         }
1823                         if ($log->{state} ne 'sep') {
1824                                 croak "Log parse error at: $_\n",
1825                                         "state: $log->{state}\n",
1826                                         $ret->{revision},
1827                                         "\n";
1828                         }
1829                         $log->{state} = 'rev';
1831                         # if we have an empty log message, put something there:
1832                         if ($ret) {
1833                                 $ret->{msg} ||= "\n";
1834                                 delete $ret->{lines};
1835                                 return $ret;
1836                         }
1837                         next;
1838                 }
1839                 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1840                         my $rev = $1;
1841                         my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1842                         ($lines) = ($lines =~ /(\d+)/);
1843                         $date = '1970-01-01 00:00:00 +0000'
1844                                 if ($_ignore_nodate && $date eq '(no date)');
1845                         my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1846                                         /(\d{4})\-(\d\d)\-(\d\d)\s
1847                                          (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1848                                          or croak "Failed to parse date: $date\n";
1849                         $ret = {        revision => $rev,
1850                                         date => "$tz $Y-$m-$d $H:$M:$S",
1851                                         author => $author,
1852                                         lines => $lines,
1853                                         msg => '' };
1854                         if (defined $_authors && ! defined $users{$author}) {
1855                                 die "Author: $author not defined in ",
1856                                                 "$_authors file\n";
1857                         }
1858                         $log->{state} = 'msg_start';
1859                         next;
1860                 }
1861                 # skip the first blank line of the message:
1862                 if ($log->{state} eq 'msg_start' && /^$/) {
1863                         $log->{state} = 'msg';
1864                 } elsif ($log->{state} eq 'msg') {
1865                         if ($ret->{lines}) {
1866                                 $ret->{msg} .= $_."\n";
1867                                 unless (--$ret->{lines}) {
1868                                         $log->{state} = 'sep';
1869                                 }
1870                         } else {
1871                                 croak "Log parse error at: $_\n",
1872                                         $ret->{revision},"\n";
1873                         }
1874                 }
1875         }
1876         return $ret;
1879 sub svn_info {
1880         my $url = shift || $SVN_URL;
1882         my $pid = open my $info_fh, '-|';
1883         defined $pid or croak $!;
1885         if ($pid == 0) {
1886                 exec(qw(svn info),$url) or croak $!;
1887         }
1889         my $ret = {};
1890         # only single-lines seem to exist in svn info output
1891         while (<$info_fh>) {
1892                 chomp $_;
1893                 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1894                         $ret->{$1} = $2;
1895                         push @{$ret->{-order}}, $1;
1896                 }
1897         }
1898         close $info_fh or croak $?;
1899         return $ret;
1902 sub sys { system(@_) == 0 or croak $? }
1904 sub do_update_index {
1905         my ($z_cmd, $cmd, $no_text_base) = @_;
1907         my ($p, $pctx) = command_output_pipe(@$z_cmd);
1909         my ($ui, $uctx) = command_input_pipe('update-index',
1910                                              "--$cmd",'-z','--stdin');
1911         local $/ = "\0";
1912         while (my $x = <$p>) {
1913                 chomp $x;
1914                 if (!$no_text_base && lstat $x && ! -l _ &&
1915                                 svn_propget_base('svn:keywords', $x)) {
1916                         my $mode = -x _ ? 0755 : 0644;
1917                         my ($v,$d,$f) = File::Spec->splitpath($x);
1918                         my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1919                                                 'text-base',"$f.svn-base");
1920                         $tb =~ s#^/##;
1921                         unless (-f $tb) {
1922                                 $tb = File::Spec->catfile($d, '.svn',
1923                                                 'text-base',"$f.svn-base");
1924                                 $tb =~ s#^/##;
1925                         }
1926                         my @s = stat($x);
1927                         unlink $x or croak $!;
1928                         copy($tb, $x);
1929                         chmod(($mode &~ umask), $x) or croak $!;
1930                         utime $s[8], $s[9], $x;
1931                 }
1932                 print $ui $x,"\0";
1933         }
1934         command_close_pipe($p, $pctx);
1935         command_close_pipe($ui, $uctx);
1938 sub index_changes {
1939         return if $_use_lib;
1941         if (!-f "$GIT_SVN_DIR/info/exclude") {
1942                 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1943                 print $fd '.svn',"\n";
1944                 close $fd or croak $!;
1945         }
1946         my $no_text_base = shift;
1947         do_update_index([qw/diff-files --name-only -z/],
1948                         'remove',
1949                         $no_text_base);
1950         do_update_index([qw/ls-files -z --others/,
1951                                 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1952                         'add',
1953                         $no_text_base);
1956 sub s_to_file {
1957         my ($str, $file, $mode) = @_;
1958         open my $fd,'>',$file or croak $!;
1959         print $fd $str,"\n" or croak $!;
1960         close $fd or croak $!;
1961         chmod ($mode &~ umask, $file) if (defined $mode);
1964 sub file_to_s {
1965         my $file = shift;
1966         open my $fd,'<',$file or croak "$!: file: $file\n";
1967         local $/;
1968         my $ret = <$fd>;
1969         close $fd or croak $!;
1970         $ret =~ s/\s*$//s;
1971         return $ret;
1974 sub assert_revision_unknown {
1975         my $r = shift;
1976         if (my $c = revdb_get($REVDB, $r)) {
1977                 croak "$r = $c already exists! Why are we refetching it?";
1978         }
1981 sub trees_eq {
1982         my ($x, $y) = @_;
1983         my @x = command(qw/cat-file commit/,$x);
1984         my @y = command(qw/cat-file commit/,$y);
1985         if (($y[0] ne $x[0]) || $x[0] ne "tree $sha1"
1986                              || $y[0] ne "tree $sha1") {
1987                 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1988                 return 0
1989         }
1990         return 1;
1993 sub git_commit {
1994         my ($log_msg, @parents) = @_;
1995         assert_revision_unknown($log_msg->{revision});
1996         map_tree_joins() if (@_branch_from && !%tree_map);
1998         my (@tmp_parents, @exec_parents, %seen_parent);
1999         if (my $lparents = $log_msg->{parents}) {
2000                 @tmp_parents = @$lparents
2001         }
2002         # commit parents can be conditionally bound to a particular
2003         # svn revision via: "svn_revno=commit_sha1", filter them out here:
2004         foreach my $p (@parents) {
2005                 next unless defined $p;
2006                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
2007                         if ($1 == $log_msg->{revision}) {
2008                                 push @tmp_parents, $2;
2009                         }
2010                 } else {
2011                         push @tmp_parents, $p if $p =~ /$sha1_short/o;
2012                 }
2013         }
2014         my $tree = $log_msg->{tree};
2015         if (!defined $tree) {
2016                 my $index = set_index($GIT_SVN_INDEX);
2017                 index_changes();
2018                 $tree = command_oneline('write-tree');
2019                 croak $? if $?;
2020                 restore_index($index);
2021         }
2023         # just in case we clobber the existing ref, we still want that ref
2024         # as our parent:
2025         if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
2026                 chomp $cur;
2027                 push @tmp_parents, $cur;
2028         }
2030         if (exists $tree_map{$tree}) {
2031                 foreach my $p (@{$tree_map{$tree}}) {
2032                         my $skip;
2033                         foreach (@tmp_parents) {
2034                                 # see if a common parent is found
2035                                 my $mb = eval { command('merge-base', $_, $p) };
2036                                 next if ($@ || $?);
2037                                 $skip = 1;
2038                                 last;
2039                         }
2040                         next if $skip;
2041                         my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
2042                         next if (($SVN_UUID eq $uuid_p) &&
2043                                                 ($log_msg->{revision} > $r_p));
2044                         next if (defined $url_p && defined $SVN_URL &&
2045                                                 ($SVN_UUID eq $uuid_p) &&
2046                                                 ($url_p eq $SVN_URL));
2047                         push @tmp_parents, $p;
2048                 }
2049         }
2050         foreach (@tmp_parents) {
2051                 next if $seen_parent{$_};
2052                 $seen_parent{$_} = 1;
2053                 push @exec_parents, $_;
2054                 # MAXPARENT is defined to 16 in commit-tree.c:
2055                 last if @exec_parents > 16;
2056         }
2058         set_commit_env($log_msg);
2059         my @exec = ('git-commit-tree', $tree);
2060         push @exec, '-p', $_  foreach @exec_parents;
2061         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2062                                                                 or croak $!;
2063         print $msg_fh $log_msg->{msg} or croak $!;
2064         unless ($_no_metadata) {
2065                 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision}",
2066                                         " $SVN_UUID\n" or croak $!;
2067         }
2068         $msg_fh->flush == 0 or croak $!;
2069         close $msg_fh or croak $!;
2070         chomp(my $commit = do { local $/; <$out_fh> });
2071         close $out_fh or croak $!;
2072         waitpid $pid, 0;
2073         croak $? if $?;
2074         if ($commit !~ /^$sha1$/o) {
2075                 die "Failed to commit, invalid sha1: $commit\n";
2076         }
2077         command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
2078         revdb_set($REVDB, $log_msg->{revision}, $commit);
2080         # this output is read via pipe, do not change:
2081         print "r$log_msg->{revision} = $commit\n";
2082         check_repack();
2083         return $commit;
2086 sub check_repack {
2087         if ($_repack && (--$_repack_nr == 0)) {
2088                 $_repack_nr = $_repack;
2089                 # repack doesn't use any arguments with spaces in them, does it?
2090                 command_noisy('repack', split(/\s+/, $_repack_flags));
2091         }
2094 sub set_commit_env {
2095         my ($log_msg) = @_;
2096         my $author = $log_msg->{author};
2097         if (!defined $author || length $author == 0) {
2098                 $author = '(no author)';
2099         }
2100         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
2101                                 : ($author,"$author\@$SVN_UUID");
2102         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2103         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2104         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2107 sub apply_mod_line_blob {
2108         my $m = shift;
2109         if ($m->{mode_b} =~ /^120/) {
2110                 blob_to_symlink($m->{sha1_b}, $m->{file_b});
2111         } else {
2112                 blob_to_file($m->{sha1_b}, $m->{file_b});
2113         }
2116 sub blob_to_symlink {
2117         my ($blob, $link) = @_;
2118         defined $link or croak "\$link not defined!\n";
2119         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
2120         if (-l $link || -f _) {
2121                 unlink $link or croak $!;
2122         }
2124         my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
2125         symlink $dest, $link or croak $!;
2128 sub blob_to_file {
2129         my ($blob, $file) = @_;
2130         defined $file or croak "\$file not defined!\n";
2131         croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
2132         if (-l $file || -f _) {
2133                 unlink $file or croak $!;
2134         }
2136         open my $blob_fh, '>', $file or croak "$!: $file\n";
2137         my $pid = fork;
2138         defined $pid or croak $!;
2140         if ($pid == 0) {
2141                 open STDOUT, '>&', $blob_fh or croak $!;
2142                 exec('git-cat-file','blob',$blob) or croak $!;
2143         }
2144         waitpid $pid, 0;
2145         croak $? if $?;
2147         close $blob_fh or croak $!;
2150 sub safe_qx {
2151         my $pid = open my $child, '-|';
2152         defined $pid or croak $!;
2153         if ($pid == 0) {
2154                 exec(@_) or croak $!;
2155         }
2156         my @ret = (<$child>);
2157         close $child or croak $?;
2158         die $? if $?; # just in case close didn't error out
2159         return wantarray ? @ret : join('',@ret);
2162 sub svn_compat_check {
2163         if ($_follow_parent) {
2164                 print STDERR 'E: --follow-parent functionality is only ',
2165                                 "available when SVN libraries are used\n";
2166                 exit 1;
2167         }
2168         my @co_help = safe_qx(qw(svn co -h));
2169         unless (grep /ignore-externals/,@co_help) {
2170                 print STDERR "W: Installed svn version does not support ",
2171                                 "--ignore-externals\n";
2172                 $_no_ignore_ext = 1;
2173         }
2174         if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
2175                 $_svn_co_url_revs = 1;
2176         }
2177         if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
2178                 $_svn_pg_peg_revs = 1;
2179         }
2181         # I really, really hope nobody hits this...
2182         unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
2183                 print STDERR <<'';
2184 W: The installed svn version does not support the --stop-on-copy flag in
2185    the log command.
2186    Lets hope the directory you're tracking is not a branch or tag
2187    and was never moved within the repository...
2189                 $_no_stop_copy = 1;
2190         }
2193 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
2194 # (and they won't honor URL@<rev> without -r<rev>, too!)
2195 sub svn_cmd_checkout {
2196         my ($url, $rev, $dir) = @_;
2197         my @cmd = ('svn','co', "-r$rev");
2198         push @cmd, '--ignore-externals' unless $_no_ignore_ext;
2199         $url .= "\@$rev" if $_svn_co_url_revs;
2200         sys(@cmd, $url, $dir);
2203 sub check_upgrade_needed {
2204         if (!-r $REVDB) {
2205                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2206                 open my $fh, '>>',$REVDB or croak $!;
2207                 close $fh;
2208         }
2209         return unless eval {
2210                 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
2211                         {STDERR => 0});
2212         };
2213         my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
2214         if ($@ || !$head) {
2215                 print STDERR "Please run: $0 rebuild --upgrade\n";
2216                 exit 1;
2217         }
2220 # fills %tree_map with a reverse mapping of trees to commits.  Useful
2221 # for finding parents to commit on.
2222 sub map_tree_joins {
2223         my %seen;
2224         foreach my $br (@_branch_from) {
2225                 my $pipe = command_output_pipe(qw/rev-list
2226                                             --topo-order --pretty=raw/, $br);
2227                 while (<$pipe>) {
2228                         if (/^commit ($sha1)$/o) {
2229                                 my $commit = $1;
2231                                 # if we've seen a commit,
2232                                 # we've seen its parents
2233                                 last if $seen{$commit};
2234                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
2235                                 unless (defined $tree) {
2236                                         die "Failed to parse commit $commit\n";
2237                                 }
2238                                 push @{$tree_map{$tree}}, $commit;
2239                                 $seen{$commit} = 1;
2240                         }
2241                 }
2242                 eval { command_close_pipe($pipe) };
2243         }
2246 sub load_all_refs {
2247         if (@_branch_from) {
2248                 print STDERR '--branch|-b parameters are ignored when ',
2249                         "--branch-all-refs|-B is passed\n";
2250         }
2252         # don't worry about rev-list on non-commit objects/tags,
2253         # it shouldn't blow up if a ref is a blob or tree...
2254         @_branch_from = command(qw/rev-parse --symbolic --all/);
2257 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
2258 sub load_authors {
2259         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2260         while (<$authors>) {
2261                 chomp;
2262                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
2263                 my ($user, $name, $email) = ($1, $2, $3);
2264                 $users{$user} = [$name, $email];
2265         }
2266         close $authors or croak $!;
2269 sub rload_authors {
2270         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2271         while (<$authors>) {
2272                 chomp;
2273                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2274                 my ($user, $name, $email) = ($1, $2, $3);
2275                 $rusers{"$name <$email>"} = $user;
2276         }
2277         close $authors or croak $!;
2280 sub svn_propget_base {
2281         my ($p, $f) = @_;
2282         $f .= '@BASE' if $_svn_pg_peg_revs;
2283         return safe_qx(qw/svn propget/, $p, $f);
2286 sub git_svn_each {
2287         my $sub = shift;
2288         foreach (command(qw/rev-parse --symbolic --all/)) {
2289                 next unless s#^refs/remotes/##;
2290                 chomp $_;
2291                 next unless -f "$GIT_DIR/svn/$_/info/url";
2292                 &$sub($_);
2293         }
2296 sub migrate_revdb {
2297         git_svn_each(sub {
2298                 my $id = shift;
2299                 defined(my $pid = fork) or croak $!;
2300                 if (!$pid) {
2301                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2302                         init_vars();
2303                         exit 0 if -r $REVDB;
2304                         print "Upgrading svn => git mapping...\n";
2305                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2306                         open my $fh, '>>',$REVDB or croak $!;
2307                         close $fh;
2308                         rebuild();
2309                         print "Done upgrading. You may now delete the ",
2310                                 "deprecated $GIT_SVN_DIR/revs directory\n";
2311                         exit 0;
2312                 }
2313                 waitpid $pid, 0;
2314                 croak $? if $?;
2315         });
2318 sub migration_check {
2319         migrate_revdb() unless (-e $REVDB);
2320         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2321         print "Upgrading repository...\n";
2322         unless (-d "$GIT_DIR/svn") {
2323                 mkdir "$GIT_DIR/svn" or croak $!;
2324         }
2325         print "Data from a previous version of git-svn exists, but\n\t",
2326                                 "$GIT_SVN_DIR\n\t(required for this version ",
2327                                 "($VERSION) of git-svn) does not.\n";
2329         foreach my $x (command(qw/rev-parse --symbolic --all/)) {
2330                 next unless $x =~ s#^refs/remotes/##;
2331                 chomp $x;
2332                 next unless -f "$GIT_DIR/$x/info/url";
2333                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2334                 next unless $u;
2335                 my $dn = dirname("$GIT_DIR/svn/$x");
2336                 mkpath([$dn]) unless -d $dn;
2337                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2338         }
2339         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2340         print "Done upgrading.\n";
2343 sub find_rev_before {
2344         my ($r, $id, $eq_ok) = @_;
2345         my $f = "$GIT_DIR/svn/$id/.rev_db";
2346         return (undef,undef) unless -r $f;
2347         --$r unless $eq_ok;
2348         while ($r > 0) {
2349                 if (my $c = revdb_get($f, $r)) {
2350                         return ($r, $c);
2351                 }
2352                 --$r;
2353         }
2354         return (undef, undef);
2357 sub init_vars {
2358         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2359         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2360         $REVDB = "$GIT_SVN_DIR/.rev_db";
2361         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2362         $SVN_URL = undef;
2363         $SVN_WC = "$GIT_SVN_DIR/tree";
2364         %tree_map = ();
2367 # convert GetOpt::Long specs for use by git-repo-config
2368 sub read_repo_config {
2369         return unless -d $GIT_DIR;
2370         my $opts = shift;
2371         foreach my $o (keys %$opts) {
2372                 my $v = $opts->{$o};
2373                 my ($key) = ($o =~ /^([a-z\-]+)/);
2374                 $key =~ s/-//g;
2375                 my $arg = 'git-repo-config';
2376                 $arg .= ' --int' if ($o =~ /[:=]i$/);
2377                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2378                 if (ref $v eq 'ARRAY') {
2379                         chomp(my @tmp = `$arg --get-all svn.$key`);
2380                         @$v = @tmp if @tmp;
2381                 } else {
2382                         chomp(my $tmp = `$arg --get svn.$key`);
2383                         if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2384                                 $$v = $tmp;
2385                         }
2386                 }
2387         }
2390 sub set_default_vals {
2391         if (defined $_repack) {
2392                 $_repack = 1000 if ($_repack <= 0);
2393                 $_repack_nr = $_repack;
2394                 $_repack_flags ||= '-d';
2395         }
2398 sub read_grafts {
2399         my $gr_file = shift;
2400         my ($grafts, $comments) = ({}, {});
2401         if (open my $fh, '<', $gr_file) {
2402                 my @tmp;
2403                 while (<$fh>) {
2404                         if (/^($sha1)\s+/) {
2405                                 my $c = $1;
2406                                 if (@tmp) {
2407                                         @{$comments->{$c}} = @tmp;
2408                                         @tmp = ();
2409                                 }
2410                                 foreach my $p (split /\s+/, $_) {
2411                                         $grafts->{$c}->{$p} = 1;
2412                                 }
2413                         } else {
2414                                 push @tmp, $_;
2415                         }
2416                 }
2417                 close $fh or croak $!;
2418                 @{$comments->{'END'}} = @tmp if @tmp;
2419         }
2420         return ($grafts, $comments);
2423 sub write_grafts {
2424         my ($grafts, $comments, $gr_file) = @_;
2426         open my $fh, '>', $gr_file or croak $!;
2427         foreach my $c (sort keys %$grafts) {
2428                 if ($comments->{$c}) {
2429                         print $fh $_ foreach @{$comments->{$c}};
2430                 }
2431                 my $p = $grafts->{$c};
2432                 my %x; # real parents
2433                 delete $p->{$c}; # commits are not self-reproducing...
2434                 my $ch = command_output_pipe(qw/cat-file commit/, $c);
2435                 while (<$ch>) {
2436                         if (/^parent ($sha1)/) {
2437                                 $x{$1} = $p->{$1} = 1;
2438                         } else {
2439                                 last unless /^\S/;
2440                         }
2441                 }
2442                 eval { command_close_pipe($ch) }; # breaking the pipe
2444                 # if real parents are the only ones in the grafts, drop it
2445                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2447                 my (@ip, @jp, $mb);
2448                 my %del = %x;
2449                 @ip = @jp = keys %$p;
2450                 foreach my $i (@ip) {
2451                         next if $del{$i} || $p->{$i} == 2;
2452                         foreach my $j (@jp) {
2453                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
2454                                 $mb = eval { command('merge-base', $i, $j) };
2455                                 next unless $mb;
2456                                 chomp $mb;
2457                                 next if $x{$mb};
2458                                 if ($mb eq $j) {
2459                                         delete $p->{$i};
2460                                         $del{$i} = 1;
2461                                 } elsif ($mb eq $i) {
2462                                         delete $p->{$j};
2463                                         $del{$j} = 1;
2464                                 }
2465                         }
2466                 }
2468                 # if real parents are the only ones in the grafts, drop it
2469                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
2471                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2472         }
2473         if ($comments->{'END'}) {
2474                 print $fh $_ foreach @{$comments->{'END'}};
2475         }
2476         close $fh or croak $!;
2479 sub read_url_paths_all {
2480         my ($l_map, $pfx, $p) = @_;
2481         my @dir;
2482         foreach (<$p/*>) {
2483                 if (-r "$_/info/url") {
2484                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2485                         my $id = $pfx . basename $_;
2486                         my $url = file_to_s("$_/info/url");
2487                         my ($u, $p) = repo_path_split($url);
2488                         $l_map->{$u}->{$p} = $id;
2489                 } elsif (-d $_) {
2490                         push @dir, $_;
2491                 }
2492         }
2493         foreach (@dir) {
2494                 my $x = $_;
2495                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
2496                 read_url_paths_all($l_map, $x, $_);
2497         }
2500 # this one only gets ids that have been imported, not new ones
2501 sub read_url_paths {
2502         my $l_map = {};
2503         git_svn_each(sub { my $x = shift;
2504                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2505                         my ($u, $p) = repo_path_split($url);
2506                         $l_map->{$u}->{$p} = $x;
2507                         });
2508         return $l_map;
2511 sub extract_metadata {
2512         my $id = shift or return (undef, undef, undef);
2513         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2514                                                         \s([a-f\d\-]+)$/x);
2515         if (!defined $rev || !$uuid || !$url) {
2516                 # some of the original repositories I made had
2517                 # identifiers like this:
2518                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2519         }
2520         return ($url, $rev, $uuid);
2523 sub cmt_metadata {
2524         return extract_metadata((grep(/^git-svn-id: /,
2525                 command(qw/cat-file commit/, shift)))[-1]);
2528 sub get_commit_time {
2529         my $cmt = shift;
2530         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
2531         while (<$fh>) {
2532                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
2533                 my ($s, $tz) = ($1, $2);
2534                 if ($tz =~ s/^\+//) {
2535                         $s += tz_to_s_offset($tz);
2536                 } elsif ($tz =~ s/^\-//) {
2537                         $s -= tz_to_s_offset($tz);
2538                 }
2539                 eval { command_close_pipe($fh) };
2540                 return $s;
2541         }
2542         die "Can't get commit time for commit: $cmt\n";
2545 sub tz_to_s_offset {
2546         my ($tz) = @_;
2547         $tz =~ s/(\d\d)$//;
2548         return ($1 * 60) + ($tz * 3600);
2551 # adapted from pager.c
2552 sub config_pager {
2553         $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2554         if (!defined $_pager) {
2555                 $_pager = 'less';
2556         } elsif (length $_pager == 0 || $_pager eq 'cat') {
2557                 $_pager = undef;
2558         }
2561 sub run_pager {
2562         return unless -t *STDOUT;
2563         pipe my $rfd, my $wfd or return;
2564         defined(my $pid = fork) or croak $!;
2565         if (!$pid) {
2566                 open STDOUT, '>&', $wfd or croak $!;
2567                 return;
2568         }
2569         open STDIN, '<&', $rfd or croak $!;
2570         $ENV{LESS} ||= 'FRSX';
2571         exec $_pager or croak "Can't run pager: $! ($_pager)\n";
2574 sub get_author_info {
2575         my ($dest, $author, $t, $tz) = @_;
2576         $author =~ s/(?:^\s*|\s*$)//g;
2577         $dest->{a_raw} = $author;
2578         my $_a;
2579         if ($_authors) {
2580                 $_a = $rusers{$author} || undef;
2581         }
2582         if (!$_a) {
2583                 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2584         }
2585         $dest->{t} = $t;
2586         $dest->{tz} = $tz;
2587         $dest->{a} = $_a;
2588         # Date::Parse isn't in the standard Perl distro :(
2589         if ($tz =~ s/^\+//) {
2590                 $t += tz_to_s_offset($tz);
2591         } elsif ($tz =~ s/^\-//) {
2592                 $t -= tz_to_s_offset($tz);
2593         }
2594         $dest->{t_utc} = $t;
2597 sub process_commit {
2598         my ($c, $r_min, $r_max, $defer) = @_;
2599         if (defined $r_min && defined $r_max) {
2600                 if ($r_min == $c->{r} && $r_min == $r_max) {
2601                         show_commit($c);
2602                         return 0;
2603                 }
2604                 return 1 if $r_min == $r_max;
2605                 if ($r_min < $r_max) {
2606                         # we need to reverse the print order
2607                         return 0 if (defined $_limit && --$_limit < 0);
2608                         push @$defer, $c;
2609                         return 1;
2610                 }
2611                 if ($r_min != $r_max) {
2612                         return 1 if ($r_min < $c->{r});
2613                         return 1 if ($r_max > $c->{r});
2614                 }
2615         }
2616         return 0 if (defined $_limit && --$_limit < 0);
2617         show_commit($c);
2618         return 1;
2621 sub show_commit {
2622         my $c = shift;
2623         if ($_oneline) {
2624                 my $x = "\n";
2625                 if (my $l = $c->{l}) {
2626                         while ($l->[0] =~ /^\s*$/) { shift @$l }
2627                         $x = $l->[0];
2628                 }
2629                 $_l_fmt ||= 'A' . length($c->{r});
2630                 print 'r',pack($_l_fmt, $c->{r}),' | ';
2631                 print "$c->{c} | " if $_show_commit;
2632                 print $x;
2633         } else {
2634                 show_commit_normal($c);
2635         }
2638 sub show_commit_changed_paths {
2639         my ($c) = @_;
2640         return unless $c->{changed};
2641         print "Changed paths:\n", @{$c->{changed}};
2644 sub show_commit_normal {
2645         my ($c) = @_;
2646         print '-' x72, "\nr$c->{r} | ";
2647         print "$c->{c} | " if $_show_commit;
2648         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2649                                  localtime($c->{t_utc})), ' | ';
2650         my $nr_line = 0;
2652         if (my $l = $c->{l}) {
2653                 while ($l->[$#$l] eq "\n" && $#$l > 0
2654                                           && $l->[($#$l - 1)] eq "\n") {
2655                         pop @$l;
2656                 }
2657                 $nr_line = scalar @$l;
2658                 if (!$nr_line) {
2659                         print "1 line\n\n\n";
2660                 } else {
2661                         if ($nr_line == 1) {
2662                                 $nr_line = '1 line';
2663                         } else {
2664                                 $nr_line .= ' lines';
2665                         }
2666                         print $nr_line, "\n";
2667                         show_commit_changed_paths($c);
2668                         print "\n";
2669                         print $_ foreach @$l;
2670                 }
2671         } else {
2672                 print "1 line\n";
2673                 show_commit_changed_paths($c);
2674                 print "\n";
2676         }
2677         foreach my $x (qw/raw diff/) {
2678                 if ($c->{$x}) {
2679                         print "\n";
2680                         print $_ foreach @{$c->{$x}}
2681                 }
2682         }
2685 sub libsvn_load {
2686         return unless $_use_lib;
2687         $_use_lib = eval {
2688                 require SVN::Core;
2689                 if ($SVN::Core::VERSION lt '1.1.0') {
2690                         die "Need SVN::Core 1.1.0 or better ",
2691                                         "(got $SVN::Core::VERSION) ",
2692                                         "Falling back to command-line svn\n";
2693                 }
2694                 require SVN::Ra;
2695                 require SVN::Delta;
2696                 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2697                 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
2698                 *SVN::Git::Fetcher::process_rm = *process_rm;
2699                 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2700                                         $SVN::Node::dir.$SVN::Node::unknown.
2701                                         $SVN::Node::none.$SVN::Node::file.
2702                                         $SVN::Node::dir.$SVN::Node::unknown.
2703                                         $SVN::Auth::SSL::CNMISMATCH.
2704                                         $SVN::Auth::SSL::NOTYETVALID.
2705                                         $SVN::Auth::SSL::EXPIRED.
2706                                         $SVN::Auth::SSL::UNKNOWNCA.
2707                                         $SVN::Auth::SSL::OTHER;
2708                 1;
2709         };
2712 sub _simple_prompt {
2713         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2714         $may_save = undef if $_no_auth_cache;
2715         $default_username = $_username if defined $_username;
2716         if (defined $default_username && length $default_username) {
2717                 if (defined $realm && length $realm) {
2718                         print "Authentication realm: $realm\n";
2719                 }
2720                 $cred->username($default_username);
2721         } else {
2722                 _username_prompt($cred, $realm, $may_save, $pool);
2723         }
2724         $cred->password(_read_password("Password for '" .
2725                                        $cred->username . "': ", $realm));
2726         $cred->may_save($may_save);
2727         $SVN::_Core::SVN_NO_ERROR;
2730 sub _ssl_server_trust_prompt {
2731         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2732         $may_save = undef if $_no_auth_cache;
2733         print "Error validating server certificate for '$realm':\n";
2734         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2735                 print " - The certificate is not issued by a trusted ",
2736                       "authority. Use the\n",
2737                       "   fingerprint to validate the certificate manually!\n";
2738         }
2739         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2740                 print " - The certificate hostname does not match.\n";
2741         }
2742         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2743                 print " - The certificate is not yet valid.\n";
2744         }
2745         if ($failures & $SVN::Auth::SSL::EXPIRED) {
2746                 print " - The certificate has expired.\n";
2747         }
2748         if ($failures & $SVN::Auth::SSL::OTHER) {
2749                 print " - The certificate has an unknown error.\n";
2750         }
2751         printf( "Certificate information:\n".
2752                 " - Hostname: %s\n".
2753                 " - Valid: from %s until %s\n".
2754                 " - Issuer: %s\n".
2755                 " - Fingerprint: %s\n",
2756                 map $cert_info->$_, qw(hostname valid_from valid_until
2757                                        issuer_dname fingerprint) );
2758         my $choice;
2759 prompt:
2760         print $may_save ?
2761               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2762               "(R)eject or accept (t)emporarily? ";
2763         $choice = lc(substr(<STDIN> || 'R', 0, 1));
2764         if ($choice =~ /^t$/i) {
2765                 $cred->may_save(undef);
2766         } elsif ($choice =~ /^r$/i) {
2767                 return -1;
2768         } elsif ($may_save && $choice =~ /^p$/i) {
2769                 $cred->may_save($may_save);
2770         } else {
2771                 goto prompt;
2772         }
2773         $cred->accepted_failures($failures);
2774         $SVN::_Core::SVN_NO_ERROR;
2777 sub _ssl_client_cert_prompt {
2778         my ($cred, $realm, $may_save, $pool) = @_;
2779         $may_save = undef if $_no_auth_cache;
2780         print "Client certificate filename: ";
2781         chomp(my $filename = <STDIN>);
2782         $cred->cert_file($filename);
2783         $cred->may_save($may_save);
2784         $SVN::_Core::SVN_NO_ERROR;
2787 sub _ssl_client_cert_pw_prompt {
2788         my ($cred, $realm, $may_save, $pool) = @_;
2789         $may_save = undef if $_no_auth_cache;
2790         $cred->password(_read_password("Password: ", $realm));
2791         $cred->may_save($may_save);
2792         $SVN::_Core::SVN_NO_ERROR;
2795 sub _username_prompt {
2796         my ($cred, $realm, $may_save, $pool) = @_;
2797         $may_save = undef if $_no_auth_cache;
2798         if (defined $realm && length $realm) {
2799                 print "Authentication realm: $realm\n";
2800         }
2801         my $username;
2802         if (defined $_username) {
2803                 $username = $_username;
2804         } else {
2805                 print "Username: ";
2806                 chomp($username = <STDIN>);
2807         }
2808         $cred->username($username);
2809         $cred->may_save($may_save);
2810         $SVN::_Core::SVN_NO_ERROR;
2813 sub _read_password {
2814         my ($prompt, $realm) = @_;
2815         print $prompt;
2816         require Term::ReadKey;
2817         Term::ReadKey::ReadMode('noecho');
2818         my $password = '';
2819         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2820                 last if $key =~ /[\012\015]/; # \n\r
2821                 $password .= $key;
2822         }
2823         Term::ReadKey::ReadMode('restore');
2824         print "\n";
2825         $password;
2828 sub libsvn_connect {
2829         my ($url) = @_;
2830         SVN::_Core::svn_config_ensure($_config_dir, undef);
2831         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2832             SVN::Client::get_simple_provider(),
2833             SVN::Client::get_ssl_server_trust_file_provider(),
2834             SVN::Client::get_simple_prompt_provider(
2835               \&_simple_prompt, 2),
2836             SVN::Client::get_ssl_client_cert_prompt_provider(
2837               \&_ssl_client_cert_prompt, 2),
2838             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2839               \&_ssl_client_cert_pw_prompt, 2),
2840             SVN::Client::get_username_provider(),
2841             SVN::Client::get_ssl_server_trust_prompt_provider(
2842               \&_ssl_server_trust_prompt),
2843             SVN::Client::get_username_prompt_provider(
2844               \&_username_prompt, 2),
2845           ]);
2846         my $config = SVN::Core::config_get_config($_config_dir);
2847         my $ra = SVN::Ra->new(url => $url, auth => $baton,
2848                               config => $config,
2849                               pool => SVN::Pool->new,
2850                               auth_provider_callbacks => $callbacks);
2852         my $df = $ENV{GIT_SVN_DELTA_FETCH};
2853         if (defined $df) {
2854                 $_xfer_delta = $df;
2855         } else {
2856                 $_xfer_delta = ($url =~ m#^file://#) ? undef : 1;
2857         }
2858         $ra->{svn_path} = $url;
2859         $ra->{repos_root} = $ra->get_repos_root;
2860         $ra->{svn_path} =~ s#^\Q$ra->{repos_root}\E/*##;
2861         push @repo_path_split_cache, qr/^(\Q$ra->{repos_root}\E)/;
2862         return $ra;
2865 sub libsvn_can_do_switch {
2866         unless (defined $_svn_can_do_switch) {
2867                 my $pool = SVN::Pool->new;
2868                 my $rep = eval {
2869                         $SVN->do_switch(1, '', 0, $SVN->{url},
2870                                         SVN::Delta::Editor->new, $pool);
2871                 };
2872                 if ($@) {
2873                         $_svn_can_do_switch = 0;
2874                 } else {
2875                         $rep->abort_report($pool);
2876                         $_svn_can_do_switch = 1;
2877                 }
2878                 $pool->clear;
2879         }
2880         $_svn_can_do_switch;
2883 sub libsvn_dup_ra {
2884         my ($ra) = @_;
2885         SVN::Ra->new(map { $_ => $ra->{$_} } qw/config url
2886                      auth auth_provider_callbacks repos_root svn_path/);
2889 sub libsvn_get_file {
2890         my ($gui, $f, $rev, $chg, $untracked) = @_;
2891         $f =~ s#^/##;
2892         print "\t$chg\t$f\n" unless $_q;
2894         my ($hash, $pid, $in, $out);
2895         my $pool = SVN::Pool->new;
2896         defined($pid = open3($in, $out, '>&STDERR',
2897                                 qw/git-hash-object -w --stdin/)) or croak $!;
2898         # redirect STDOUT for SVN 1.1.x compatibility
2899         open my $stdout, '>&', \*STDOUT or croak $!;
2900         open STDOUT, '>&', $in or croak $!;
2901         my ($r, $props) = $SVN->get_file($f, $rev, \*STDOUT, $pool);
2902         $in->flush == 0 or croak $!;
2903         open STDOUT, '>&', $stdout or croak $!;
2904         close $in or croak $!;
2905         close $stdout or croak $!;
2906         $pool->clear;
2907         chomp($hash = do { local $/; <$out> });
2908         close $out or croak $!;
2909         waitpid $pid, 0;
2910         $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2912         my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2913         if (exists $props->{'svn:special'}) {
2914                 $mode = '120000';
2915                 my $link = `git-cat-file blob $hash`; # no chomping symlinks
2916                 $link =~ s/^link // or die "svn:special file with contents: <",
2917                                                 $link, "> is not understood\n";
2918                 defined($pid = open3($in, $out, '>&STDERR',
2919                                 qw/git-hash-object -w --stdin/)) or croak $!;
2920                 print $in $link;
2921                 $in->flush == 0 or croak $!;
2922                 close $in or croak $!;
2923                 chomp($hash = do { local $/; <$out> });
2924                 close $out or croak $!;
2925                 waitpid $pid, 0;
2926                 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2927         }
2928         %{$untracked->{file_prop}->{$f}} = %$props;
2929         print $gui $mode,' ',$hash,"\t",$f,"\0" or croak $!;
2932 sub uri_encode {
2933         my ($f) = @_;
2934         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2935         $f
2938 sub uri_decode {
2939         my ($f) = @_;
2940         $f =~ tr/+/ /;
2941         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2942         $f
2945 sub libsvn_log_entry {
2946         my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2947         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2948                                          (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2949                                 or die "Unable to parse date: $date\n";
2950         if (defined $author && length $author > 0 &&
2951             defined $_authors && ! defined $users{$author}) {
2952                 die "Author: $author not defined in $_authors file\n";
2953         }
2954         $msg = '' if ($rev == 0 && !defined $msg);
2956         open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2957         my $h;
2958         print $un "r$rev\n" or croak $!;
2959         $h = $untracked->{empty};
2960         foreach (sort keys %$h) {
2961                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2962                 print $un "  $act: ", uri_encode($_), "\n" or croak $!;
2963                 warn "W: $act: $_\n";
2964         }
2965         foreach my $t (qw/dir_prop file_prop/) {
2966                 $h = $untracked->{$t} or next;
2967                 foreach my $path (sort keys %$h) {
2968                         my $ppath = $path eq '' ? '.' : $path;
2969                         foreach my $prop (sort keys %{$h->{$path}}) {
2970                                 next if $SKIP{$prop};
2971                                 my $v = $h->{$path}->{$prop};
2972                                 if (defined $v) {
2973                                         print $un "  +$t: ",
2974                                                   uri_encode($ppath), ' ',
2975                                                   uri_encode($prop), ' ',
2976                                                   uri_encode($v), "\n"
2977                                                   or croak $!;
2978                                 } else {
2979                                         print $un "  -$t: ",
2980                                                   uri_encode($ppath), ' ',
2981                                                   uri_encode($prop), "\n"
2982                                                   or croak $!;
2983                                 }
2984                         }
2985                 }
2986         }
2987         foreach my $t (qw/absent_file absent_directory/) {
2988                 $h = $untracked->{$t} or next;
2989                 foreach my $parent (sort keys %$h) {
2990                         foreach my $path (sort @{$h->{$parent}}) {
2991                                 print $un "  $t: ",
2992                                       uri_encode("$parent/$path"), "\n"
2993                                       or croak $!;
2994                                 warn "W: $t: $parent/$path ",
2995                                      "Insufficient permissions?\n";
2996                         }
2997                 }
2998         }
3000         # revprops (make this optional? it's an extra network trip...)
3001         my $pool = SVN::Pool->new;
3002         my $rp = $SVN->rev_proplist($rev, $pool);
3003         foreach (sort keys %$rp) {
3004                 next if /^svn:(?:author|date|log)$/;
3005                 print $un "  rev_prop: ", uri_encode($_), ' ',
3006                           uri_encode($rp->{$_}), "\n";
3007         }
3008         $pool->clear;
3009         close $un or croak $!;
3011         { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
3012           author => $author, msg => $msg."\n", parents => $parents || [],
3013           revprops => $rp }
3016 sub process_rm {
3017         my ($gui, $last_commit, $f, $q) = @_;
3018         # remove entire directories.
3019         if (command('ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
3020                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3021                                                      -r --name-only -z/,
3022                                                      $last_commit,'--',$f);
3023                 local $/ = "\0";
3024                 while (<$ls>) {
3025                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
3026                         print "\tD\t$_\n" unless $q;
3027                 }
3028                 print "\tD\t$f/\n" unless $q;
3029                 command_close_pipe($ls, $ctx);
3030                 return $SVN::Node::dir;
3031         } else {
3032                 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
3033                 print "\tD\t$f\n" unless $q;
3034                 return $SVN::Node::file;
3035         }
3038 sub libsvn_fetch {
3039         $_xfer_delta ? libsvn_fetch_delta(@_) : libsvn_fetch_full(@_);
3042 sub libsvn_fetch_delta {
3043         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
3044         my $pool = SVN::Pool->new;
3045         my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
3046         my $reporter = $SVN->do_update($rev, '', 1, $ed, $pool);
3047         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3048         my (undef, $last_rev, undef) = cmt_metadata($last_commit);
3049         $reporter->set_path('', $last_rev, 0, @lock, $pool);
3050         $reporter->finish_report($pool);
3051         $pool->clear;
3052         unless ($ed->{git_commit_ok}) {
3053                 die "SVN connection failed somewhere...\n";
3054         }
3055         libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
3058 sub libsvn_fetch_full {
3059         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
3060         my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3061         my %amr;
3062         my $ut = { empty => {}, dir_prop => {}, file_prop => {} };
3063         my $p = $SVN->{svn_path};
3064         foreach my $f (keys %$paths) {
3065                 my $m = $paths->{$f}->action();
3066                 if (length $p) {
3067                         $f =~ s#^/\Q$p\E/##;
3068                         next if $f =~ m#^/#;
3069                 } else {
3070                         $f =~ s#^/##;
3071                 }
3072                 if ($m =~ /^[DR]$/) {
3073                         my $t = process_rm($gui, $last_commit, $f, $_q);
3074                         if ($m eq 'D') {
3075                                 $ut->{empty}->{$f} = 0 if $t == $SVN::Node::dir;
3076                                 next;
3077                         }
3078                         # 'R' can be file replacements, too, right?
3079                 }
3080                 my $pool = SVN::Pool->new;
3081                 my $t = $SVN->check_path($f, $rev, $pool);
3082                 if ($t == $SVN::Node::file) {
3083                         if ($m =~ /^[AMR]$/) {
3084                                 $amr{$f} = $m;
3085                         } else {
3086                                 die "Unrecognized action: $m, ($f r$rev)\n";
3087                         }
3088                 } elsif ($t == $SVN::Node::dir && $m =~ /^[AR]$/) {
3089                         my @traversed = ();
3090                         libsvn_traverse($gui, '', $f, $rev, \@traversed, $ut);
3091                         if (@traversed) {
3092                                 foreach (@traversed) {
3093                                         $amr{$_} = $m;
3094                                 }
3095                         } else {
3096                                 my ($dir, $file) = ($f =~ m#^(.*?)/?([^/]+)$#);
3097                                 delete $ut->{empty}->{$dir};
3098                                 $ut->{empty}->{$f} = 1;
3099                         }
3100                 }
3101                 $pool->clear;
3102         }
3103         foreach (keys %amr) {
3104                 libsvn_get_file($gui, $_, $rev, $amr{$_}, $ut);
3105                 my ($d) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
3106                 delete $ut->{empty}->{$d};
3107         }
3108         unless (exists $ut->{dir_prop}->{''}) {
3109                 my $pool = SVN::Pool->new;
3110                 my (undef, undef, $props) = $SVN->get_dir('', $rev, $pool);
3111                 %{$ut->{dir_prop}->{''}} = %$props;
3112                 $pool->clear;
3113         }
3114         command_close_pipe($gui, $ctx);
3115         libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ut);
3118 sub svn_grab_base_rev {
3119         my $c = eval { command_oneline([qw/rev-parse --verify/,
3120                                         "refs/remotes/$GIT_SVN^0"],
3121                                         { STDERR => 0 }) };
3122         if (defined $c && length $c) {
3123                 my ($url, $rev, $uuid) = cmt_metadata($c);
3124                 return ($rev, $c) if defined $rev;
3125         }
3126         if ($_no_metadata) {
3127                 my $offset = -41; # from tail
3128                 my $rl;
3129                 open my $fh, '<', $REVDB or
3130                         die "--no-metadata specified and $REVDB not readable\n";
3131                 seek $fh, $offset, 2;
3132                 $rl = readline $fh;
3133                 defined $rl or return (undef, undef);
3134                 chomp $rl;
3135                 while ($c ne $rl && tell $fh != 0) {
3136                         $offset -= 41;
3137                         seek $fh, $offset, 2;
3138                         $rl = readline $fh;
3139                         defined $rl or return (undef, undef);
3140                         chomp $rl;
3141                 }
3142                 my $rev = tell $fh;
3143                 croak $! if ($rev < -1);
3144                 $rev =  ($rev - 41) / 41;
3145                 close $fh or croak $!;
3146                 return ($rev, $c);
3147         }
3148         return (undef, undef);
3151 sub libsvn_parse_revision {
3152         my $base = shift;
3153         my $head = $SVN->get_latest_revnum();
3154         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
3155                 return ($base + 1, $head) if (defined $base);
3156                 return (0, $head);
3157         }
3158         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
3159         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
3160         if ($_revision =~ /^BASE:(\d+)$/) {
3161                 return ($base + 1, $1) if (defined $base);
3162                 return (0, $head);
3163         }
3164         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
3165         die "revision argument: $_revision not understood by git-svn\n",
3166                 "Try using the command-line svn client instead\n";
3169 sub libsvn_traverse {
3170         my ($gui, $pfx, $path, $rev, $files, $untracked) = @_;
3171         my $cwd = length $pfx ? "$pfx/$path" : $path;
3172         my $pool = SVN::Pool->new;
3173         $cwd =~ s#^\Q$SVN->{svn_path}\E##;
3174         my $nr = 0;
3175         my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
3176         %{$untracked->{dir_prop}->{$cwd}} = %$props;
3177         foreach my $d (keys %$dirent) {
3178                 my $t = $dirent->{$d}->kind;
3179                 if ($t == $SVN::Node::dir) {
3180                         my $i = libsvn_traverse($gui, $cwd, $d, $rev,
3181                                                 $files, $untracked);
3182                         if ($i) {
3183                                 $nr += $i;
3184                         } else {
3185                                 $untracked->{empty}->{"$cwd/$d"} = 1;
3186                         }
3187                 } elsif ($t == $SVN::Node::file) {
3188                         $nr++;
3189                         my $file = "$cwd/$d";
3190                         if (defined $files) {
3191                                 push @$files, $file;
3192                         } else {
3193                                 libsvn_get_file($gui, $file, $rev, 'A',
3194                                                 $untracked);
3195                                 my ($dir) = ($file =~ m#^(.*?)/?(?:[^/]+)$#);
3196                                 delete $untracked->{empty}->{$dir};
3197                         }
3198                 }
3199         }
3200         $pool->clear;
3201         $nr;
3204 sub libsvn_traverse_ignore {
3205         my ($fh, $path, $r) = @_;
3206         $path =~ s#^/+##g;
3207         my $pool = SVN::Pool->new;
3208         my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
3209         my $p = $path;
3210         $p =~ s#^\Q$SVN->{svn_path}\E/##;
3211         print $fh length $p ? "\n# $p\n" : "\n# /\n";
3212         if (my $s = $props->{'svn:ignore'}) {
3213                 $s =~ s/[\r\n]+/\n/g;
3214                 chomp $s;
3215                 if (length $p == 0) {
3216                         $s =~ s#\n#\n/$p#g;
3217                         print $fh "/$s\n";
3218                 } else {
3219                         $s =~ s#\n#\n/$p/#g;
3220                         print $fh "/$p/$s\n";
3221                 }
3222         }
3223         foreach (sort keys %$dirent) {
3224                 next if $dirent->{$_}->kind != $SVN::Node::dir;
3225                 libsvn_traverse_ignore($fh, "$path/$_", $r);
3226         }
3227         $pool->clear;
3230 sub revisions_eq {
3231         my ($path, $r0, $r1) = @_;
3232         return 1 if $r0 == $r1;
3233         my $nr = 0;
3234         if ($_use_lib) {
3235                 # should be OK to use Pool here (r1 - r0) should be small
3236                 my $pool = SVN::Pool->new;
3237                 libsvn_get_log($SVN, [$path], $r0, $r1,
3238                                 0, 0, 1, sub {$nr++}, $pool);
3239                 $pool->clear;
3240         } else {
3241                 my ($url, undef) = repo_path_split($SVN_URL);
3242                 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
3243                 while (next_log_entry($svn_log)) { $nr++ }
3244                 close $svn_log->{fh};
3245         }
3246         return 0 if ($nr > 1);
3247         return 1;
3250 sub libsvn_find_parent_branch {
3251         my ($paths, $rev, $author, $date, $msg) = @_;
3252         my $svn_path = '/'.$SVN->{svn_path};
3254         # look for a parent from another branch:
3255         my $i = $paths->{$svn_path} or return;
3256         my $branch_from = $i->copyfrom_path or return;
3257         my $r = $i->copyfrom_rev;
3258         print STDERR  "Found possible branch point: ",
3259                                 "$branch_from => $svn_path, $r\n";
3260         $branch_from =~ s#^/##;
3261         my $l_map = {};
3262         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
3263         my $url = $SVN->{repos_root};
3264         defined $l_map->{$url} or return;
3265         my $id = $l_map->{$url}->{$branch_from};
3266         if (!defined $id && $_follow_parent) {
3267                 print STDERR "Following parent: $branch_from\@$r\n";
3268                 # auto create a new branch and follow it
3269                 $id = basename($branch_from);
3270                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
3271                 while (-r "$GIT_DIR/svn/$id") {
3272                         # just grow a tail if we're not unique enough :x
3273                         $id .= '-';
3274                 }
3275         }
3276         return unless defined $id;
3278         my ($r0, $parent) = find_rev_before($r,$id,1);
3279         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
3280                 defined(my $pid = fork) or croak $!;
3281                 if (!$pid) {
3282                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
3283                         init_vars();
3284                         $SVN_URL = "$url/$branch_from";
3285                         $SVN = undef;
3286                         setup_git_svn();
3287                         # we can't assume SVN_URL exists at r+1:
3288                         $_revision = "0:$r";
3289                         fetch_lib();
3290                         exit 0;
3291                 }
3292                 waitpid $pid, 0;
3293                 croak $? if $?;
3294                 ($r0, $parent) = find_rev_before($r,$id,1);
3295         }
3296         return unless (defined $r0 && defined $parent);
3297         if (revisions_eq($branch_from, $r0, $r)) {
3298                 unlink $GIT_SVN_INDEX;
3299                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
3300                 command_noisy('read-tree', $parent);
3301                 unless (libsvn_can_do_switch()) {
3302                         return libsvn_fetch_full($parent, $paths, $rev,
3303                                                 $author, $date, $msg);
3304                 }
3305                 # do_switch works with svn/trunk >= r22312, but that is not
3306                 # included with SVN 1.4.2 (the latest version at the moment),
3307                 # so we can't rely on it.
3308                 my $ra = libsvn_connect("$url/$branch_from");
3309                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
3310                 my $pool = SVN::Pool->new;
3311                 my $reporter = $ra->do_switch($rev, '', 1, $SVN->{url},
3312                                               $ed, $pool);
3313                 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3314                 $reporter->set_path('', $r0, 0, @lock, $pool);
3315                 $reporter->finish_report($pool);
3316                 $pool->clear;
3317                 unless ($ed->{git_commit_ok}) {
3318                         die "SVN connection failed somewhere...\n";
3319                 }
3320                 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
3321         }
3322         print STDERR "Nope, branch point not imported or unknown\n";
3323         return undef;
3326 sub libsvn_get_log {
3327         my ($ra, @args) = @_;
3328         $args[4]-- if $args[4] && $_xfer_delta && ! $_follow_parent;
3329         if ($SVN::Core::VERSION le '1.2.0') {
3330                 splice(@args, 3, 1);
3331         }
3332         $ra->get_log(@args);
3335 sub libsvn_new_tree {
3336         if (my $log_entry = libsvn_find_parent_branch(@_)) {
3337                 return $log_entry;
3338         }
3339         my ($paths, $rev, $author, $date, $msg) = @_;
3340         my $ut;
3341         if ($_xfer_delta) {
3342                 my $pool = SVN::Pool->new;
3343                 my $ed = SVN::Git::Fetcher->new({q => $_q});
3344                 my $reporter = $SVN->do_update($rev, '', 1, $ed, $pool);
3345                 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3346                 $reporter->set_path('', $rev, 1, @lock, $pool);
3347                 $reporter->finish_report($pool);
3348                 $pool->clear;
3349                 unless ($ed->{git_commit_ok}) {
3350                         die "SVN connection failed somewhere...\n";
3351                 }
3352                 $ut = $ed;
3353         } else {
3354                 $ut = { empty => {}, dir_prop => {}, file_prop => {} };
3355                 my ($gui, $ctx) = command_input_pipe(qw/update-index
3356                                                      -z --index-info/);
3357                 libsvn_traverse($gui, '', $SVN->{svn_path}, $rev, undef, $ut);
3358                 command_close_pipe($gui, $ctx);
3359         }
3360         libsvn_log_entry($rev, $author, $date, $msg, [], $ut);
3363 sub find_graft_path_commit {
3364         my ($tree_paths, $p1, $r1) = @_;
3365         foreach my $x (keys %$tree_paths) {
3366                 next unless ($p1 =~ /^\Q$x\E/);
3367                 my $i = $tree_paths->{$x};
3368                 my ($r0, $parent) = find_rev_before($r1,$i,1);
3369                 return $parent if (defined $r0 && $r0 == $r1);
3370                 print STDERR "r$r1 of $i not imported\n";
3371                 next;
3372         }
3373         return undef;
3376 sub find_graft_path_parents {
3377         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
3378         foreach my $x (keys %$tree_paths) {
3379                 next unless ($p0 =~ /^\Q$x\E/);
3380                 my $i = $tree_paths->{$x};
3381                 my ($r, $parent) = find_rev_before($r0, $i, 1);
3382                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
3383                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
3384                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
3385                         next if ($url_a && $url_b && $url_a eq $url_b &&
3386                                                         $uuid_b eq $uuid_a);
3387                         $grafts->{$c}->{$parent} = 1;
3388                 }
3389         }
3392 sub libsvn_graft_file_copies {
3393         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
3394         foreach (keys %$paths) {
3395                 my $i = $paths->{$_};
3396                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
3397                                         $i->copyfrom_rev);
3398                 next unless (defined $p0 && defined $r0);
3400                 my $p1 = $_;
3401                 $p1 =~ s#^/##;
3402                 $p0 =~ s#^/##;
3403                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
3404                 next unless $c;
3405                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
3406         }
3409 sub set_index {
3410         my $old = $ENV{GIT_INDEX_FILE};
3411         $ENV{GIT_INDEX_FILE} = shift;
3412         return $old;
3415 sub restore_index {
3416         my ($old) = @_;
3417         if (defined $old) {
3418                 $ENV{GIT_INDEX_FILE} = $old;
3419         } else {
3420                 delete $ENV{GIT_INDEX_FILE};
3421         }
3424 sub libsvn_commit_cb {
3425         my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
3426         if ($_optimize_commits && $rev == ($r_last + 1)) {
3427                 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
3428                 $log->{tree} = get_tree_from_treeish($c);
3429                 my $cmt = git_commit($log, $cmt_last, $c);
3430                 my @diff = command('diff-tree', $cmt, $c);
3431                 if (@diff) {
3432                         print STDERR "Trees differ: $cmt $c\n",
3433                                         join('',@diff),"\n";
3434                         exit 1;
3435                 }
3436         } else {
3437                 fetch("$rev=$c");
3438         }
3441 sub libsvn_ls_fullurl {
3442         my $fullurl = shift;
3443         my $ra = libsvn_connect($fullurl);
3444         my @ret;
3445         my $pool = SVN::Pool->new;
3446         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
3447         my ($dirent, undef, undef) = $ra->get_dir('', $r, $pool);
3448         foreach my $d (keys %$dirent) {
3449                 if ($dirent->{$d}->kind == $SVN::Node::dir) {
3450                         push @ret, "$d/"; # add '/' for compat with cli svn
3451                 }
3452         }
3453         $pool->clear;
3454         return @ret;
3458 sub libsvn_skip_unknown_revs {
3459         my $err = shift;
3460         my $errno = $err->apr_err();
3461         # Maybe the branch we're tracking didn't
3462         # exist when the repo started, so it's
3463         # not an error if it doesn't, just continue
3464         #
3465         # Wonderfully consistent library, eh?
3466         # 160013 - svn:// and file://
3467         # 175002 - http(s)://
3468         # 175007 - http(s):// (this repo required authorization, too...)
3469         #   More codes may be discovered later...
3470         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3471                 return;
3472         }
3473         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3474 };
3476 # Tie::File seems to be prone to offset errors if revisions get sparse,
3477 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
3478 # one of my favorite modules is out :<  Next up would be one of the DBM
3479 # modules, but I'm not sure which is most portable...  So I'll just
3480 # go with something that's plain-text, but still capable of
3481 # being randomly accessed.  So here's my ultra-simple fixed-width
3482 # database.  All records are 40 characters + "\n", so it's easy to seek
3483 # to a revision: (41 * rev) is the byte offset.
3484 # A record of 40 0s denotes an empty revision.
3485 # And yes, it's still pretty fast (faster than Tie::File).
3486 sub revdb_set {
3487         my ($file, $rev, $commit) = @_;
3488         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
3489         open my $fh, '+<', $file or croak $!;
3490         my $offset = $rev * 41;
3491         # assume that append is the common case:
3492         seek $fh, 0, 2 or croak $!;
3493         my $pos = tell $fh;
3494         if ($pos < $offset) {
3495                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
3496         }
3497         seek $fh, $offset, 0 or croak $!;
3498         print $fh $commit,"\n";
3499         close $fh or croak $!;
3502 sub revdb_get {
3503         my ($file, $rev) = @_;
3504         my $ret;
3505         my $offset = $rev * 41;
3506         open my $fh, '<', $file or croak $!;
3507         seek $fh, $offset, 0;
3508         if (tell $fh == $offset) {
3509                 $ret = readline $fh;
3510                 if (defined $ret) {
3511                         chomp $ret;
3512                         $ret = undef if ($ret =~ /^0{40}$/);
3513                 }
3514         }
3515         close $fh or croak $!;
3516         return $ret;
3519 sub copy_remote_ref {
3520         my $origin = $_cp_remote ? $_cp_remote : 'origin';
3521         my $ref = "refs/remotes/$GIT_SVN";
3522         if (command('ls-remote', $origin, $ref)) {
3523                 command_noisy('fetch', $origin, "$ref:$ref");
3524         } elsif ($_cp_remote && !$_upgrade) {
3525                 die "Unable to find remote reference: ",
3526                                 "refs/remotes/$GIT_SVN on $origin\n";
3527         }
3529 package SVN::Git::Fetcher;
3530 use vars qw/@ISA/;
3531 use strict;
3532 use warnings;
3533 use Carp qw/croak/;
3534 use IO::File qw//;
3535 use Git qw/command command_oneline command_noisy
3536            command_output_pipe command_input_pipe command_close_pipe/;
3538 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3539 sub new {
3540         my ($class, $git_svn) = @_;
3541         my $self = SVN::Delta::Editor->new;
3542         bless $self, $class;
3543         $self->{c} = $git_svn->{c} if exists $git_svn->{c};
3544         $self->{q} = $git_svn->{q};
3545         $self->{empty} = {};
3546         $self->{dir_prop} = {};
3547         $self->{file_prop} = {};
3548         $self->{absent_dir} = {};
3549         $self->{absent_file} = {};
3550         ($self->{gui}, $self->{ctx}) = command_input_pipe(
3551                                              qw/update-index -z --index-info/);
3552         require Digest::MD5;
3553         $self;
3556 sub open_root {
3557         { path => '' };
3560 sub open_directory {
3561         my ($self, $path, $pb, $rev) = @_;
3562         { path => $path };
3565 sub delete_entry {
3566         my ($self, $path, $rev, $pb) = @_;
3567         my $t = process_rm($self->{gui}, $self->{c}, $path, $self->{q});
3568         $self->{empty}->{$path} = 0 if $t == $SVN::Node::dir;
3569         undef;
3572 sub open_file {
3573         my ($self, $path, $pb, $rev) = @_;
3574         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
3575                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3576         unless (defined $mode && defined $blob) {
3577                 die "$path was not found in commit $self->{c} (r$rev)\n";
3578         }
3579         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3580           pool => SVN::Pool->new, action => 'M' };
3583 sub add_file {
3584         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3585         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3586         delete $self->{empty}->{$dir};
3587         { path => $path, mode_a => 100644, mode_b => 100644,
3588           pool => SVN::Pool->new, action => 'A' };
3591 sub add_directory {
3592         my ($self, $path, $cp_path, $cp_rev) = @_;
3593         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3594         delete $self->{empty}->{$dir};
3595         $self->{empty}->{$path} = 1;
3596         { path => $path };
3599 sub change_dir_prop {
3600         my ($self, $db, $prop, $value) = @_;
3601         $self->{dir_prop}->{$db->{path}} ||= {};
3602         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3603         undef;
3606 sub absent_directory {
3607         my ($self, $path, $pb) = @_;
3608         $self->{absent_dir}->{$pb->{path}} ||= [];
3609         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3610         undef;
3613 sub absent_file {
3614         my ($self, $path, $pb) = @_;
3615         $self->{absent_file}->{$pb->{path}} ||= [];
3616         push @{$self->{absent_file}->{$pb->{path}}}, $path;
3617         undef;
3620 sub change_file_prop {
3621         my ($self, $fb, $prop, $value) = @_;
3622         if ($prop eq 'svn:executable') {
3623                 if ($fb->{mode_b} != 120000) {
3624                         $fb->{mode_b} = defined $value ? 100755 : 100644;
3625                 }
3626         } elsif ($prop eq 'svn:special') {
3627                 $fb->{mode_b} = defined $value ? 120000 : 100644;
3628         } else {
3629                 $self->{file_prop}->{$fb->{path}} ||= {};
3630                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3631         }
3632         undef;
3635 sub apply_textdelta {
3636         my ($self, $fb, $exp) = @_;
3637         my $fh = IO::File->new_tmpfile;
3638         $fh->autoflush(1);
3639         # $fh gets auto-closed() by SVN::TxDelta::apply(),
3640         # (but $base does not,) so dup() it for reading in close_file
3641         open my $dup, '<&', $fh or croak $!;
3642         my $base = IO::File->new_tmpfile;
3643         $base->autoflush(1);
3644         if ($fb->{blob}) {
3645                 defined (my $pid = fork) or croak $!;
3646                 if (!$pid) {
3647                         open STDOUT, '>&', $base or croak $!;
3648                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
3649                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
3650                 }
3651                 waitpid $pid, 0;
3652                 croak $? if $?;
3654                 if (defined $exp) {
3655                         seek $base, 0, 0 or croak $!;
3656                         my $md5 = Digest::MD5->new;
3657                         $md5->addfile($base);
3658                         my $got = $md5->hexdigest;
3659                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3660                             "expected: $exp\n",
3661                             "     got: $got\n" if ($got ne $exp);
3662                 }
3663         }
3664         seek $base, 0, 0 or croak $!;
3665         $fb->{fh} = $dup;
3666         $fb->{base} = $base;
3667         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3670 sub close_file {
3671         my ($self, $fb, $exp) = @_;
3672         my $hash;
3673         my $path = $fb->{path};
3674         if (my $fh = $fb->{fh}) {
3675                 seek($fh, 0, 0) or croak $!;
3676                 my $md5 = Digest::MD5->new;
3677                 $md5->addfile($fh);
3678                 my $got = $md5->hexdigest;
3679                 die "Checksum mismatch: $path\n",
3680                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
3681                 seek($fh, 0, 0) or croak $!;
3682                 if ($fb->{mode_b} == 120000) {
3683                         read($fh, my $buf, 5) == 5 or croak $!;
3684                         $buf eq 'link ' or die "$path has mode 120000",
3685                                                "but is not a link\n";
3686                 }
3687                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3688                 if (!$pid) {
3689                         open STDIN, '<&', $fh or croak $!;
3690                         exec qw/git-hash-object -w --stdin/ or croak $!;
3691                 }
3692                 chomp($hash = do { local $/; <$out> });
3693                 close $out or croak $!;
3694                 close $fh or croak $!;
3695                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3696                 close $fb->{base} or croak $!;
3697         } else {
3698                 $hash = $fb->{blob} or die "no blob information\n";
3699         }
3700         $fb->{pool}->clear;
3701         my $gui = $self->{gui};
3702         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
3703         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
3704         undef;
3707 sub abort_edit {
3708         my $self = shift;
3709         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
3710         $self->SUPER::abort_edit(@_);
3713 sub close_edit {
3714         my $self = shift;
3715         command_close_pipe($self->{gui}, $self->{ctx});
3716         $self->{git_commit_ok} = 1;
3717         $self->SUPER::close_edit(@_);
3720 package SVN::Git::Editor;
3721 use vars qw/@ISA/;
3722 use strict;
3723 use warnings;
3724 use Carp qw/croak/;
3725 use IO::File;
3726 use Git qw/command command_oneline command_noisy
3727            command_output_pipe command_input_pipe command_close_pipe/;
3729 sub new {
3730         my $class = shift;
3731         my $git_svn = shift;
3732         my $self = SVN::Delta::Editor->new(@_);
3733         bless $self, $class;
3734         foreach (qw/svn_path c r ra /) {
3735                 die "$_ required!\n" unless (defined $git_svn->{$_});
3736                 $self->{$_} = $git_svn->{$_};
3737         }
3738         $self->{pool} = SVN::Pool->new;
3739         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3740         $self->{rm} = { };
3741         require Digest::MD5;
3742         return $self;
3745 sub split_path {
3746         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3749 sub repo_path {
3750         (defined $_[1] && length $_[1]) ? $_[1] : ''
3753 sub url_path {
3754         my ($self, $path) = @_;
3755         $self->{ra}->{url} . '/' . $self->repo_path($path);
3758 sub rmdirs {
3759         my ($self, $q) = @_;
3760         my $rm = $self->{rm};
3761         delete $rm->{''}; # we never delete the url we're tracking
3762         return unless %$rm;
3764         foreach (keys %$rm) {
3765                 my @d = split m#/#, $_;
3766                 my $c = shift @d;
3767                 $rm->{$c} = 1;
3768                 while (@d) {
3769                         $c .= '/' . shift @d;
3770                         $rm->{$c} = 1;
3771                 }
3772         }
3773         delete $rm->{$self->{svn_path}};
3774         delete $rm->{''}; # we never delete the url we're tracking
3775         return unless %$rm;
3777         my ($fh, $ctx) = command_output_pipe(
3778                                    qw/ls-tree --name-only -r -z/, $self->{c});
3779         local $/ = "\0";
3780         while (<$fh>) {
3781                 chomp;
3782                 my @dn = split m#/#, $_;
3783                 while (pop @dn) {
3784                         delete $rm->{join '/', @dn};
3785                 }
3786                 unless (%$rm) {
3787                         eval { command_close_pipe($fh) };
3788                         return;
3789                 }
3790         }
3791         command_close_pipe($fh, $ctx);
3793         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3794         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3795                 $self->close_directory($bat->{$d}, $p);
3796                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3797                 print "\tD+\t/$d/\n" unless $q;
3798                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3799                 delete $bat->{$d};
3800         }
3803 sub open_or_add_dir {
3804         my ($self, $full_path, $baton) = @_;
3805         my $p = SVN::Pool->new;
3806         my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
3807         $p->clear;
3808         if ($t == $SVN::Node::none) {
3809                 return $self->add_directory($full_path, $baton,
3810                                                 undef, -1, $self->{pool});
3811         } elsif ($t == $SVN::Node::dir) {
3812                 return $self->open_directory($full_path, $baton,
3813                                                 $self->{r}, $self->{pool});
3814         }
3815         print STDERR "$full_path already exists in repository at ",
3816                 "r$self->{r} and it is not a directory (",
3817                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3818         exit 1;
3821 sub ensure_path {
3822         my ($self, $path) = @_;
3823         my $bat = $self->{bat};
3824         $path = $self->repo_path($path);
3825         return $bat->{''} unless (length $path);
3826         my @p = split m#/+#, $path;
3827         my $c = shift @p;
3828         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3829         while (@p) {
3830                 my $c0 = $c;
3831                 $c .= '/' . shift @p;
3832                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3833         }
3834         return $bat->{$c};
3837 sub A {
3838         my ($self, $m, $q) = @_;
3839         my ($dir, $file) = split_path($m->{file_b});
3840         my $pbat = $self->ensure_path($dir);
3841         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3842                                         undef, -1);
3843         print "\tA\t$m->{file_b}\n" unless $q;
3844         $self->chg_file($fbat, $m);
3845         $self->close_file($fbat,undef,$self->{pool});
3848 sub C {
3849         my ($self, $m, $q) = @_;
3850         my ($dir, $file) = split_path($m->{file_b});
3851         my $pbat = $self->ensure_path($dir);
3852         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3853                                 $self->url_path($m->{file_a}), $self->{r});
3854         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3855         $self->chg_file($fbat, $m);
3856         $self->close_file($fbat,undef,$self->{pool});
3859 sub delete_entry {
3860         my ($self, $path, $pbat) = @_;
3861         my $rpath = $self->repo_path($path);
3862         my ($dir, $file) = split_path($rpath);
3863         $self->{rm}->{$dir} = 1;
3864         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3867 sub R {
3868         my ($self, $m, $q) = @_;
3869         my ($dir, $file) = split_path($m->{file_b});
3870         my $pbat = $self->ensure_path($dir);
3871         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3872                                 $self->url_path($m->{file_a}), $self->{r});
3873         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3874         $self->chg_file($fbat, $m);
3875         $self->close_file($fbat,undef,$self->{pool});
3877         ($dir, $file) = split_path($m->{file_a});
3878         $pbat = $self->ensure_path($dir);
3879         $self->delete_entry($m->{file_a}, $pbat);
3882 sub M {
3883         my ($self, $m, $q) = @_;
3884         my ($dir, $file) = split_path($m->{file_b});
3885         my $pbat = $self->ensure_path($dir);
3886         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3887                                 $pbat,$self->{r},$self->{pool});
3888         print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3889         $self->chg_file($fbat, $m);
3890         $self->close_file($fbat,undef,$self->{pool});
3893 sub T { shift->M(@_) }
3895 sub change_file_prop {
3896         my ($self, $fbat, $pname, $pval) = @_;
3897         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3900 sub chg_file {
3901         my ($self, $fbat, $m) = @_;
3902         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3903                 $self->change_file_prop($fbat,'svn:executable','*');
3904         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3905                 $self->change_file_prop($fbat,'svn:executable',undef);
3906         }
3907         my $fh = IO::File->new_tmpfile or croak $!;
3908         if ($m->{mode_b} =~ /^120/) {
3909                 print $fh 'link ' or croak $!;
3910                 $self->change_file_prop($fbat,'svn:special','*');
3911         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3912                 $self->change_file_prop($fbat,'svn:special',undef);
3913         }
3914         defined(my $pid = fork) or croak $!;
3915         if (!$pid) {
3916                 open STDOUT, '>&', $fh or croak $!;
3917                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3918         }
3919         waitpid $pid, 0;
3920         croak $? if $?;
3921         $fh->flush == 0 or croak $!;
3922         seek $fh, 0, 0 or croak $!;
3924         my $md5 = Digest::MD5->new;
3925         $md5->addfile($fh) or croak $!;
3926         seek $fh, 0, 0 or croak $!;
3928         my $exp = $md5->hexdigest;
3929         my $pool = SVN::Pool->new;
3930         my $atd = $self->apply_textdelta($fbat, undef, $pool);
3931         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3932         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3933         $pool->clear;
3935         close $fh or croak $!;
3938 sub D {
3939         my ($self, $m, $q) = @_;
3940         my ($dir, $file) = split_path($m->{file_b});
3941         my $pbat = $self->ensure_path($dir);
3942         print "\tD\t$m->{file_b}\n" unless $q;
3943         $self->delete_entry($m->{file_b}, $pbat);
3946 sub close_edit {
3947         my ($self) = @_;
3948         my ($p,$bat) = ($self->{pool}, $self->{bat});
3949         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3950                 $self->close_directory($bat->{$_}, $p);
3951         }
3952         $self->SUPER::close_edit($p);
3953         $p->clear;
3956 sub abort_edit {
3957         my ($self) = @_;
3958         $self->SUPER::abort_edit($self->{pool});
3959         $self->{pool}->clear;
3962 __END__
3964 Data structures:
3966 $svn_log hashref (as returned by svn_log_raw)
3968         fh => file handle of the log file,
3969         state => state of the log file parser (sep/msg/rev/msg_start...)
3972 $log_msg hashref as returned by next_log_entry($svn_log)
3974         msg => 'whitespace-formatted log entry
3975 ',                                              # trailing newline is preserved
3976         revision => '8',                        # integer
3977         date => '2004-02-24T17:01:44.108345Z',  # commit date
3978         author => 'committer name'
3979 };
3982 @mods = array of diff-index line hashes, each element represents one line
3983         of diff-index output
3985 diff-index line ($m hash)
3987         mode_a => first column of diff-index output, no leading ':',
3988         mode_b => second column of diff-index output,
3989         sha1_b => sha1sum of the final blob,
3990         chg => change type [MCRADT],
3991         file_a => original file name of a file (iff chg is 'C' or 'R')
3992         file_b => new/current file name of a file (any chg)
3996 # retval of read_url_paths{,_all}();
3997 $l_map = {
3998         # repository root url
3999         'https://svn.musicpd.org' => {
4000                 # repository path               # GIT_SVN_ID
4001                 'mpd/trunk'             =>      'trunk',
4002                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
4003         },
4006 Notes:
4007         I don't trust the each() function on unless I created %hash myself
4008         because the internal iterator may not have started at base.