Code

git-svn: make multi-init capable of reusing the Ra connection
[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
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 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
36 require SVN::Ra;
37 require SVN::Delta;
38 if ($SVN::Core::VERSION lt '1.1.0') {
39         fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
40 }
41 push @Git::SVN::Ra::ISA, 'SVN::Ra';
42 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
43 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
44 use Carp qw/croak/;
45 use IO::File qw//;
46 use File::Basename qw/dirname basename/;
47 use File::Path qw/mkpath/;
48 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
49 use POSIX qw/strftime/;
50 use IPC::Open3;
51 use Memoize;
52 use Git;
53 memoize('revisions_eq');
54 memoize('cmt_metadata');
55 memoize('get_commit_time');
57 BEGIN {
58         my $s;
59         foreach (qw/command command_oneline command_noisy command_output_pipe
60                     command_input_pipe command_close_pipe/) {
61                 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
62                       "*$_ = *Git::$_; ";
63         }
64         eval $s;
65 }
67 my ($SVN);
69 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
70 my $sha1 = qr/[a-f\d]{40}/;
71 my $sha1_short = qr/[a-f\d]{4,40}/;
72 my $_esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
73 my ($_revision,$_stdin,$_help,$_rmdir,$_edit,
74         $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
75         $_repack, $_repack_nr, $_repack_flags, $_q,
76         $_message, $_file, $_no_metadata,
77         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
78         $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
79         $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
80         $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
81         $_pager, $_color, $_prefix);
82 my (@_branch_from, %tree_map, %users, %rusers);
83 my @repo_path_split_cache;
84 use vars qw/$_follow_parent/;
86 my %fc_opts = ( 'branch|b=s' => \@_branch_from,
87                 'follow-parent|follow' => \$_follow_parent,
88                 'branch-all-refs|B' => \$_branch_all_refs,
89                 'authors-file|A=s' => \$_authors,
90                 'repack:i' => \$_repack,
91                 'no-metadata' => \$_no_metadata,
92                 'quiet|q' => \$_q,
93                 'username=s' => \$Git::SVN::Prompt::_username,
94                 'config-dir=s' => \$Git::SVN::Ra::config_dir,
95                 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96                 'ignore-nodate' => \$_ignore_nodate,
97                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
99 my ($_trunk, $_tags, $_branches);
100 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
101                 'tags|t=s' => \$_tags,
102                 'branches|b=s' => \$_branches );
103 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
104 my %cmt_opts = ( 'edit|e' => \$_edit,
105                 'rmdir' => \$_rmdir,
106                 'find-copies-harder' => \$_find_copies_harder,
107                 'l=i' => \$_l,
108                 'copy-similarity|C=i'=> \$_cp_similarity
109 );
111 my %cmd = (
112         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
113                         { 'revision|r=s' => \$_revision, %fc_opts } ],
114         init => [ \&cmd_init, "Initialize a repo for tracking" .
115                           " (requires URL argument)",
116                           \%init_opts ],
117         dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
118                         { 'merge|m|M' => \$_merge,
119                           'strategy|s=s' => \$_strategy,
120                           'dry-run|n' => \$_dry_run,
121                         %cmt_opts, %fc_opts } ],
122         'set-tree' => [ \&commit, "Set an SVN repository to a git tree-ish",
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                         { 'copy-remote|remote=s' => \$_cp_remote,
128                           'upgrade' => \$_upgrade } ],
129         'graft-branches' => [ \&graft_branches,
130                         'Detect merges/branches from already imported history',
131                         { 'merge-rx|m' => \@_opt_m,
132                           'branch|b=s' => \@_branch_from,
133                           'branch-all-refs|B' => \$_branch_all_refs,
134                           'no-default-regex' => \$_no_default_regex,
135                           'no-graft-copy' => \$_no_graft_copy } ],
136         'multi-init' => [ \&cmd_multi_init,
137                         'Initialize multiple trees (like git-svnimport)',
138                         { %multi_opts, %init_opts,
139                          'revision|r=i' => \$_revision,
140                          'username=s' => \$Git::SVN::Prompt::_username,
141                          'config-dir=s' => \$Git::SVN::Ra::config_dir,
142                          'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
143                          'prefix=s' => \$_prefix,
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 );
167 my $cmd;
168 for (my $i = 0; $i < @ARGV; $i++) {
169         if (defined $cmd{$ARGV[$i]}) {
170                 $cmd = $ARGV[$i];
171                 splice @ARGV, $i, 1;
172                 last;
173         }
174 };
176 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
178 read_repo_config(\%opts);
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
180                                 'version|V' => \$_version,
181                                 'id|i=s' => \$GIT_SVN);
182 exit 1 if (!$rv && $cmd ne 'log');
184 set_default_vals();
185 usage(0) if $_help;
186 version() if $_version;
187 usage(1) unless defined $cmd;
188 init_vars();
189 load_authors() if $_authors;
190 load_all_refs() if $_branch_all_refs;
191 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
192 $cmd{$cmd}->[0]->(@ARGV);
193 exit 0;
195 ####################### primary functions ######################
196 sub usage {
197         my $exit = shift || 0;
198         my $fd = $exit ? \*STDERR : \*STDOUT;
199         print $fd <<"";
200 git-svn - bidirectional operations between a single Subversion tree and git
201 Usage: $0 <command> [options] [arguments]\n
203         print $fd "Available commands:\n" unless $cmd;
205         foreach (sort keys %cmd) {
206                 next if $cmd && $cmd ne $_;
207                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
208                 foreach (keys %{$cmd{$_}->[2]}) {
209                         # prints out arguments as they should be passed:
210                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
211                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
212                                                         "--$_" : "-$_" }
213                                                 split /\|/,$_)," $x\n";
214                 }
215         }
216         print $fd <<"";
217 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
218 arbitrary identifier if you're tracking multiple SVN branches/repositories in
219 one git repository and want to keep them separate.  See git-svn(1) for more
220 information.
222         exit $exit;
225 sub version {
226         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
227         exit 0;
230 sub rebuild {
231         if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
232                 copy_remote_ref();
233         }
234         $SVN_URL = shift or undef;
235         my $newest_rev = 0;
236         if ($_upgrade) {
237                 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
238                               $GIT_SVN-HEAD");
239         } else {
240                 check_upgrade_needed();
241         }
243         my ($rev_list, $ctx) = command_output_pipe("rev-list",
244                                                    "refs/remotes/$GIT_SVN");
245         my $latest;
246         my $svn_uuid;
247         while (<$rev_list>) {
248                 chomp;
249                 my $c = $_;
250                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
251                 my @commit = grep(/^git-svn-id: /,
252                                   command(qw/cat-file commit/, $c));
253                 next if (!@commit); # skip merges
254                 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
255                 if (!defined $rev || !$uuid) {
256                         croak "Unable to extract revision or UUID from ",
257                                 "$c, $commit[$#commit]\n";
258                 }
260                 # if we merged or otherwise started elsewhere, this is
261                 # how we break out of it
262                 next if (defined $svn_uuid && ($uuid ne $svn_uuid));
263                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
265                 unless (defined $latest) {
266                         if (!$SVN_URL && !$url) {
267                                 croak "SVN repository location required: $url\n";
268                         }
269                         $SVN_URL ||= $url;
270                         $svn_uuid ||= $uuid;
271                         setup_git_svn();
272                         $latest = $rev;
273                 }
274                 revdb_set($REVDB, $rev, $c);
275                 print "r$rev = $c\n";
276                 $newest_rev = $rev if ($rev > $newest_rev);
277         }
278         command_close_pipe($rev_list, $ctx);
281 sub do_git_init_db {
282         unless (-d $ENV{GIT_DIR}) {
283                 my @init_db = ('init');
284                 push @init_db, "--template=$_template" if defined $_template;
285                 push @init_db, "--shared" if defined $_shared;
286                 command_noisy(@init_db);
287         }
290 sub cmd_init {
291         my $url = shift or die "SVN repository location required " .
292                                 "as a command-line argument\n";
293         if (my $repo_path = shift) {
294                 unless (-d $repo_path) {
295                         mkpath([$repo_path]);
296                 }
297                 chdir $repo_path or croak $!;
298                 $ENV{GIT_DIR} = $repo_path . "/.git";
299         }
300         do_git_init_db();
302         Git::SVN->init(undef, $url);
305 sub cmd_fetch {
306         fetch_child_id($GIT_SVN, @_);
309 sub fetch {
310         check_upgrade_needed();
311         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
312         my $ret = fetch_lib(@_);
313         if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
314                 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
315         }
316         return $ret;
319 sub fetch_lib {
320         my (@parents) = @_;
321         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
322         $SVN ||= Git::SVN::Ra->new($SVN_URL);
323         my ($last_rev, $last_commit) = svn_grab_base_rev();
324         my ($base, $head) = libsvn_parse_revision($last_rev);
325         if ($base > $head) {
326                 return { revision => $last_rev, commit => $last_commit }
327         }
328         my $index = set_index($GIT_SVN_INDEX);
330         # limit ourselves and also fork() since get_log won't release memory
331         # after processing a revision and SVN stuff seems to leak
332         my $inc = 1000;
333         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
334         if (defined $last_commit) {
335                 unless (-e $GIT_SVN_INDEX) {
336                         command_noisy('read-tree', $last_commit);
337                 }
338                 my $x = command_oneline('write-tree');
339                 my ($y) = (command(qw/cat-file commit/, $last_commit)
340                                                         =~ /^tree ($sha1)/m);
341                 if ($y ne $x) {
342                         unlink $GIT_SVN_INDEX or croak $!;
343                         command_noisy('read-tree', $last_commit);
344                 }
345                 $x = command_oneline('write-tree');
346                 if ($y ne $x) {
347                         print STDERR "trees ($last_commit) $y != $x\n",
348                                  "Something is seriously wrong...\n";
349                 }
350         }
351         while (1) {
352                 # fork, because using SVN::Pool with get_log() still doesn't
353                 # seem to help enough to keep memory usage down.
354                 defined(my $pid = fork) or croak $!;
355                 if (!$pid) {
356                         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
358                         # Yes I'm perfectly aware that the fourth argument
359                         # below is the limit revisions number.  Unfortunately
360                         # performance sucks with it enabled, so it's much
361                         # faster to fetch revision ranges instead of relying
362                         # on the limiter.
363                         $SVN->dup->get_log([''], $min, $max, 0, 1, 1,
364                                 sub {
365                                         my $log_msg;
366                                         if ($last_commit) {
367                                                 $log_msg = libsvn_fetch(
368                                                         $last_commit, @_);
369                                                 $last_commit = git_commit(
370                                                         $log_msg,
371                                                         $last_commit,
372                                                         @parents);
373                                         } else {
374                                                 $log_msg = libsvn_new_tree(@_);
375                                                 $last_commit = git_commit(
376                                                         $log_msg, @parents);
377                                         }
378                                 });
379                         exit 0;
380                 }
381                 waitpid $pid, 0;
382                 croak $? if $?;
383                 ($last_rev, $last_commit) = svn_grab_base_rev();
384                 last if ($max >= $head);
385                 $min = $max + 1;
386                 $max += $inc;
387                 $max = $head if ($max > $head);
388                 $SVN = Git::SVN::Ra->new($SVN_URL);
389         }
390         restore_index($index);
391         return { revision => $last_rev, commit => $last_commit };
394 sub commit {
395         my (@commits) = @_;
396         check_upgrade_needed();
397         if ($_stdin || !@commits) {
398                 print "Reading from stdin...\n";
399                 @commits = ();
400                 while (<STDIN>) {
401                         if (/\b($sha1_short)\b/o) {
402                                 unshift @commits, $1;
403                         }
404                 }
405         }
406         my @revs;
407         foreach my $c (@commits) {
408                 my @tmp = command('rev-parse',$c);
409                 if (scalar @tmp == 1) {
410                         push @revs, $tmp[0];
411                 } elsif (scalar @tmp > 1) {
412                         push @revs, reverse(command('rev-list',@tmp));
413                 } else {
414                         die "Failed to rev-parse $c\n";
415                 }
416         }
417         commit_lib(@revs);
418         print "Done committing ",scalar @revs," revisions to SVN\n";
421 sub commit_lib {
422         my (@revs) = @_;
423         my ($r_last, $cmt_last) = svn_grab_base_rev();
424         defined $r_last or die "Must have an existing revision to commit\n";
425         my $fetched = fetch();
426         if ($r_last != $fetched->{revision}) {
427                 print STDERR "There are new revisions that were fetched ",
428                                 "and need to be merged (or acknowledged) ",
429                                 "before committing.\n",
430                                 "last rev: $r_last\n",
431                                 " current: $fetched->{revision}\n";
432                 exit 1;
433         }
434         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
436         my $repo;
437         set_svn_commit_env();
438         foreach my $c (@revs) {
439                 my $log_msg = get_commit_message($c, $commit_msg);
441                 # fork for each commit because there's a memory leak I
442                 # can't track down... (it's probably in the SVN code)
443                 defined(my $pid = open my $fh, '-|') or croak $!;
444                 if (!$pid) {
445                         my $pool = SVN::Pool->new;
446                         my $ed = SVN::Git::Editor->new(
447                                         {       r => $r_last,
448                                                 ra => $SVN->dup,
449                                                 c => $c,
450                                                 svn_path => $SVN->{svn_path},
451                                         },
452                                         $SVN->get_commit_editor(
453                                                 $log_msg->{msg},
454                                                 sub {
455                                                         libsvn_commit_cb(
456                                                                 @_, $c,
457                                                                 $log_msg->{msg},
458                                                                 $r_last,
459                                                                 $cmt_last)
460                                                 }, $pool)
461                                         );
462                         my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
463                         if (@$mods == 0) {
464                                 print "No changes\nr$r_last = $cmt_last\n";
465                                 $ed->abort_edit;
466                         } else {
467                                 $ed->close_edit;
468                         }
469                         $pool->clear;
470                         exit 0;
471                 }
472                 my ($r_new, $cmt_new, $no);
473                 while (<$fh>) {
474                         print $_;
475                         chomp;
476                         if (/^r(\d+) = ($sha1)$/o) {
477                                 ($r_new, $cmt_new) = ($1, $2);
478                         } elsif ($_ eq 'No changes') {
479                                 $no = 1;
480                         }
481                 }
482                 close $fh or exit 1;
483                 if (! defined $r_new && ! defined $cmt_new) {
484                         unless ($no) {
485                                 die "Failed to parse revision information\n";
486                         }
487                 } else {
488                         ($r_last, $cmt_last) = ($r_new, $cmt_new);
489                 }
490         }
491         $ENV{LC_ALL} = 'C';
492         unlink $commit_msg;
495 sub dcommit {
496         my $head = shift || 'HEAD';
497         my $gs = "refs/remotes/$GIT_SVN";
498         my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
499         my $last_rev;
500         foreach my $d (reverse @refs) {
501                 if (!verify_ref("$d~1")) {
502                         die "Commit $d\n",
503                             "has no parent commit, and therefore ",
504                             "nothing to diff against.\n",
505                             "You should be working from a repository ",
506                             "originally created by git-svn\n";
507                 }
508                 unless (defined $last_rev) {
509                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
510                         unless (defined $last_rev) {
511                                 die "Unable to extract revision information ",
512                                     "from commit $d~1\n";
513                         }
514                 }
515                 if ($_dry_run) {
516                         print "diff-tree $d~1 $d\n";
517                 } else {
518                         if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
519                                 $last_rev = $r;
520                         } # else: no changes, same $last_rev
521                 }
522         }
523         return if $_dry_run;
524         fetch();
525         my @diff = command('diff-tree', 'HEAD', $gs, '--');
526         my @finish;
527         if (@diff) {
528                 @finish = qw/rebase/;
529                 push @finish, qw/--merge/ if $_merge;
530                 push @finish, "--strategy=$_strategy" if $_strategy;
531                 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
532         } else {
533                 print "No changes between current HEAD and $gs\n",
534                       "Resetting to the latest $gs\n";
535                 @finish = qw/reset --mixed/;
536         }
537         command_noisy(@finish, $gs);
540 sub show_ignore {
541         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
542         my $repo;
543         $SVN ||= Git::SVN::Ra->new($SVN_URL);
544         my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
545         libsvn_traverse_ignore(\*STDOUT, '', $r);
548 sub graft_branches {
549         my $gr_file = "$GIT_DIR/info/grafts";
550         my ($grafts, $comments) = read_grafts($gr_file);
551         my $gr_sha1;
553         if (%$grafts) {
554                 # temporarily disable our grafts file to make this idempotent
555                 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
556                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
557         }
559         my $l_map = read_url_paths();
560         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
561         unless ($_no_default_regex) {
562                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
563                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
564                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
565         }
566         foreach my $u (keys %$l_map) {
567                 if (@re) {
568                         foreach my $p (keys %{$l_map->{$u}}) {
569                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
570                         }
571                 }
572                 unless ($_no_graft_copy) {
573                         graft_file_copy_lib($grafts,$l_map,$u);
574                 }
575         }
576         graft_tree_joins($grafts);
578         write_grafts($grafts, $comments, $gr_file);
579         unlink "$gr_file~$gr_sha1" if $gr_sha1;
582 sub cmd_multi_init {
583         my $url = shift;
584         unless (defined $_trunk || defined $_branches || defined $_tags) {
585                 usage(1);
586         }
587         do_git_init_db();
588         $_prefix = '' unless defined $_prefix;
589         if (defined $_trunk) {
590                 my $gs_trunk = eval { Git::SVN->new($_prefix . 'trunk') };
591                 unless ($gs_trunk) {
592                         my $trunk_url = complete_svn_url($url, $_trunk);
593                         $gs_trunk = Git::SVN->init($_prefix . 'trunk',
594                                                    $trunk_url);
595                         command_noisy('config', 'svn.trunk', $trunk_url);
596                 }
597         }
598         my $ra = $url ? Git::SVN::Ra->new($url) : undef;
599         complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
600         complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
603 sub multi_fetch {
604         # try to do trunk first, since branches/tags
605         # may be descended from it.
606         if (-e "$GIT_DIR/svn/trunk/info/url") {
607                 fetch_child_id('trunk', @_);
608         }
609         rec_fetch('', "$GIT_DIR/svn", @_);
612 sub show_log {
613         my (@args) = @_;
614         my ($r_min, $r_max);
615         my $r_last = -1; # prevent dupes
616         rload_authors() if $_authors;
617         if (defined $TZ) {
618                 $ENV{TZ} = $TZ;
619         } else {
620                 delete $ENV{TZ};
621         }
622         if (defined $_revision) {
623                 if ($_revision =~ /^(\d+):(\d+)$/) {
624                         ($r_min, $r_max) = ($1, $2);
625                 } elsif ($_revision =~ /^\d+$/) {
626                         $r_min = $r_max = $_revision;
627                 } else {
628                         print STDERR "-r$_revision is not supported, use ",
629                                 "standard \'git log\' arguments instead\n";
630                         exit 1;
631                 }
632         }
634         config_pager();
635         @args = (git_svn_log_cmd($r_min, $r_max), @args);
636         my $log = command_output_pipe(@args);
637         run_pager();
638         my (@k, $c, $d);
640         while (<$log>) {
641                 if (/^${_esc_color}commit ($sha1_short)/o) {
642                         my $cmt = $1;
643                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
644                                 $r_last = $c->{r};
645                                 process_commit($c, $r_min, $r_max, \@k) or
646                                                                 goto out;
647                         }
648                         $d = undef;
649                         $c = { c => $cmt };
650                 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
651                         get_author_info($c, $1, $2, $3);
652                 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
653                         # ignore
654                 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
655                         push @{$c->{raw}}, $_;
656                 } elsif (/^${_esc_color}[ACRMDT]\t/) {
657                         # we could add $SVN->{svn_path} here, but that requires
658                         # remote access at the moment (repo_path_split)...
659                         s#^(${_esc_color})([ACRMDT])\t#$1   $2 #;
660                         push @{$c->{changed}}, $_;
661                 } elsif (/^${_esc_color}diff /) {
662                         $d = 1;
663                         push @{$c->{diff}}, $_;
664                 } elsif ($d) {
665                         push @{$c->{diff}}, $_;
666                 } elsif (/^${_esc_color}    (git-svn-id:.+)$/) {
667                         ($c->{url}, $c->{r}, undef) = extract_metadata($1);
668                 } elsif (s/^${_esc_color}    //) {
669                         push @{$c->{l}}, $_;
670                 }
671         }
672         if ($c && defined $c->{r} && $c->{r} != $r_last) {
673                 $r_last = $c->{r};
674                 process_commit($c, $r_min, $r_max, \@k);
675         }
676         if (@k) {
677                 my $swap = $r_max;
678                 $r_max = $r_min;
679                 $r_min = $swap;
680                 process_commit($_, $r_min, $r_max) foreach reverse @k;
681         }
682 out:
683         close $log;
684         print '-' x72,"\n" unless $_incremental || $_oneline;
687 sub commit_diff_usage {
688         print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
689         exit 1
692 sub commit_diff {
693         my $ta = shift or commit_diff_usage();
694         my $tb = shift or commit_diff_usage();
695         if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
696                 print STDERR "Needed URL or usable git-svn id command-line\n";
697                 commit_diff_usage();
698         }
699         my $r = shift;
700         unless (defined $r) {
701                 if (defined $_revision) {
702                         $r = $_revision
703                 } else {
704                         die "-r|--revision is a required argument\n";
705                 }
706         }
707         if (defined $_message && defined $_file) {
708                 print STDERR "Both --message/-m and --file/-F specified ",
709                                 "for the commit message.\n",
710                                 "I have no idea what you mean\n";
711                 exit 1;
712         }
713         if (defined $_file) {
714                 $_message = file_to_s($_file);
715         } else {
716                 $_message ||= get_commit_message($tb,
717                                         "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
718         }
719         $SVN ||= Git::SVN::Ra->new($SVN_URL);
720         if ($r eq 'HEAD') {
721                 $r = $SVN->get_latest_revnum;
722         } elsif ($r !~ /^\d+$/) {
723                 die "revision argument: $r not understood by git-svn\n";
724         }
725         my $rev_committed;
726         my $pool = SVN::Pool->new;
727         my $ed = SVN::Git::Editor->new({        r => $r,
728                                                 ra => $SVN->dup,
729                                                 c => $tb,
730                                                 svn_path => $SVN->{svn_path}
731                                         },
732                                 $SVN->get_commit_editor($_message,
733                                         sub {
734                                                 $rev_committed = $_[0];
735                                                 print "Committed $_[0]\n";
736                                         },
737                                         $pool)
738                                 );
739         eval {
740                 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
741                 if (@$mods == 0) {
742                         print "No changes\n$ta == $tb\n";
743                         $ed->abort_edit;
744                 } else {
745                         $ed->close_edit;
746                 }
747         };
748         $pool->clear;
749         fatal "$@\n" if $@;
750         $_message = $_file = undef;
751         return $rev_committed;
754 ########################### utility functions #########################
756 sub cmt_showable {
757         my ($c) = @_;
758         return 1 if defined $c->{r};
759         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
760                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
761                 my @msg = command(qw/cat-file commit/, $c->{c});
762                 shift @msg while ($msg[0] ne "\n");
763                 shift @msg;
764                 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
766                 (undef, $c->{r}, undef) = extract_metadata(
767                                 (grep(/^git-svn-id: /, @msg))[-1]);
768         }
769         return defined $c->{r};
772 sub log_use_color {
773         return 1 if $_color;
774         my ($dc, $dcvar);
775         $dcvar = 'color.diff';
776         $dc = `git-config --get $dcvar`;
777         if ($dc eq '') {
778                 # nothing at all; fallback to "diff.color"
779                 $dcvar = 'diff.color';
780                 $dc = `git-config --get $dcvar`;
781         }
782         chomp($dc);
783         if ($dc eq 'auto') {
784                 my $pc;
785                 $pc = `git-config --get color.pager`;
786                 if ($pc eq '') {
787                         # does not have it -- fallback to pager.color
788                         $pc = `git-config --bool --get pager.color`;
789                 }
790                 else {
791                         $pc = `git-config --bool --get color.pager`;
792                         if ($?) {
793                                 $pc = 'false';
794                         }
795                 }
796                 chomp($pc);
797                 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
798                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
799                 }
800                 return 0;
801         }
802         return 0 if $dc eq 'never';
803         return 1 if $dc eq 'always';
804         chomp($dc = `git-config --bool --get $dcvar`);
805         return ($dc eq 'true');
808 sub git_svn_log_cmd {
809         my ($r_min, $r_max) = @_;
810         my @cmd = (qw/log --abbrev-commit --pretty=raw
811                         --default/, "refs/remotes/$GIT_SVN");
812         push @cmd, '-r' unless $_non_recursive;
813         push @cmd, qw/--raw --name-status/ if $_verbose;
814         push @cmd, '--color' if log_use_color();
815         return @cmd unless defined $r_max;
816         if ($r_max == $r_min) {
817                 push @cmd, '--max-count=1';
818                 if (my $c = revdb_get($REVDB, $r_max)) {
819                         push @cmd, $c;
820                 }
821         } else {
822                 my ($c_min, $c_max);
823                 $c_max = revdb_get($REVDB, $r_max);
824                 $c_min = revdb_get($REVDB, $r_min);
825                 if (defined $c_min && defined $c_max) {
826                         if ($r_max > $r_max) {
827                                 push @cmd, "$c_min..$c_max";
828                         } else {
829                                 push @cmd, "$c_max..$c_min";
830                         }
831                 } elsif ($r_max > $r_min) {
832                         push @cmd, $c_max;
833                 } else {
834                         push @cmd, $c_min;
835                 }
836         }
837         return @cmd;
840 sub fetch_child_id {
841         my $id = shift;
842         print "Fetching $id\n";
843         my $ref = "$GIT_DIR/refs/remotes/$id";
844         defined(my $pid = open my $fh, '-|') or croak $!;
845         if (!$pid) {
846                 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
847                 init_vars();
848                 fetch(@_);
849                 exit 0;
850         }
851         while (<$fh>) {
852                 print $_;
853                 check_repack() if (/^r\d+ = $sha1/o);
854         }
855         close $fh or croak $?;
858 sub rec_fetch {
859         my ($pfx, $p, @args) = @_;
860         my @dir;
861         foreach (sort <$p/*>) {
862                 if (-r "$_/info/url") {
863                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
864                         my $id = $pfx . basename $_;
865                         next if $id eq 'trunk';
866                         fetch_child_id($id, @args);
867                 } elsif (-d $_) {
868                         push @dir, $_;
869                 }
870         }
871         foreach (@dir) {
872                 my $x = $_;
873                 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
874                 rec_fetch($x, $_);
875         }
878 sub complete_svn_url {
879         my ($url, $path) = @_;
880         $path =~ s#/+$##;
881         $url =~ s#/+$## if $url;
882         if ($path !~ m#^[a-z\+]+://#) {
883                 $path = '/' . $path if ($path !~ m#^/#);
884                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
885                         fatal("E: '$path' is not a complete URL ",
886                               "and a separate URL is not specified\n");
887                 }
888                 $path = $url . $path;
889         }
890         return $path;
893 sub complete_url_ls_init {
894         my ($ra, $path, $switch, $pfx) = @_;
895         unless ($path) {
896                 print STDERR "W: $switch not specified\n";
897                 return;
898         }
899         $path =~ s#/+$##;
900         if ($path =~ m#^[a-z\+]+://#) {
901                 $ra = Git::SVN::Ra->new($path);
902                 $path = '';
903         } else {
904                 $path =~ s#^/+##;
905                 unless ($ra) {
906                         fatal("E: '$path' is not a complete URL ",
907                               "and a separate URL is not specified\n");
908                 }
909         }
910         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
911         my ($dirent, undef, undef) = $ra->get_dir($path, $r);
912         my $url = $ra->{url} . (length $path ? "/$path" : '');
913         foreach my $d (sort keys %$dirent) {
914                 next if ($dirent->{$d}->kind != $SVN::Node::dir);
915                 my $u =  "$url/$d";
916                 my $id = "$pfx$d";
917                 my $gs = eval { Git::SVN->new($id) };
918                 # don't try to init already existing refs
919                 unless ($gs) {
920                         print "init $u => $id\n";
921                         Git::SVN->init($id, $u);
922                 }
923         }
924         my ($n) = ($switch =~ /^--(\w+)/);
925         command_noisy('config', "svn.$n", $url);
928 sub common_prefix {
929         my $paths = shift;
930         my %common;
931         foreach (@$paths) {
932                 my @tmp = split m#/#, $_;
933                 my $p = '';
934                 while (my $x = shift @tmp) {
935                         $p .= "/$x";
936                         $common{$p} ||= 0;
937                         $common{$p}++;
938                 }
939         }
940         foreach (sort {length $b <=> length $a} keys %common) {
941                 if ($common{$_} == @$paths) {
942                         return $_;
943                 }
944         }
945         return '';
948 # grafts set here are 'stronger' in that they're based on actual tree
949 # matches, and won't be deleted from merge-base checking in write_grafts()
950 sub graft_tree_joins {
951         my $grafts = shift;
952         map_tree_joins() if (@_branch_from && !%tree_map);
953         return unless %tree_map;
955         git_svn_each(sub {
956                 my $i = shift;
957                 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
958                 my ($fh, $ctx) = command_output_pipe(@args);
959                 while (<$fh>) {
960                         next unless /^commit ($sha1)$/o;
961                         my $c = $1;
962                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
963                         next unless $tree_map{$t};
965                         my $l;
966                         do {
967                                 $l = readline $fh;
968                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
970                         my ($s, $tz) = ($1, $2);
971                         if ($tz =~ s/^\+//) {
972                                 $s += tz_to_s_offset($tz);
973                         } elsif ($tz =~ s/^\-//) {
974                                 $s -= tz_to_s_offset($tz);
975                         }
977                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
979                         foreach my $p (@{$tree_map{$t}}) {
980                                 next if $p eq $c;
981                                 my $mb = eval { command('merge-base', $c, $p) };
982                                 next unless ($@ || $?);
983                                 if (defined $r_a) {
984                                         # see if SVN says it's a relative
985                                         my ($url_b, $r_b, $uuid_b) =
986                                                         cmt_metadata($p);
987                                         next if (defined $url_b &&
988                                                         defined $url_a &&
989                                                         ($url_a eq $url_b) &&
990                                                         ($uuid_a eq $uuid_b));
991                                         if ($uuid_a eq $uuid_b) {
992                                                 if ($r_b < $r_a) {
993                                                         $grafts->{$c}->{$p} = 2;
994                                                         next;
995                                                 } elsif ($r_b > $r_a) {
996                                                         $grafts->{$p}->{$c} = 2;
997                                                         next;
998                                                 }
999                                         }
1000                                 }
1001                                 my $ct = get_commit_time($p);
1002                                 if ($ct < $s) {
1003                                         $grafts->{$c}->{$p} = 2;
1004                                 } elsif ($ct > $s) {
1005                                         $grafts->{$p}->{$c} = 2;
1006                                 }
1007                                 # what should we do when $ct == $s ?
1008                         }
1009                 }
1010                 command_close_pipe($fh, $ctx);
1011         });
1014 sub graft_file_copy_lib {
1015         my ($grafts, $l_map, $u) = @_;
1016         my $tree_paths = $l_map->{$u};
1017         my $pfx = common_prefix([keys %$tree_paths]);
1018         my ($repo, $path) = repo_path_split($u.$pfx);
1019         $SVN = Git::SVN::Ra->new($repo);
1021         my ($base, $head) = libsvn_parse_revision();
1022         my $inc = 1000;
1023         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1024         my $eh = $SVN::Error::handler;
1025         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1026         while (1) {
1027                 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
1028                         sub {
1029                                 libsvn_graft_file_copies($grafts, $tree_paths,
1030                                                         $path, @_);
1031                         });
1032                 last if ($max >= $head);
1033                 $min = $max + 1;
1034                 $max += $inc;
1035                 $max = $head if ($max > $head);
1036         }
1037         $SVN::Error::handler = $eh;
1040 sub process_merge_msg_matches {
1041         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1042         my (@strong, @weak);
1043         foreach (@matches) {
1044                 # merging with ourselves is not interesting
1045                 next if $_ eq $p;
1046                 if ($l_map->{$u}->{$_}) {
1047                         push @strong, $_;
1048                 } else {
1049                         push @weak, $_;
1050                 }
1051         }
1052         foreach my $w (@weak) {
1053                 last if @strong;
1054                 # no exact match, use branch name as regexp.
1055                 my $re = qr/\Q$w\E/i;
1056                 foreach (keys %{$l_map->{$u}}) {
1057                         if (/$re/) {
1058                                 push @strong, $l_map->{$u}->{$_};
1059                                 last;
1060                         }
1061                 }
1062                 last if @strong;
1063                 $w = basename($w);
1064                 $re = qr/\Q$w\E/i;
1065                 foreach (keys %{$l_map->{$u}}) {
1066                         if (/$re/) {
1067                                 push @strong, $l_map->{$u}->{$_};
1068                                 last;
1069                         }
1070                 }
1071         }
1072         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1073                                         \s(?:[a-f\d\-]+)$/xsm);
1074         unless (defined $rev) {
1075                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1076                                         \@(?:[a-f\d\-]+)/xsm);
1077                 return unless defined $rev;
1078         }
1079         foreach my $m (@strong) {
1080                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1081                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1082         }
1085 sub graft_merge_msg {
1086         my ($grafts, $l_map, $u, $p, @re) = @_;
1088         my $x = $l_map->{$u}->{$p};
1089         my $rl = rev_list_raw("refs/remotes/$x");
1090         while (my $c = next_rev_list_entry($rl)) {
1091                 foreach my $re (@re) {
1092                         my (@br) = ($c->{m} =~ /$re/g);
1093                         next unless @br;
1094                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1095                 }
1096         }
1099 sub verify_ref {
1100         my ($ref) = @_;
1101         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1102                                { STDERR => 0 }); };
1105 sub repo_path_split {
1106         my $full_url = shift;
1107         $full_url =~ s#/+$##;
1109         foreach (@repo_path_split_cache) {
1110                 if ($full_url =~ s#$_##) {
1111                         my $u = $1;
1112                         $full_url =~ s#^/+##;
1113                         return ($u, $full_url);
1114                 }
1115         }
1116         my $tmp = Git::SVN::Ra->new($full_url);
1117         return ($tmp->{repos_root}, $tmp->{svn_path});
1120 sub setup_git_svn {
1121         defined $SVN_URL or croak "SVN repository location required\n";
1122         unless (-d $GIT_DIR) {
1123                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1124         }
1125         mkpath([$GIT_SVN_DIR]);
1126         mkpath(["$GIT_SVN_DIR/info"]);
1127         open my $fh, '>>',$REVDB or croak $!;
1128         close $fh;
1129         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1133 sub get_tree_from_treeish {
1134         my ($treeish) = @_;
1135         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1136         my $type = command_oneline(qw/cat-file -t/, $treeish);
1137         my $expected;
1138         while ($type eq 'tag') {
1139                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1140         }
1141         if ($type eq 'commit') {
1142                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1143                                                     $treeish))[0];
1144                 ($expected) = ($expected =~ /^tree ($sha1)$/);
1145                 die "Unable to get tree from $treeish\n" unless $expected;
1146         } elsif ($type eq 'tree') {
1147                 $expected = $treeish;
1148         } else {
1149                 die "$treeish is a $type, expected tree, tag or commit\n";
1150         }
1151         return $expected;
1154 sub get_diff {
1155         my ($from, $treeish) = @_;
1156         print "diff-tree $from $treeish\n";
1157         my @diff_tree = qw(diff-tree -z -r);
1158         if ($_cp_similarity) {
1159                 push @diff_tree, "-C$_cp_similarity";
1160         } else {
1161                 push @diff_tree, '-C';
1162         }
1163         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1164         push @diff_tree, "-l$_l" if defined $_l;
1165         push @diff_tree, $from, $treeish;
1166         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1167         local $/ = "\0";
1168         my $state = 'meta';
1169         my @mods;
1170         while (<$diff_fh>) {
1171                 chomp $_; # this gets rid of the trailing "\0"
1172                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1173                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1174                         push @mods, {   mode_a => $1, mode_b => $2,
1175                                         sha1_b => $3, chg => $4 };
1176                         if ($4 =~ /^(?:C|R)$/) {
1177                                 $state = 'file_a';
1178                         } else {
1179                                 $state = 'file_b';
1180                         }
1181                 } elsif ($state eq 'file_a') {
1182                         my $x = $mods[$#mods] or croak "Empty array\n";
1183                         if ($x->{chg} !~ /^(?:C|R)$/) {
1184                                 croak "Error parsing $_, $x->{chg}\n";
1185                         }
1186                         $x->{file_a} = $_;
1187                         $state = 'file_b';
1188                 } elsif ($state eq 'file_b') {
1189                         my $x = $mods[$#mods] or croak "Empty array\n";
1190                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1191                                 croak "Error parsing $_, $x->{chg}\n";
1192                         }
1193                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1194                                 croak "Error parsing $_, $x->{chg}\n";
1195                         }
1196                         $x->{file_b} = $_;
1197                         $state = 'meta';
1198                 } else {
1199                         croak "Error parsing $_\n";
1200                 }
1201         }
1202         command_close_pipe($diff_fh, $ctx);
1203         return \@mods;
1206 sub libsvn_checkout_tree {
1207         my ($from, $treeish, $ed) = @_;
1208         my $mods = get_diff($from, $treeish);
1209         return $mods unless (scalar @$mods);
1210         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1211         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1212                 my $f = $m->{chg};
1213                 if (defined $o{$f}) {
1214                         $ed->$f($m, $_q);
1215                 } else {
1216                         croak "Invalid change type: $f\n";
1217                 }
1218         }
1219         $ed->rmdirs($_q) if $_rmdir;
1220         return $mods;
1223 sub get_commit_message {
1224         my ($commit, $commit_msg) = (@_);
1225         my %log_msg = ( msg => '' );
1226         open my $msg, '>', $commit_msg or croak $!;
1228         my $type = command_oneline(qw/cat-file -t/, $commit);
1229         if ($type eq 'commit' || $type eq 'tag') {
1230                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1231                                                          $type, $commit);
1232                 my $in_msg = 0;
1233                 while (<$msg_fh>) {
1234                         if (!$in_msg) {
1235                                 $in_msg = 1 if (/^\s*$/);
1236                         } elsif (/^git-svn-id: /) {
1237                                 # skip this, we regenerate the correct one
1238                                 # on re-fetch anyways
1239                         } else {
1240                                 print $msg $_ or croak $!;
1241                         }
1242                 }
1243                 command_close_pipe($msg_fh, $ctx);
1244         }
1245         close $msg or croak $!;
1247         if ($_edit || ($type eq 'tree')) {
1248                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1249                 system($editor, $commit_msg);
1250         }
1252         # file_to_s removes all trailing newlines, so just use chomp() here:
1253         open $msg, '<', $commit_msg or croak $!;
1254         { local $/; chomp($log_msg{msg} = <$msg>); }
1255         close $msg or croak $!;
1257         return \%log_msg;
1260 sub set_svn_commit_env {
1261         if (defined $LC_ALL) {
1262                 $ENV{LC_ALL} = $LC_ALL;
1263         } else {
1264                 delete $ENV{LC_ALL};
1265         }
1268 sub rev_list_raw {
1269         my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1270         return { fh => $fh, ctx => $c, t => { } };
1273 sub next_rev_list_entry {
1274         my $rl = shift;
1275         my $fh = $rl->{fh};
1276         my $x = $rl->{t};
1277         while (<$fh>) {
1278                 if (/^commit ($sha1)$/o) {
1279                         if ($x->{c}) {
1280                                 $rl->{t} = { c => $1 };
1281                                 return $x;
1282                         } else {
1283                                 $x->{c} = $1;
1284                         }
1285                 } elsif (/^parent ($sha1)$/o) {
1286                         $x->{p}->{$1} = 1;
1287                 } elsif (s/^    //) {
1288                         $x->{m} ||= '';
1289                         $x->{m} .= $_;
1290                 }
1291         }
1292         command_close_pipe($fh, $rl->{ctx});
1293         return ($x != $rl->{t}) ? $x : undef;
1296 sub s_to_file {
1297         my ($str, $file, $mode) = @_;
1298         open my $fd,'>',$file or croak $!;
1299         print $fd $str,"\n" or croak $!;
1300         close $fd or croak $!;
1301         chmod ($mode &~ umask, $file) if (defined $mode);
1304 sub file_to_s {
1305         my $file = shift;
1306         open my $fd,'<',$file or croak "$!: file: $file\n";
1307         local $/;
1308         my $ret = <$fd>;
1309         close $fd or croak $!;
1310         $ret =~ s/\s*$//s;
1311         return $ret;
1314 sub assert_revision_unknown {
1315         my $r = shift;
1316         if (my $c = revdb_get($REVDB, $r)) {
1317                 croak "$r = $c already exists! Why are we refetching it?";
1318         }
1321 sub git_commit {
1322         my ($log_msg, @parents) = @_;
1323         assert_revision_unknown($log_msg->{revision});
1324         map_tree_joins() if (@_branch_from && !%tree_map);
1326         my (@tmp_parents, @exec_parents, %seen_parent);
1327         if (my $lparents = $log_msg->{parents}) {
1328                 @tmp_parents = @$lparents
1329         }
1330         # commit parents can be conditionally bound to a particular
1331         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1332         foreach my $p (@parents) {
1333                 next unless defined $p;
1334                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1335                         if ($1 == $log_msg->{revision}) {
1336                                 push @tmp_parents, $2;
1337                         }
1338                 } else {
1339                         push @tmp_parents, $p if $p =~ /$sha1_short/o;
1340                 }
1341         }
1342         my $tree = $log_msg->{tree};
1343         if (!defined $tree) {
1344                 my $index = set_index($GIT_SVN_INDEX);
1345                 $tree = command_oneline('write-tree');
1346                 croak $? if $?;
1347                 restore_index($index);
1348         }
1349         # just in case we clobber the existing ref, we still want that ref
1350         # as our parent:
1351         if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1352                 chomp $cur;
1353                 push @tmp_parents, $cur;
1354         }
1356         if (exists $tree_map{$tree}) {
1357                 foreach my $p (@{$tree_map{$tree}}) {
1358                         my $skip;
1359                         foreach (@tmp_parents) {
1360                                 # see if a common parent is found
1361                                 my $mb = eval { command('merge-base', $_, $p) };
1362                                 next if ($@ || $?);
1363                                 $skip = 1;
1364                                 last;
1365                         }
1366                         next if $skip;
1367                         my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1368                         next if (($SVN->uuid eq $uuid_p) &&
1369                                                 ($log_msg->{revision} > $r_p));
1370                         next if (defined $url_p && defined $SVN_URL &&
1371                                                 ($SVN->uuid eq $uuid_p) &&
1372                                                 ($url_p eq $SVN_URL));
1373                         push @tmp_parents, $p;
1374                 }
1375         }
1376         foreach (@tmp_parents) {
1377                 next if $seen_parent{$_};
1378                 $seen_parent{$_} = 1;
1379                 push @exec_parents, $_;
1380                 # MAXPARENT is defined to 16 in commit-tree.c:
1381                 last if @exec_parents > 16;
1382         }
1384         set_commit_env($log_msg);
1385         my @exec = ('git-commit-tree', $tree);
1386         push @exec, '-p', $_  foreach @exec_parents;
1387         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1388                                                                 or croak $!;
1389         print $msg_fh $log_msg->{msg} or croak $!;
1390         unless ($_no_metadata) {
1391                 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1392                                         $SVN->uuid,"\n" or croak $!;
1393         }
1394         $msg_fh->flush == 0 or croak $!;
1395         close $msg_fh or croak $!;
1396         chomp(my $commit = do { local $/; <$out_fh> });
1397         close $out_fh or croak $!;
1398         waitpid $pid, 0;
1399         croak $? if $?;
1400         if ($commit !~ /^$sha1$/o) {
1401                 die "Failed to commit, invalid sha1: $commit\n";
1402         }
1403         command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1404         revdb_set($REVDB, $log_msg->{revision}, $commit);
1406         # this output is read via pipe, do not change:
1407         print "r$log_msg->{revision} = $commit\n";
1408         return $commit;
1411 sub check_repack {
1412         if ($_repack && (--$_repack_nr == 0)) {
1413                 $_repack_nr = $_repack;
1414                 # repack doesn't use any arguments with spaces in them, does it?
1415                 command_noisy('repack', split(/\s+/, $_repack_flags));
1416         }
1419 sub set_commit_env {
1420         my ($log_msg) = @_;
1421         my $author = $log_msg->{author};
1422         if (!defined $author || length $author == 0) {
1423                 $author = '(no author)';
1424         }
1425         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1426                                 : ($author,$author . '@' . $SVN->uuid);
1427         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1428         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1429         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1432 sub check_upgrade_needed {
1433         if (!-r $REVDB) {
1434                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1435                 open my $fh, '>>',$REVDB or croak $!;
1436                 close $fh;
1437         }
1438         return unless eval {
1439                 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1440                         {STDERR => 0});
1441         };
1442         my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1443         if ($@ || !$head) {
1444                 print STDERR "Please run: $0 rebuild --upgrade\n";
1445                 exit 1;
1446         }
1449 # fills %tree_map with a reverse mapping of trees to commits.  Useful
1450 # for finding parents to commit on.
1451 sub map_tree_joins {
1452         my %seen;
1453         foreach my $br (@_branch_from) {
1454                 my $pipe = command_output_pipe(qw/rev-list
1455                                             --topo-order --pretty=raw/, $br);
1456                 while (<$pipe>) {
1457                         if (/^commit ($sha1)$/o) {
1458                                 my $commit = $1;
1460                                 # if we've seen a commit,
1461                                 # we've seen its parents
1462                                 last if $seen{$commit};
1463                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1464                                 unless (defined $tree) {
1465                                         die "Failed to parse commit $commit\n";
1466                                 }
1467                                 push @{$tree_map{$tree}}, $commit;
1468                                 $seen{$commit} = 1;
1469                         }
1470                 }
1471                 close $pipe;
1472         }
1475 sub load_all_refs {
1476         if (@_branch_from) {
1477                 print STDERR '--branch|-b parameters are ignored when ',
1478                         "--branch-all-refs|-B is passed\n";
1479         }
1481         # don't worry about rev-list on non-commit objects/tags,
1482         # it shouldn't blow up if a ref is a blob or tree...
1483         @_branch_from = command(qw/rev-parse --symbolic --all/);
1486 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1487 sub load_authors {
1488         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1489         while (<$authors>) {
1490                 chomp;
1491                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1492                 my ($user, $name, $email) = ($1, $2, $3);
1493                 $users{$user} = [$name, $email];
1494         }
1495         close $authors or croak $!;
1498 sub rload_authors {
1499         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1500         while (<$authors>) {
1501                 chomp;
1502                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1503                 my ($user, $name, $email) = ($1, $2, $3);
1504                 $rusers{"$name <$email>"} = $user;
1505         }
1506         close $authors or croak $!;
1509 sub git_svn_each {
1510         my $sub = shift;
1511         foreach (command(qw/rev-parse --symbolic --all/)) {
1512                 next unless s#^refs/remotes/##;
1513                 chomp $_;
1514                 next unless -f "$GIT_DIR/svn/$_/info/url";
1515                 &$sub($_);
1516         }
1519 sub migrate_revdb {
1520         git_svn_each(sub {
1521                 my $id = shift;
1522                 defined(my $pid = fork) or croak $!;
1523                 if (!$pid) {
1524                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1525                         init_vars();
1526                         exit 0 if -r $REVDB;
1527                         print "Upgrading svn => git mapping...\n";
1528                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1529                         open my $fh, '>>',$REVDB or croak $!;
1530                         close $fh;
1531                         rebuild();
1532                         print "Done upgrading. You may now delete the ",
1533                                 "deprecated $GIT_SVN_DIR/revs directory\n";
1534                         exit 0;
1535                 }
1536                 waitpid $pid, 0;
1537                 croak $? if $?;
1538         });
1541 sub migration_check {
1542         migrate_revdb() unless (-e $REVDB);
1543         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1544         print "Upgrading repository...\n";
1545         unless (-d "$GIT_DIR/svn") {
1546                 mkdir "$GIT_DIR/svn" or croak $!;
1547         }
1548         print "Data from a previous version of git-svn exists, but\n\t",
1549                                 "$GIT_SVN_DIR\n\t(required for this version ",
1550                                 "($VERSION) of git-svn) does not.\n";
1552         foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1553                 next unless $x =~ s#^refs/remotes/##;
1554                 chomp $x;
1555                 next unless -f "$GIT_DIR/$x/info/url";
1556                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1557                 next unless $u;
1558                 my $dn = dirname("$GIT_DIR/svn/$x");
1559                 mkpath([$dn]) unless -d $dn;
1560                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1561         }
1562         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1563         print "Done upgrading.\n";
1566 sub find_rev_before {
1567         my ($r, $id, $eq_ok) = @_;
1568         my $f = "$GIT_DIR/svn/$id/.rev_db";
1569         return (undef,undef) unless -r $f;
1570         --$r unless $eq_ok;
1571         while ($r > 0) {
1572                 if (my $c = revdb_get($f, $r)) {
1573                         return ($r, $c);
1574                 }
1575                 --$r;
1576         }
1577         return (undef, undef);
1580 sub init_vars {
1581         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1582         $Git::SVN::default = $GIT_SVN;
1583         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1584         $REVDB = "$GIT_SVN_DIR/.rev_db";
1585         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1586         $SVN_URL = undef;
1587         %tree_map = ();
1590 # convert GetOpt::Long specs for use by git-config
1591 sub read_repo_config {
1592         return unless -d $GIT_DIR;
1593         my $opts = shift;
1594         foreach my $o (keys %$opts) {
1595                 my $v = $opts->{$o};
1596                 my ($key) = ($o =~ /^([a-z\-]+)/);
1597                 $key =~ s/-//g;
1598                 my $arg = 'git-config';
1599                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1600                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1601                 if (ref $v eq 'ARRAY') {
1602                         chomp(my @tmp = `$arg --get-all svn.$key`);
1603                         @$v = @tmp if @tmp;
1604                 } else {
1605                         chomp(my $tmp = `$arg --get svn.$key`);
1606                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1607                                 $$v = $tmp;
1608                         }
1609                 }
1610         }
1613 sub set_default_vals {
1614         if (defined $_repack) {
1615                 $_repack = 1000 if ($_repack <= 0);
1616                 $_repack_nr = $_repack;
1617                 $_repack_flags ||= '-d';
1618         }
1621 sub read_grafts {
1622         my $gr_file = shift;
1623         my ($grafts, $comments) = ({}, {});
1624         if (open my $fh, '<', $gr_file) {
1625                 my @tmp;
1626                 while (<$fh>) {
1627                         if (/^($sha1)\s+/) {
1628                                 my $c = $1;
1629                                 if (@tmp) {
1630                                         @{$comments->{$c}} = @tmp;
1631                                         @tmp = ();
1632                                 }
1633                                 foreach my $p (split /\s+/, $_) {
1634                                         $grafts->{$c}->{$p} = 1;
1635                                 }
1636                         } else {
1637                                 push @tmp, $_;
1638                         }
1639                 }
1640                 close $fh or croak $!;
1641                 @{$comments->{'END'}} = @tmp if @tmp;
1642         }
1643         return ($grafts, $comments);
1646 sub write_grafts {
1647         my ($grafts, $comments, $gr_file) = @_;
1649         open my $fh, '>', $gr_file or croak $!;
1650         foreach my $c (sort keys %$grafts) {
1651                 if ($comments->{$c}) {
1652                         print $fh $_ foreach @{$comments->{$c}};
1653                 }
1654                 my $p = $grafts->{$c};
1655                 my %x; # real parents
1656                 delete $p->{$c}; # commits are not self-reproducing...
1657                 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1658                 while (<$ch>) {
1659                         if (/^parent ($sha1)/) {
1660                                 $x{$1} = $p->{$1} = 1;
1661                         } else {
1662                                 last unless /^\S/;
1663                         }
1664                 }
1665                 close $ch; # breaking the pipe
1667                 # if real parents are the only ones in the grafts, drop it
1668                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1670                 my (@ip, @jp, $mb);
1671                 my %del = %x;
1672                 @ip = @jp = keys %$p;
1673                 foreach my $i (@ip) {
1674                         next if $del{$i} || $p->{$i} == 2;
1675                         foreach my $j (@jp) {
1676                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1677                                 $mb = eval { command('merge-base', $i, $j) };
1678                                 next unless $mb;
1679                                 chomp $mb;
1680                                 next if $x{$mb};
1681                                 if ($mb eq $j) {
1682                                         delete $p->{$i};
1683                                         $del{$i} = 1;
1684                                 } elsif ($mb eq $i) {
1685                                         delete $p->{$j};
1686                                         $del{$j} = 1;
1687                                 }
1688                         }
1689                 }
1691                 # if real parents are the only ones in the grafts, drop it
1692                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1694                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1695         }
1696         if ($comments->{'END'}) {
1697                 print $fh $_ foreach @{$comments->{'END'}};
1698         }
1699         close $fh or croak $!;
1702 sub read_url_paths_all {
1703         my ($l_map, $pfx, $p) = @_;
1704         my @dir;
1705         foreach (<$p/*>) {
1706                 if (-r "$_/info/url") {
1707                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1708                         my $id = $pfx . basename $_;
1709                         my $url = file_to_s("$_/info/url");
1710                         my ($u, $p) = repo_path_split($url);
1711                         $l_map->{$u}->{$p} = $id;
1712                 } elsif (-d $_) {
1713                         push @dir, $_;
1714                 }
1715         }
1716         foreach (@dir) {
1717                 my $x = $_;
1718                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1719                 read_url_paths_all($l_map, $x, $_);
1720         }
1723 # this one only gets ids that have been imported, not new ones
1724 sub read_url_paths {
1725         my $l_map = {};
1726         git_svn_each(sub { my $x = shift;
1727                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1728                         my ($u, $p) = repo_path_split($url);
1729                         $l_map->{$u}->{$p} = $x;
1730                         });
1731         return $l_map;
1734 sub extract_metadata {
1735         my $id = shift or return (undef, undef, undef);
1736         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1737                                                         \s([a-f\d\-]+)$/x);
1738         if (!defined $rev || !$uuid || !$url) {
1739                 # some of the original repositories I made had
1740                 # identifiers like this:
1741                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1742         }
1743         return ($url, $rev, $uuid);
1746 sub cmt_metadata {
1747         return extract_metadata((grep(/^git-svn-id: /,
1748                 command(qw/cat-file commit/, shift)))[-1]);
1751 sub get_commit_time {
1752         my $cmt = shift;
1753         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1754         while (<$fh>) {
1755                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1756                 my ($s, $tz) = ($1, $2);
1757                 if ($tz =~ s/^\+//) {
1758                         $s += tz_to_s_offset($tz);
1759                 } elsif ($tz =~ s/^\-//) {
1760                         $s -= tz_to_s_offset($tz);
1761                 }
1762                 close $fh;
1763                 return $s;
1764         }
1765         die "Can't get commit time for commit: $cmt\n";
1768 sub tz_to_s_offset {
1769         my ($tz) = @_;
1770         $tz =~ s/(\d\d)$//;
1771         return ($1 * 60) + ($tz * 3600);
1774 # adapted from pager.c
1775 sub config_pager {
1776         $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
1777         if (!defined $_pager) {
1778                 $_pager = 'less';
1779         } elsif (length $_pager == 0 || $_pager eq 'cat') {
1780                 $_pager = undef;
1781         }
1784 sub run_pager {
1785         return unless -t *STDOUT;
1786         pipe my $rfd, my $wfd or return;
1787         defined(my $pid = fork) or croak $!;
1788         if (!$pid) {
1789                 open STDOUT, '>&', $wfd or croak $!;
1790                 return;
1791         }
1792         open STDIN, '<&', $rfd or croak $!;
1793         $ENV{LESS} ||= 'FRSX';
1794         exec $_pager or croak "Can't run pager: $! ($_pager)\n";
1797 sub get_author_info {
1798         my ($dest, $author, $t, $tz) = @_;
1799         $author =~ s/(?:^\s*|\s*$)//g;
1800         $dest->{a_raw} = $author;
1801         my $_a;
1802         if ($_authors) {
1803                 $_a = $rusers{$author} || undef;
1804         }
1805         if (!$_a) {
1806                 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
1807         }
1808         $dest->{t} = $t;
1809         $dest->{tz} = $tz;
1810         $dest->{a} = $_a;
1811         # Date::Parse isn't in the standard Perl distro :(
1812         if ($tz =~ s/^\+//) {
1813                 $t += tz_to_s_offset($tz);
1814         } elsif ($tz =~ s/^\-//) {
1815                 $t -= tz_to_s_offset($tz);
1816         }
1817         $dest->{t_utc} = $t;
1820 sub process_commit {
1821         my ($c, $r_min, $r_max, $defer) = @_;
1822         if (defined $r_min && defined $r_max) {
1823                 if ($r_min == $c->{r} && $r_min == $r_max) {
1824                         show_commit($c);
1825                         return 0;
1826                 }
1827                 return 1 if $r_min == $r_max;
1828                 if ($r_min < $r_max) {
1829                         # we need to reverse the print order
1830                         return 0 if (defined $_limit && --$_limit < 0);
1831                         push @$defer, $c;
1832                         return 1;
1833                 }
1834                 if ($r_min != $r_max) {
1835                         return 1 if ($r_min < $c->{r});
1836                         return 1 if ($r_max > $c->{r});
1837                 }
1838         }
1839         return 0 if (defined $_limit && --$_limit < 0);
1840         show_commit($c);
1841         return 1;
1844 sub show_commit {
1845         my $c = shift;
1846         if ($_oneline) {
1847                 my $x = "\n";
1848                 if (my $l = $c->{l}) {
1849                         while ($l->[0] =~ /^\s*$/) { shift @$l }
1850                         $x = $l->[0];
1851                 }
1852                 $_l_fmt ||= 'A' . length($c->{r});
1853                 print 'r',pack($_l_fmt, $c->{r}),' | ';
1854                 print "$c->{c} | " if $_show_commit;
1855                 print $x;
1856         } else {
1857                 show_commit_normal($c);
1858         }
1861 sub show_commit_changed_paths {
1862         my ($c) = @_;
1863         return unless $c->{changed};
1864         print "Changed paths:\n", @{$c->{changed}};
1867 sub show_commit_normal {
1868         my ($c) = @_;
1869         print '-' x72, "\nr$c->{r} | ";
1870         print "$c->{c} | " if $_show_commit;
1871         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
1872                                  localtime($c->{t_utc})), ' | ';
1873         my $nr_line = 0;
1875         if (my $l = $c->{l}) {
1876                 while ($l->[$#$l] eq "\n" && $#$l > 0
1877                                           && $l->[($#$l - 1)] eq "\n") {
1878                         pop @$l;
1879                 }
1880                 $nr_line = scalar @$l;
1881                 if (!$nr_line) {
1882                         print "1 line\n\n\n";
1883                 } else {
1884                         if ($nr_line == 1) {
1885                                 $nr_line = '1 line';
1886                         } else {
1887                                 $nr_line .= ' lines';
1888                         }
1889                         print $nr_line, "\n";
1890                         show_commit_changed_paths($c);
1891                         print "\n";
1892                         print $_ foreach @$l;
1893                 }
1894         } else {
1895                 print "1 line\n";
1896                 show_commit_changed_paths($c);
1897                 print "\n";
1899         }
1900         foreach my $x (qw/raw diff/) {
1901                 if ($c->{$x}) {
1902                         print "\n";
1903                         print $_ foreach @{$c->{$x}}
1904                 }
1905         }
1908 package Git::SVN;
1909 use strict;
1910 use warnings;
1911 use vars qw/$default/;
1912 use Carp qw/croak/;
1913 use File::Path qw/mkpath/;
1914 use IPC::Open3;
1916 # properties that we do not log:
1917 my %SKIP_PROP;
1918 BEGIN {
1919         %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1920                                         svn:special svn:executable
1921                                         svn:entry:committed-rev
1922                                         svn:entry:last-author
1923                                         svn:entry:uuid
1924                                         svn:entry:committed-date/;
1927 sub init {
1928         my ($class, $id, $url) = @_;
1929         my $self = _new($class, $id);
1930         mkpath(["$self->{dir}/info"]);
1931         if (defined $url) {
1932                 $url =~ s!/+$!!; # strip trailing slash
1933                 ::s_to_file($url, "$self->{dir}/info/url");
1934         }
1935         $self->{url} = $url;
1936         open my $fh, '>>', $self->{db_path} or croak $!;
1937         close $fh or croak $!;
1938         $self;
1941 sub new {
1942         my ($class, $id) = @_;
1943         my $self = _new($class, $id);
1944         $self->{url} = ::file_to_s("$self->{dir}/info/url");
1945         $self;
1948 sub refname { "refs/remotes/$_[0]->{id}" }
1950 sub ra {
1951         my ($self) = shift;
1952         $self->{ra} ||= Git::SVN::Ra->new($self->{url});
1955 sub copy_remote_ref {
1956         my ($self) = @_;
1957         my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
1958         my $ref = $self->refname;
1959         if (command('ls-remote', $origin, $ref)) {
1960                 command_noisy('fetch', $origin, "$ref:$ref");
1961         } elsif ($::_cp_remote && !$::_upgrade) {
1962                 die "Unable to find remote reference: $ref on $origin\n";
1963         }
1966 sub traverse_ignore {
1967         my ($self, $fh, $path, $r) = @_;
1968         $path =~ s#^/+##g;
1969         my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
1970         my $p = $path;
1971         $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
1972         print $fh length $p ? "\n# $p\n" : "\n# /\n";
1973         if (my $s = $props->{'svn:ignore'}) {
1974                 $s =~ s/[\r\n]+/\n/g;
1975                 chomp $s;
1976                 if (length $p == 0) {
1977                         $s =~ s#\n#\n/$p#g;
1978                         print $fh "/$s\n";
1979                 } else {
1980                         $s =~ s#\n#\n/$p/#g;
1981                         print $fh "/$p/$s\n";
1982                 }
1983         }
1984         foreach (sort keys %$dirent) {
1985                 next if $dirent->{$_}->kind != $SVN::Node::dir;
1986                 $self->traverse_ignore($fh, "$path/$_", $r);
1987         }
1990 # returns the newest SVN revision number and newest commit SHA1
1991 sub last_rev_commit {
1992         my ($self) = @_;
1993         if (defined $self->{last_rev} && defined $self->{last_commit}) {
1994                 return ($self->{last_rev}, $self->{last_commit});
1995         }
1996         my $c = ::verify_ref($self->refname.'^0');
1997         if (defined $c && length $c) {
1998                 my $rev = (::cmt_metadata($c))[1];
1999                 if (defined $rev) {
2000                         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2001                         return ($rev, $c);
2002                 }
2003         }
2004         my $offset = -41; # from tail
2005         my $rl;
2006         open my $fh, '<', $self->{db_path} or
2007                                  croak "$self->{db_path} not readable: $!\n";
2008         seek $fh, $offset, 2;
2009         $rl = readline $fh;
2010         defined $rl or return (undef, undef);
2011         chomp $rl;
2012         while ($c ne $rl && tell $fh != 0) {
2013                 $offset -= 41;
2014                 seek $fh, $offset, 2;
2015                 $rl = readline $fh;
2016                 defined $rl or return (undef, undef);
2017                 chomp $rl;
2018         }
2019         my $rev = tell $fh;
2020         croak $! if ($rev < 0);
2021         $rev =  ($rev - 41) / 41;
2022         close $fh or croak $!;
2023         ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2024         return ($rev, $c);
2027 sub parse_revision {
2028         my ($self, $base) = @_;
2029         my $head = $self->ra->get_latest_revnum;
2030         if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2031                 return ($base + 1, $head) if (defined $base);
2032                 return (0, $head);
2033         }
2034         return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2035         return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2036         if ($::_revision =~ /^BASE:(\d+)$/) {
2037                 return ($base + 1, $1) if (defined $base);
2038                 return (0, $head);
2039         }
2040         return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2041         die "revision argument: $::_revision not understood by git-svn\n",
2042                 "Try using the command-line svn client instead\n";
2045 sub tmp_index_do {
2046         my ($self, $sub) = @_;
2047         my $old_index = $ENV{GIT_INDEX_FILE};
2048         $ENV{GIT_INDEX_FILE} = $self->{index};
2049         my @ret = &$sub;
2050         if ($old_index) {
2051                 $ENV{GIT_INDEX_FILE} = $old_index;
2052         } else {
2053                 delete $ENV{GIT_INDEX_FILE};
2054         }
2055         wantarray ? @ret : $ret[0];
2058 sub assert_index_clean {
2059         my ($self, $treeish) = @_;
2061         $self->tmp_index_do(sub {
2062                 command_noisy('read-tree', $treeish) unless -e $self->{index};
2063                 my $x = command_oneline('write-tree');
2064                 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2065                            /^tree ($::sha1)/mo);
2066                 if ($y ne $x) {
2067                         unlink $self->{index} or croak $!;
2068                         command_noisy('read-tree', $treeish);
2069                 }
2070                 $x = command_oneline('write-tree');
2071                 if ($y ne $x) {
2072                         ::fatal "trees ($treeish) $y != $x\n",
2073                                 "Something is seriously wrong...\n";
2074                 }
2075         });
2078 sub get_commit_parents {
2079         my ($self, $log_msg, @parents) = @_;
2080         my (%seen, @ret, @tmp);
2081         # commit parents can be conditionally bound to a particular
2082         # svn revision via: "svn_revno=commit_sha1", filter them out here:
2083         foreach my $p (@parents) {
2084                 next unless defined $p;
2085                 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
2086                         push @tmp, $2 if $1 == $log_msg->{revision};
2087                 } else {
2088                         push @tmp, $p if $p =~ /^$::sha1_short$/o;
2089                 }
2090         }
2091         if (my $cur = ::verify_ref($self->refname.'^0')) {
2092                 push @tmp, $cur;
2093         }
2094         push @tmp, $_ foreach (@{$log_msg->{parents}}, @tmp);
2095         while (my $p = shift @tmp) {
2096                 next if $seen{$p};
2097                 $seen{$p} = 1;
2098                 push @ret, $p;
2099                 # MAXPARENT is defined to 16 in commit-tree.c:
2100                 last if @ret >= 16;
2101         }
2102         if (@tmp) {
2103                 die "r$log_msg->{revision}: No room for parents:\n\t",
2104                     join("\n\t", @tmp), "\n";
2105         }
2106         @ret;
2109 sub check_upgrade_needed {
2110         my ($self) = @_;
2111         if (!-r $self->{db_path}) {
2112                 -d $self->{dir} or mkpath([$self->{dir}]);
2113                 open my $fh, '>>', $self->{db_path} or croak $!;
2114                 close $fh;
2115         }
2116         return unless ::verify_ref($self->{id}.'-HEAD^0');
2117         my $head = ::verify_ref($self->refname.'^0');
2118         if ($@ || !$head) {
2119                 ::fatal("Please run: $0 rebuild --upgrade\n");
2120         }
2123 sub do_git_commit {
2124         my ($self, $log_msg, @parents) = @_;
2125         if (my $c = $self->rev_db_get($log_msg->{revision})) {
2126                 croak "$log_msg->{revision} = $c already exists! ",
2127                       "Why are we refetching it?\n";
2128         }
2129         my ($name, $email) = ::author_name_email($log_msg->{author}, $self->ra);
2130         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
2131         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
2132         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
2134         my $tree = $log_msg->{tree};
2135         if (!defined $tree) {
2136                 $tree = $self->tmp_index_do(sub {
2137                                             command_oneline('write-tree') });
2138         }
2139         die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2141         my @exec = ('git-commit-tree', $tree);
2142         foreach ($self->get_commit_parents($log_msg, @parents)) {
2143                 push @exec, '-p', $_;
2144         }
2145         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2146                                                                    or croak $!;
2147         print $msg_fh $log_msg->{log} or croak $!;
2148         print $msg_fh "\ngit-svn-id: $self->{ra}->{url}\@$log_msg->{revision}",
2149                       " ", $self->ra->uuid,"\n" or croak $!;
2150         $msg_fh->flush == 0 or croak $!;
2151         close $msg_fh or croak $!;
2152         chomp(my $commit = do { local $/; <$out_fh> });
2153         close $out_fh or croak $!;
2154         waitpid $pid, 0;
2155         croak $? if $?;
2156         if ($commit !~ /^$::sha1$/o) {
2157                 die "Failed to commit, invalid sha1: $commit\n";
2158         }
2160         command_noisy('update-ref',$self->refname, $commit);
2161         $self->rev_db_set($log_msg->{revision}, $commit);
2163         $self->{last_rev} = $log_msg->{revision};
2164         $self->{last_commit} = $commit;
2165         print "r$log_msg->{revision} = $commit\n";
2166         return $commit;
2169 sub do_fetch {
2170         my ($self, $paths, $rev) = @_; #, $author, $date, $msg) = @_;
2171         my $ed = SVN::Git::Fetcher->new($self);
2172         my ($last_rev, @parents);
2173         if ($self->{last_commit}) {
2174                 $last_rev = $self->{last_rev};
2175                 $ed->{c} = $self->{last_commit};
2176                 @parents = ($self->{last_commit});
2177         } else {
2178                 $last_rev = $rev;
2179         }
2180         unless ($self->ra->do_update($last_rev, $rev, '', 1, $ed)) {
2181                 die "SVN connection failed somewhere...\n";
2182         }
2183         $self->make_log_entry($rev, \@parents, $ed);
2186 sub write_untracked {
2187         my ($self, $rev, $fh, $untracked) = @_;
2188         my $h;
2189         print $fh "r$rev\n" or croak $!;
2190         $h = $untracked->{empty};
2191         foreach (sort keys %$h) {
2192                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2193                 print $fh "  $act: ", uri_encode($_), "\n" or croak $!;
2194                 warn "W: $act: $_\n";
2195         }
2196         foreach my $t (qw/dir_prop file_prop/) {
2197                 $h = $untracked->{$t} or next;
2198                 foreach my $path (sort keys %$h) {
2199                         my $ppath = $path eq '' ? '.' : $path;
2200                         foreach my $prop (sort keys %{$h->{$path}}) {
2201                                 next if $SKIP{$prop};
2202                                 my $v = $h->{$path}->{$prop};
2203                                 if (defined $v) {
2204                                         print $fh "  +$t: ",
2205                                                   uri_encode($ppath), ' ',
2206                                                   uri_encode($prop), ' ',
2207                                                   uri_encode($v), "\n"
2208                                                   or croak $!;
2209                                 } else {
2210                                         print $fh "  -$t: ",
2211                                                   uri_encode($ppath), ' ',
2212                                                   uri_encode($prop), "\n"
2213                                                   or croak $!;
2214                                 }
2215                         }
2216                 }
2217         }
2218         foreach my $t (qw/absent_file absent_directory/) {
2219                 $h = $untracked->{$t} or next;
2220                 foreach my $parent (sort keys %$h) {
2221                         foreach my $path (sort @{$h->{$parent}}) {
2222                                 print $fh "  $t: ",
2223                                       uri_encode("$parent/$path"), "\n"
2224                                       or croak $!;
2225                                 warn "W: $t: $parent/$path ",
2226                                      "Insufficient permissions?\n";
2227                         }
2228                 }
2229         }
2232 sub make_log_entry {
2233         my ($self, $rev, $parents, $untracked) = @_;
2234         my $rp = $self->ra->rev_proplist($rev);
2235         my %log_entry = ( parents => $parents || [], revision => $rev,
2236                           revprops => $rp, log => '');
2237         open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2238         $self->write_untracked($rev, $un, $untracked);
2239         foreach (sort keys %$rp) {
2240                 my $v = $rp->{$_};
2241                 if (/^svn:(author|date|log)$/) {
2242                         $log_entry{$1} = $v;
2243                 } else {
2244                         print $un "  rev_prop: ", uri_encode($_), ' ',
2245                                   uri_encode($v), "\n";
2246                 }
2247         }
2248         close $un or croak $!;
2249         $log_entry{date} = parse_svn_date($log_entry{date});
2250         $log_entry{author} = check_author($log_entry{author});
2251         $log_entry{log} .= "\n";
2252         \%log_entry;
2255 sub fetch {
2256         my ($self, @parents) = @_;
2257         my ($last_rev, $last_commit) = $self->last_rev_commit;
2258         my ($base, $head) = $self->parse_revision($last_rev);
2259         return if ($base > $head);
2260         if (defined $last_commit) {
2261                 $self->assert_index_clean($last_commit);
2262         }
2263         my $inc = 1000;
2264         my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2265         my $err_handler = $SVN::Error::handler;
2266         $SVN::Error::handler = \&skip_unknown_revs;
2267         while (1) {
2268                 my @revs;
2269                 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
2270                         my ($paths, $rev, $author, $date, $msg) = @_;
2271                         push @revs, $rev });
2272                 foreach (@revs) {
2273                         my $log_entry = $self->do_fetch(undef, $_);
2274                         $self->do_git_commit($log_entry, @parents);
2275                 }
2276                 last if $max >= $head;
2277                 $min = $max + 1;
2278                 $max += $inc;
2279                 $max = $head if ($max > $head);
2280         }
2281         $SVN::Error::handler = $err_handler;
2284 sub set_tree_cb {
2285         my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2286         # TODO: enable and test optimized commits:
2287         if (0 && $rev == ($self->{last_rev} + 1)) {
2288                 $log_entry->{revision} = $rev;
2289                 $log_entry->{author} = $author;
2290                 $self->do_git_commit($log_entry, "$rev=$tree");
2291         } else {
2292                 $self->fetch("$rev=$tree");
2293         }
2296 sub set_tree {
2297         my ($self, $tree) = (shift, shift);
2298         my $log_entry = get_commit_entry($tree);
2299         unless ($self->{last_rev}) {
2300                 fatal("Must have an existing revision to commit\n");
2301         }
2302         my $pool = SVN::Pool->new;
2303         my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
2304                                          ra => $self->ra->dup,
2305                                          c => $tree,
2306                                          svn_path => $self->ra->{svn_path}
2307                                        },
2308                                        $self->ra->get_commit_editor(
2309                                          $log_entry->{log}, sub {
2310                                            $self->set_tree_cb($log_entry,
2311                                                               $tree, @_);
2312                                        }),
2313                                        $pool);
2314         my $mods = $ed->apply_diff($self->{last_commit}, $tree);
2315         if (@$mods == 0) {
2316                 print "No changes\nr$self->{last_rev} = $tree\n";
2317         }
2318         $pool->clear;
2321 sub skip_unknown_revs {
2322         my ($err) = @_;
2323         my $errno = $err->apr_err();
2324         # Maybe the branch we're tracking didn't
2325         # exist when the repo started, so it's
2326         # not an error if it doesn't, just continue
2327         #
2328         # Wonderfully consistent library, eh?
2329         # 160013 - svn:// and file://
2330         # 175002 - http(s)://
2331         # 175007 - http(s):// (this repo required authorization, too...)
2332         #   More codes may be discovered later...
2333         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2334                 return;
2335         }
2336         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2339 # rev_db:
2340 # Tie::File seems to be prone to offset errors if revisions get sparse,
2341 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2342 # one of my favorite modules is out :<  Next up would be one of the DBM
2343 # modules, but I'm not sure which is most portable...  So I'll just
2344 # go with something that's plain-text, but still capable of
2345 # being randomly accessed.  So here's my ultra-simple fixed-width
2346 # database.  All records are 40 characters + "\n", so it's easy to seek
2347 # to a revision: (41 * rev) is the byte offset.
2348 # A record of 40 0s denotes an empty revision.
2349 # And yes, it's still pretty fast (faster than Tie::File).
2351 sub rev_db_set {
2352         my ($self, $rev, $commit) = @_;
2353         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2354         open my $fh, '+<', $self->{db_path} or croak $!;
2355         my $offset = $rev * 41;
2356         # assume that append is the common case:
2357         seek $fh, 0, 2 or croak $!;
2358         my $pos = tell $fh;
2359         if ($pos < $offset) {
2360                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
2361                   or croak $!;
2362         }
2363         seek $fh, $offset, 0 or croak $!;
2364         print $fh $commit,"\n" or croak $!;
2365         close $fh or croak $!;
2368 sub rev_db_get {
2369         my ($self, $rev) = @_;
2370         my $ret;
2371         my $offset = $rev * 41;
2372         open my $fh, '<', $self->{db_path} or croak $!;
2373         if (seek $fh, $offset, 0) {
2374                 $ret = readline $fh;
2375                 if (defined $ret) {
2376                         chomp $ret;
2377                         $ret = undef if ($ret =~ /^0{40}$/);
2378                 }
2379         }
2380         close $fh or croak $!;
2381         $ret;
2384 sub _new {
2385         my ($class, $id) = @_;
2386         $id ||= $Git::SVN::default;
2387         my $dir = "$ENV{GIT_DIR}/svn/$id";
2388         bless { id => $id, dir => $dir, index => "$dir/index",
2389                 db_path => "$dir/.rev_db" }, $class;
2393 package Git::SVN::Prompt;
2394 use strict;
2395 use warnings;
2396 require SVN::Core;
2397 use vars qw/$_no_auth_cache $_username/;
2399 sub simple {
2400         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2401         $may_save = undef if $_no_auth_cache;
2402         $default_username = $_username if defined $_username;
2403         if (defined $default_username && length $default_username) {
2404                 if (defined $realm && length $realm) {
2405                         print STDERR "Authentication realm: $realm\n";
2406                         STDERR->flush;
2407                 }
2408                 $cred->username($default_username);
2409         } else {
2410                 username($cred, $realm, $may_save, $pool);
2411         }
2412         $cred->password(_read_password("Password for '" .
2413                                        $cred->username . "': ", $realm));
2414         $cred->may_save($may_save);
2415         $SVN::_Core::SVN_NO_ERROR;
2418 sub ssl_server_trust {
2419         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2420         $may_save = undef if $_no_auth_cache;
2421         print STDERR "Error validating server certificate for '$realm':\n";
2422         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2423                 print STDERR " - The certificate is not issued by a trusted ",
2424                       "authority. Use the\n",
2425                       "   fingerprint to validate the certificate manually!\n";
2426         }
2427         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2428                 print STDERR " - The certificate hostname does not match.\n";
2429         }
2430         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2431                 print STDERR " - The certificate is not yet valid.\n";
2432         }
2433         if ($failures & $SVN::Auth::SSL::EXPIRED) {
2434                 print STDERR " - The certificate has expired.\n";
2435         }
2436         if ($failures & $SVN::Auth::SSL::OTHER) {
2437                 print STDERR " - The certificate has an unknown error.\n";
2438         }
2439         printf STDERR
2440                 "Certificate information:\n".
2441                 " - Hostname: %s\n".
2442                 " - Valid: from %s until %s\n".
2443                 " - Issuer: %s\n".
2444                 " - Fingerprint: %s\n",
2445                 map $cert_info->$_, qw(hostname valid_from valid_until
2446                                        issuer_dname fingerprint);
2447         my $choice;
2448 prompt:
2449         print STDERR $may_save ?
2450               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2451               "(R)eject or accept (t)emporarily? ";
2452         STDERR->flush;
2453         $choice = lc(substr(<STDIN> || 'R', 0, 1));
2454         if ($choice =~ /^t$/i) {
2455                 $cred->may_save(undef);
2456         } elsif ($choice =~ /^r$/i) {
2457                 return -1;
2458         } elsif ($may_save && $choice =~ /^p$/i) {
2459                 $cred->may_save($may_save);
2460         } else {
2461                 goto prompt;
2462         }
2463         $cred->accepted_failures($failures);
2464         $SVN::_Core::SVN_NO_ERROR;
2467 sub ssl_client_cert {
2468         my ($cred, $realm, $may_save, $pool) = @_;
2469         $may_save = undef if $_no_auth_cache;
2470         print STDERR "Client certificate filename: ";
2471         STDERR->flush;
2472         chomp(my $filename = <STDIN>);
2473         $cred->cert_file($filename);
2474         $cred->may_save($may_save);
2475         $SVN::_Core::SVN_NO_ERROR;
2478 sub ssl_client_cert_pw {
2479         my ($cred, $realm, $may_save, $pool) = @_;
2480         $may_save = undef if $_no_auth_cache;
2481         $cred->password(_read_password("Password: ", $realm));
2482         $cred->may_save($may_save);
2483         $SVN::_Core::SVN_NO_ERROR;
2486 sub username {
2487         my ($cred, $realm, $may_save, $pool) = @_;
2488         $may_save = undef if $_no_auth_cache;
2489         if (defined $realm && length $realm) {
2490                 print STDERR "Authentication realm: $realm\n";
2491         }
2492         my $username;
2493         if (defined $_username) {
2494                 $username = $_username;
2495         } else {
2496                 print STDERR "Username: ";
2497                 STDERR->flush;
2498                 chomp($username = <STDIN>);
2499         }
2500         $cred->username($username);
2501         $cred->may_save($may_save);
2502         $SVN::_Core::SVN_NO_ERROR;
2505 sub _read_password {
2506         my ($prompt, $realm) = @_;
2507         print STDERR $prompt;
2508         STDERR->flush;
2509         require Term::ReadKey;
2510         Term::ReadKey::ReadMode('noecho');
2511         my $password = '';
2512         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2513                 last if $key =~ /[\012\015]/; # \n\r
2514                 $password .= $key;
2515         }
2516         Term::ReadKey::ReadMode('restore');
2517         print STDERR "\n";
2518         STDERR->flush;
2519         $password;
2522 package main;
2524 sub uri_encode {
2525         my ($f) = @_;
2526         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2527         $f
2530 sub uri_decode {
2531         my ($f) = @_;
2532         $f =~ tr/+/ /;
2533         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2534         $f
2537 sub libsvn_log_entry {
2538         my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2539         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2540                                          (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2541                                 or die "Unable to parse date: $date\n";
2542         if (defined $author && length $author > 0 &&
2543             defined $_authors && ! defined $users{$author}) {
2544                 die "Author: $author not defined in $_authors file\n";
2545         }
2546         $msg = '' if ($rev == 0 && !defined $msg);
2548         open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2549         my $h;
2550         print $un "r$rev\n" or croak $!;
2551         $h = $untracked->{empty};
2552         foreach (sort keys %$h) {
2553                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2554                 print $un "  $act: ", uri_encode($_), "\n" or croak $!;
2555                 warn "W: $act: $_\n";
2556         }
2557         foreach my $t (qw/dir_prop file_prop/) {
2558                 $h = $untracked->{$t} or next;
2559                 foreach my $path (sort keys %$h) {
2560                         my $ppath = $path eq '' ? '.' : $path;
2561                         foreach my $prop (sort keys %{$h->{$path}}) {
2562                                 next if $SKIP{$prop};
2563                                 my $v = $h->{$path}->{$prop};
2564                                 if (defined $v) {
2565                                         print $un "  +$t: ",
2566                                                   uri_encode($ppath), ' ',
2567                                                   uri_encode($prop), ' ',
2568                                                   uri_encode($v), "\n"
2569                                                   or croak $!;
2570                                 } else {
2571                                         print $un "  -$t: ",
2572                                                   uri_encode($ppath), ' ',
2573                                                   uri_encode($prop), "\n"
2574                                                   or croak $!;
2575                                 }
2576                         }
2577                 }
2578         }
2579         foreach my $t (qw/absent_file absent_directory/) {
2580                 $h = $untracked->{$t} or next;
2581                 foreach my $parent (sort keys %$h) {
2582                         foreach my $path (sort @{$h->{$parent}}) {
2583                                 print $un "  $t: ",
2584                                       uri_encode("$parent/$path"), "\n"
2585                                       or croak $!;
2586                                 warn "W: $t: $parent/$path ",
2587                                      "Insufficient permissions?\n";
2588                         }
2589                 }
2590         }
2592         # revprops (make this optional? it's an extra network trip...)
2593         my $rp = $SVN->rev_proplist($rev);
2594         foreach (sort keys %$rp) {
2595                 next if /^svn:(?:author|date|log)$/;
2596                 print $un "  rev_prop: ", uri_encode($_), ' ',
2597                           uri_encode($rp->{$_}), "\n";
2598         }
2599         close $un or croak $!;
2601         { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2602           author => $author, msg => $msg."\n", parents => $parents || [],
2603           revprops => $rp }
2606 sub libsvn_fetch {
2607         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2608         my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2609         my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2610         unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2611                 die "SVN connection failed somewhere...\n";
2612         }
2613         libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2616 sub svn_grab_base_rev {
2617         my $c = eval { command_oneline([qw/rev-parse --verify/,
2618                                         "refs/remotes/$GIT_SVN^0"],
2619                                         { STDERR => 0 }) };
2620         if (defined $c && length $c) {
2621                 my ($url, $rev, $uuid) = cmt_metadata($c);
2622                 return ($rev, $c) if defined $rev;
2623         }
2624         if ($_no_metadata) {
2625                 my $offset = -41; # from tail
2626                 my $rl;
2627                 open my $fh, '<', $REVDB or
2628                         die "--no-metadata specified and $REVDB not readable\n";
2629                 seek $fh, $offset, 2;
2630                 $rl = readline $fh;
2631                 defined $rl or return (undef, undef);
2632                 chomp $rl;
2633                 while ($c ne $rl && tell $fh != 0) {
2634                         $offset -= 41;
2635                         seek $fh, $offset, 2;
2636                         $rl = readline $fh;
2637                         defined $rl or return (undef, undef);
2638                         chomp $rl;
2639                 }
2640                 my $rev = tell $fh;
2641                 croak $! if ($rev < -1);
2642                 $rev =  ($rev - 41) / 41;
2643                 close $fh or croak $!;
2644                 return ($rev, $c);
2645         }
2646         return (undef, undef);
2649 sub libsvn_parse_revision {
2650         my $base = shift;
2651         my $head = $SVN->get_latest_revnum();
2652         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2653                 return ($base + 1, $head) if (defined $base);
2654                 return (0, $head);
2655         }
2656         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2657         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2658         if ($_revision =~ /^BASE:(\d+)$/) {
2659                 return ($base + 1, $1) if (defined $base);
2660                 return (0, $head);
2661         }
2662         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2663         die "revision argument: $_revision not understood by git-svn\n",
2664                 "Try using the command-line svn client instead\n";
2667 sub libsvn_traverse_ignore {
2668         my ($fh, $path, $r) = @_;
2669         $path =~ s#^/+##g;
2670         my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2671         my $p = $path;
2672         $p =~ s#^\Q$SVN->{svn_path}\E/##;
2673         print $fh length $p ? "\n# $p\n" : "\n# /\n";
2674         if (my $s = $props->{'svn:ignore'}) {
2675                 $s =~ s/[\r\n]+/\n/g;
2676                 chomp $s;
2677                 if (length $p == 0) {
2678                         $s =~ s#\n#\n/$p#g;
2679                         print $fh "/$s\n";
2680                 } else {
2681                         $s =~ s#\n#\n/$p/#g;
2682                         print $fh "/$p/$s\n";
2683                 }
2684         }
2685         foreach (sort keys %$dirent) {
2686                 next if $dirent->{$_}->kind != $SVN::Node::dir;
2687                 libsvn_traverse_ignore($fh, "$path/$_", $r);
2688         }
2691 sub revisions_eq {
2692         my ($path, $r0, $r1) = @_;
2693         return 1 if $r0 == $r1;
2694         my $nr = 0;
2695         # should be OK to use Pool here (r1 - r0) should be small
2696         $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2697         return 0 if ($nr > 1);
2698         return 1;
2701 sub libsvn_find_parent_branch {
2702         my ($paths, $rev, $author, $date, $msg) = @_;
2703         my $svn_path = '/'.$SVN->{svn_path};
2705         # look for a parent from another branch:
2706         my $i = $paths->{$svn_path} or return;
2707         my $branch_from = $i->copyfrom_path or return;
2708         my $r = $i->copyfrom_rev;
2709         print STDERR  "Found possible branch point: ",
2710                                 "$branch_from => $svn_path, $r\n";
2711         $branch_from =~ s#^/##;
2712         my $l_map = {};
2713         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2714         my $url = $SVN->{repos_root};
2715         defined $l_map->{$url} or return;
2716         my $id = $l_map->{$url}->{$branch_from};
2717         if (!defined $id && $_follow_parent) {
2718                 print STDERR "Following parent: $branch_from\@$r\n";
2719                 # auto create a new branch and follow it
2720                 $id = basename($branch_from);
2721                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2722                 while (-r "$GIT_DIR/svn/$id") {
2723                         # just grow a tail if we're not unique enough :x
2724                         $id .= '-';
2725                 }
2726         }
2727         return unless defined $id;
2729         my ($r0, $parent) = find_rev_before($r,$id,1);
2730         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2731                 defined(my $pid = fork) or croak $!;
2732                 if (!$pid) {
2733                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2734                         init_vars();
2735                         $SVN_URL = "$url/$branch_from";
2736                         $SVN = undef;
2737                         setup_git_svn();
2738                         # we can't assume SVN_URL exists at r+1:
2739                         $_revision = "0:$r";
2740                         fetch_lib();
2741                         exit 0;
2742                 }
2743                 waitpid $pid, 0;
2744                 croak $? if $?;
2745                 ($r0, $parent) = find_rev_before($r,$id,1);
2746         }
2747         return unless (defined $r0 && defined $parent);
2748         if (revisions_eq($branch_from, $r0, $r)) {
2749                 unlink $GIT_SVN_INDEX;
2750                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2751                 command_noisy('read-tree', $parent);
2752                 unless ($SVN->can_do_switch) {
2753                         return _libsvn_new_tree($paths, $rev, $author, $date,
2754                                                 $msg, [$parent]);
2755                 }
2756                 # do_switch works with svn/trunk >= r22312, but that is not
2757                 # included with SVN 1.4.2 (the latest version at the moment),
2758                 # so we can't rely on it.
2759                 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2760                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2761                 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2762                                    die "SVN connection failed somewhere...\n";
2763                 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2764         }
2765         print STDERR "Nope, branch point not imported or unknown\n";
2766         return undef;
2769 sub libsvn_new_tree {
2770         if (my $log_entry = libsvn_find_parent_branch(@_)) {
2771                 return $log_entry;
2772         }
2773         my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2774         _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2777 sub _libsvn_new_tree {
2778         my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2779         my $ed = SVN::Git::Fetcher->new({q => $_q});
2780         unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2781                 die "SVN connection failed somewhere...\n";
2782         }
2783         libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2786 sub find_graft_path_commit {
2787         my ($tree_paths, $p1, $r1) = @_;
2788         foreach my $x (keys %$tree_paths) {
2789                 next unless ($p1 =~ /^\Q$x\E/);
2790                 my $i = $tree_paths->{$x};
2791                 my ($r0, $parent) = find_rev_before($r1,$i,1);
2792                 return $parent if (defined $r0 && $r0 == $r1);
2793                 print STDERR "r$r1 of $i not imported\n";
2794                 next;
2795         }
2796         return undef;
2799 sub find_graft_path_parents {
2800         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2801         foreach my $x (keys %$tree_paths) {
2802                 next unless ($p0 =~ /^\Q$x\E/);
2803                 my $i = $tree_paths->{$x};
2804                 my ($r, $parent) = find_rev_before($r0, $i, 1);
2805                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2806                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2807                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2808                         next if ($url_a && $url_b && $url_a eq $url_b &&
2809                                                         $uuid_b eq $uuid_a);
2810                         $grafts->{$c}->{$parent} = 1;
2811                 }
2812         }
2815 sub libsvn_graft_file_copies {
2816         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2817         foreach (keys %$paths) {
2818                 my $i = $paths->{$_};
2819                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2820                                         $i->copyfrom_rev);
2821                 next unless (defined $p0 && defined $r0);
2823                 my $p1 = $_;
2824                 $p1 =~ s#^/##;
2825                 $p0 =~ s#^/##;
2826                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2827                 next unless $c;
2828                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2829         }
2832 sub set_index {
2833         my $old = $ENV{GIT_INDEX_FILE};
2834         $ENV{GIT_INDEX_FILE} = shift;
2835         return $old;
2838 sub restore_index {
2839         my ($old) = @_;
2840         if (defined $old) {
2841                 $ENV{GIT_INDEX_FILE} = $old;
2842         } else {
2843                 delete $ENV{GIT_INDEX_FILE};
2844         }
2847 sub libsvn_commit_cb {
2848         my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2849         if ($_optimize_commits && $rev == ($r_last + 1)) {
2850                 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2851                 $log->{tree} = get_tree_from_treeish($c);
2852                 my $cmt = git_commit($log, $cmt_last, $c);
2853                 my @diff = command('diff-tree', $cmt, $c);
2854                 if (@diff) {
2855                         print STDERR "Trees differ: $cmt $c\n",
2856                                         join('',@diff),"\n";
2857                         exit 1;
2858                 }
2859         } else {
2860                 fetch("$rev=$c");
2861         }
2864 sub libsvn_skip_unknown_revs {
2865         my $err = shift;
2866         my $errno = $err->apr_err();
2867         # Maybe the branch we're tracking didn't
2868         # exist when the repo started, so it's
2869         # not an error if it doesn't, just continue
2870         #
2871         # Wonderfully consistent library, eh?
2872         # 160013 - svn:// and file://
2873         # 175002 - http(s)://
2874         # 175007 - http(s):// (this repo required authorization, too...)
2875         #   More codes may be discovered later...
2876         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2877                 return;
2878         }
2879         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2880 };
2882 # Tie::File seems to be prone to offset errors if revisions get sparse,
2883 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2884 # one of my favorite modules is out :<  Next up would be one of the DBM
2885 # modules, but I'm not sure which is most portable...  So I'll just
2886 # go with something that's plain-text, but still capable of
2887 # being randomly accessed.  So here's my ultra-simple fixed-width
2888 # database.  All records are 40 characters + "\n", so it's easy to seek
2889 # to a revision: (41 * rev) is the byte offset.
2890 # A record of 40 0s denotes an empty revision.
2891 # And yes, it's still pretty fast (faster than Tie::File).
2892 sub revdb_set {
2893         my ($file, $rev, $commit) = @_;
2894         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2895         open my $fh, '+<', $file or croak $!;
2896         my $offset = $rev * 41;
2897         # assume that append is the common case:
2898         seek $fh, 0, 2 or croak $!;
2899         my $pos = tell $fh;
2900         if ($pos < $offset) {
2901                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2902         }
2903         seek $fh, $offset, 0 or croak $!;
2904         print $fh $commit,"\n";
2905         close $fh or croak $!;
2908 sub revdb_get {
2909         my ($file, $rev) = @_;
2910         my $ret;
2911         my $offset = $rev * 41;
2912         open my $fh, '<', $file or croak $!;
2913         seek $fh, $offset, 0;
2914         if (tell $fh == $offset) {
2915                 $ret = readline $fh;
2916                 if (defined $ret) {
2917                         chomp $ret;
2918                         $ret = undef if ($ret =~ /^0{40}$/);
2919                 }
2920         }
2921         close $fh or croak $!;
2922         return $ret;
2925 sub copy_remote_ref {
2926         my $origin = $_cp_remote ? $_cp_remote : 'origin';
2927         my $ref = "refs/remotes/$GIT_SVN";
2928         if (command('ls-remote', $origin, $ref)) {
2929                 command_noisy('fetch', $origin, "$ref:$ref");
2930         } elsif ($_cp_remote && !$_upgrade) {
2931                 die "Unable to find remote reference: ",
2932                                 "refs/remotes/$GIT_SVN on $origin\n";
2933         }
2937         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2938                                 $SVN::Node::dir.$SVN::Node::unknown.
2939                                 $SVN::Node::none.$SVN::Node::file.
2940                                 $SVN::Node::dir.$SVN::Node::unknown.
2941                                 $SVN::Auth::SSL::CNMISMATCH.
2942                                 $SVN::Auth::SSL::NOTYETVALID.
2943                                 $SVN::Auth::SSL::EXPIRED.
2944                                 $SVN::Auth::SSL::UNKNOWNCA.
2945                                 $SVN::Auth::SSL::OTHER;
2948 package SVN::Git::Fetcher;
2949 use vars qw/@ISA/;
2950 use strict;
2951 use warnings;
2952 use Carp qw/croak/;
2953 use IO::File qw//;
2955 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2956 sub new {
2957         my ($class, $git_svn) = @_;
2958         my $self = SVN::Delta::Editor->new;
2959         bless $self, $class;
2960         $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2961         $self->{q} = $git_svn->{q};
2962         $self->{empty} = {};
2963         $self->{dir_prop} = {};
2964         $self->{file_prop} = {};
2965         $self->{absent_dir} = {};
2966         $self->{absent_file} = {};
2967         ($self->{gui}, $self->{ctx}) = command_input_pipe(
2968                                              qw/update-index -z --index-info/);
2969         require Digest::MD5;
2970         $self;
2973 sub open_root {
2974         { path => '' };
2977 sub open_directory {
2978         my ($self, $path, $pb, $rev) = @_;
2979         { path => $path };
2982 sub delete_entry {
2983         my ($self, $path, $rev, $pb) = @_;
2984         my $gui = $self->{gui};
2986         # remove entire directories.
2987         if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2988                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2989                                                      -r --name-only -z/,
2990                                                      $self->{c}, '--', $path);
2991                 local $/ = "\0";
2992                 while (<$ls>) {
2993                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2994                         print "\tD\t$_\n" unless $self->{q};
2995                 }
2996                 print "\tD\t$path/\n" unless $self->{q};
2997                 command_close_pipe($ls, $ctx);
2998                 $self->{empty}->{$path} = 0
2999         } else {
3000                 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
3001                 print "\tD\t$path\n" unless $self->{q};
3002         }
3003         undef;
3006 sub open_file {
3007         my ($self, $path, $pb, $rev) = @_;
3008         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
3009                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3010         unless (defined $mode && defined $blob) {
3011                 die "$path was not found in commit $self->{c} (r$rev)\n";
3012         }
3013         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3014           pool => SVN::Pool->new, action => 'M' };
3017 sub add_file {
3018         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3019         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3020         delete $self->{empty}->{$dir};
3021         { path => $path, mode_a => 100644, mode_b => 100644,
3022           pool => SVN::Pool->new, action => 'A' };
3025 sub add_directory {
3026         my ($self, $path, $cp_path, $cp_rev) = @_;
3027         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3028         delete $self->{empty}->{$dir};
3029         $self->{empty}->{$path} = 1;
3030         { path => $path };
3033 sub change_dir_prop {
3034         my ($self, $db, $prop, $value) = @_;
3035         $self->{dir_prop}->{$db->{path}} ||= {};
3036         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3037         undef;
3040 sub absent_directory {
3041         my ($self, $path, $pb) = @_;
3042         $self->{absent_dir}->{$pb->{path}} ||= [];
3043         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3044         undef;
3047 sub absent_file {
3048         my ($self, $path, $pb) = @_;
3049         $self->{absent_file}->{$pb->{path}} ||= [];
3050         push @{$self->{absent_file}->{$pb->{path}}}, $path;
3051         undef;
3054 sub change_file_prop {
3055         my ($self, $fb, $prop, $value) = @_;
3056         if ($prop eq 'svn:executable') {
3057                 if ($fb->{mode_b} != 120000) {
3058                         $fb->{mode_b} = defined $value ? 100755 : 100644;
3059                 }
3060         } elsif ($prop eq 'svn:special') {
3061                 $fb->{mode_b} = defined $value ? 120000 : 100644;
3062         } else {
3063                 $self->{file_prop}->{$fb->{path}} ||= {};
3064                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3065         }
3066         undef;
3069 sub apply_textdelta {
3070         my ($self, $fb, $exp) = @_;
3071         my $fh = IO::File->new_tmpfile;
3072         $fh->autoflush(1);
3073         # $fh gets auto-closed() by SVN::TxDelta::apply(),
3074         # (but $base does not,) so dup() it for reading in close_file
3075         open my $dup, '<&', $fh or croak $!;
3076         my $base = IO::File->new_tmpfile;
3077         $base->autoflush(1);
3078         if ($fb->{blob}) {
3079                 defined (my $pid = fork) or croak $!;
3080                 if (!$pid) {
3081                         open STDOUT, '>&', $base or croak $!;
3082                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
3083                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
3084                 }
3085                 waitpid $pid, 0;
3086                 croak $? if $?;
3088                 if (defined $exp) {
3089                         seek $base, 0, 0 or croak $!;
3090                         my $md5 = Digest::MD5->new;
3091                         $md5->addfile($base);
3092                         my $got = $md5->hexdigest;
3093                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3094                             "expected: $exp\n",
3095                             "     got: $got\n" if ($got ne $exp);
3096                 }
3097         }
3098         seek $base, 0, 0 or croak $!;
3099         $fb->{fh} = $dup;
3100         $fb->{base} = $base;
3101         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3104 sub close_file {
3105         my ($self, $fb, $exp) = @_;
3106         my $hash;
3107         my $path = $fb->{path};
3108         if (my $fh = $fb->{fh}) {
3109                 seek($fh, 0, 0) or croak $!;
3110                 my $md5 = Digest::MD5->new;
3111                 $md5->addfile($fh);
3112                 my $got = $md5->hexdigest;
3113                 die "Checksum mismatch: $path\n",
3114                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
3115                 seek($fh, 0, 0) or croak $!;
3116                 if ($fb->{mode_b} == 120000) {
3117                         read($fh, my $buf, 5) == 5 or croak $!;
3118                         $buf eq 'link ' or die "$path has mode 120000",
3119                                                "but is not a link\n";
3120                 }
3121                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3122                 if (!$pid) {
3123                         open STDIN, '<&', $fh or croak $!;
3124                         exec qw/git-hash-object -w --stdin/ or croak $!;
3125                 }
3126                 chomp($hash = do { local $/; <$out> });
3127                 close $out or croak $!;
3128                 close $fh or croak $!;
3129                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3130                 close $fb->{base} or croak $!;
3131         } else {
3132                 $hash = $fb->{blob} or die "no blob information\n";
3133         }
3134         $fb->{pool}->clear;
3135         my $gui = $self->{gui};
3136         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
3137         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
3138         undef;
3141 sub abort_edit {
3142         my $self = shift;
3143         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
3144         $self->SUPER::abort_edit(@_);
3147 sub close_edit {
3148         my $self = shift;
3149         command_close_pipe($self->{gui}, $self->{ctx});
3150         $self->{git_commit_ok} = 1;
3151         $self->SUPER::close_edit(@_);
3154 package SVN::Git::Editor;
3155 use vars qw/@ISA/;
3156 use strict;
3157 use warnings;
3158 use Carp qw/croak/;
3159 use IO::File;
3161 sub new {
3162         my $class = shift;
3163         my $git_svn = shift;
3164         my $self = SVN::Delta::Editor->new(@_);
3165         bless $self, $class;
3166         foreach (qw/svn_path c r ra /) {
3167                 die "$_ required!\n" unless (defined $git_svn->{$_});
3168                 $self->{$_} = $git_svn->{$_};
3169         }
3170         $self->{pool} = SVN::Pool->new;
3171         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3172         $self->{rm} = { };
3173         require Digest::MD5;
3174         return $self;
3177 sub split_path {
3178         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3181 sub repo_path {
3182         (defined $_[1] && length $_[1]) ? $_[1] : ''
3185 sub url_path {
3186         my ($self, $path) = @_;
3187         $self->{ra}->{url} . '/' . $self->repo_path($path);
3190 sub rmdirs {
3191         my ($self, $q) = @_;
3192         my $rm = $self->{rm};
3193         delete $rm->{''}; # we never delete the url we're tracking
3194         return unless %$rm;
3196         foreach (keys %$rm) {
3197                 my @d = split m#/#, $_;
3198                 my $c = shift @d;
3199                 $rm->{$c} = 1;
3200                 while (@d) {
3201                         $c .= '/' . shift @d;
3202                         $rm->{$c} = 1;
3203                 }
3204         }
3205         delete $rm->{$self->{svn_path}};
3206         delete $rm->{''}; # we never delete the url we're tracking
3207         return unless %$rm;
3209         my ($fh, $ctx) = command_output_pipe(
3210                                    qw/ls-tree --name-only -r -z/, $self->{c});
3211         local $/ = "\0";
3212         while (<$fh>) {
3213                 chomp;
3214                 my @dn = split m#/#, $_;
3215                 while (pop @dn) {
3216                         delete $rm->{join '/', @dn};
3217                 }
3218                 unless (%$rm) {
3219                         close $fh;
3220                         return;
3221                 }
3222         }
3223         command_close_pipe($fh, $ctx);
3225         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3226         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3227                 $self->close_directory($bat->{$d}, $p);
3228                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3229                 print "\tD+\t$d/\n" unless $q;
3230                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3231                 delete $bat->{$d};
3232         }
3235 sub open_or_add_dir {
3236         my ($self, $full_path, $baton) = @_;
3237         my $t = $self->{ra}->check_path($full_path, $self->{r});
3238         if ($t == $SVN::Node::none) {
3239                 return $self->add_directory($full_path, $baton,
3240                                                 undef, -1, $self->{pool});
3241         } elsif ($t == $SVN::Node::dir) {
3242                 return $self->open_directory($full_path, $baton,
3243                                                 $self->{r}, $self->{pool});
3244         }
3245         print STDERR "$full_path already exists in repository at ",
3246                 "r$self->{r} and it is not a directory (",
3247                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3248         exit 1;
3251 sub ensure_path {
3252         my ($self, $path) = @_;
3253         my $bat = $self->{bat};
3254         $path = $self->repo_path($path);
3255         return $bat->{''} unless (length $path);
3256         my @p = split m#/+#, $path;
3257         my $c = shift @p;
3258         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3259         while (@p) {
3260                 my $c0 = $c;
3261                 $c .= '/' . shift @p;
3262                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3263         }
3264         return $bat->{$c};
3267 sub A {
3268         my ($self, $m, $q) = @_;
3269         my ($dir, $file) = split_path($m->{file_b});
3270         my $pbat = $self->ensure_path($dir);
3271         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3272                                         undef, -1);
3273         print "\tA\t$m->{file_b}\n" unless $q;
3274         $self->chg_file($fbat, $m);
3275         $self->close_file($fbat,undef,$self->{pool});
3278 sub C {
3279         my ($self, $m, $q) = @_;
3280         my ($dir, $file) = split_path($m->{file_b});
3281         my $pbat = $self->ensure_path($dir);
3282         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3283                                 $self->url_path($m->{file_a}), $self->{r});
3284         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
3285         $self->chg_file($fbat, $m);
3286         $self->close_file($fbat,undef,$self->{pool});
3289 sub delete_entry {
3290         my ($self, $path, $pbat) = @_;
3291         my $rpath = $self->repo_path($path);
3292         my ($dir, $file) = split_path($rpath);
3293         $self->{rm}->{$dir} = 1;
3294         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3297 sub R {
3298         my ($self, $m, $q) = @_;
3299         my ($dir, $file) = split_path($m->{file_b});
3300         my $pbat = $self->ensure_path($dir);
3301         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3302                                 $self->url_path($m->{file_a}), $self->{r});
3303         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
3304         $self->chg_file($fbat, $m);
3305         $self->close_file($fbat,undef,$self->{pool});
3307         ($dir, $file) = split_path($m->{file_a});
3308         $pbat = $self->ensure_path($dir);
3309         $self->delete_entry($m->{file_a}, $pbat);
3312 sub M {
3313         my ($self, $m, $q) = @_;
3314         my ($dir, $file) = split_path($m->{file_b});
3315         my $pbat = $self->ensure_path($dir);
3316         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3317                                 $pbat,$self->{r},$self->{pool});
3318         print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
3319         $self->chg_file($fbat, $m);
3320         $self->close_file($fbat,undef,$self->{pool});
3323 sub T { shift->M(@_) }
3325 sub change_file_prop {
3326         my ($self, $fbat, $pname, $pval) = @_;
3327         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3330 sub chg_file {
3331         my ($self, $fbat, $m) = @_;
3332         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3333                 $self->change_file_prop($fbat,'svn:executable','*');
3334         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3335                 $self->change_file_prop($fbat,'svn:executable',undef);
3336         }
3337         my $fh = IO::File->new_tmpfile or croak $!;
3338         if ($m->{mode_b} =~ /^120/) {
3339                 print $fh 'link ' or croak $!;
3340                 $self->change_file_prop($fbat,'svn:special','*');
3341         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3342                 $self->change_file_prop($fbat,'svn:special',undef);
3343         }
3344         defined(my $pid = fork) or croak $!;
3345         if (!$pid) {
3346                 open STDOUT, '>&', $fh or croak $!;
3347                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3348         }
3349         waitpid $pid, 0;
3350         croak $? if $?;
3351         $fh->flush == 0 or croak $!;
3352         seek $fh, 0, 0 or croak $!;
3354         my $md5 = Digest::MD5->new;
3355         $md5->addfile($fh) or croak $!;
3356         seek $fh, 0, 0 or croak $!;
3358         my $exp = $md5->hexdigest;
3359         my $pool = SVN::Pool->new;
3360         my $atd = $self->apply_textdelta($fbat, undef, $pool);
3361         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3362         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3363         $pool->clear;
3365         close $fh or croak $!;
3368 sub D {
3369         my ($self, $m, $q) = @_;
3370         my ($dir, $file) = split_path($m->{file_b});
3371         my $pbat = $self->ensure_path($dir);
3372         print "\tD\t$m->{file_b}\n" unless $q;
3373         $self->delete_entry($m->{file_b}, $pbat);
3376 sub close_edit {
3377         my ($self) = @_;
3378         my ($p,$bat) = ($self->{pool}, $self->{bat});
3379         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3380                 $self->close_directory($bat->{$_}, $p);
3381         }
3382         $self->SUPER::close_edit($p);
3383         $p->clear;
3386 sub abort_edit {
3387         my ($self) = @_;
3388         $self->SUPER::abort_edit($self->{pool});
3389         $self->{pool}->clear;
3392 package Git::SVN::Ra;
3393 use vars qw/@ISA $config_dir/;
3394 use strict;
3395 use warnings;
3396 my ($can_do_switch);
3398 BEGIN {
3399         # enforce temporary pool usage for some simple functions
3400         my $e;
3401         foreach (qw/get_latest_revnum rev_proplist get_file
3402                     check_path get_dir get_uuid get_repos_root/) {
3403                 $e .= "sub $_ {
3404                         my \$self = shift;
3405                         my \$pool = SVN::Pool->new;
3406                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
3407                         \$pool->clear;
3408                         wantarray ? \@ret : \$ret[0]; }\n";
3409         }
3410         eval $e;
3413 sub new {
3414         my ($class, $url) = @_;
3415         SVN::_Core::svn_config_ensure($config_dir, undef);
3416         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3417             SVN::Client::get_simple_provider(),
3418             SVN::Client::get_ssl_server_trust_file_provider(),
3419             SVN::Client::get_simple_prompt_provider(
3420               \&Git::SVN::Prompt::simple, 2),
3421             SVN::Client::get_ssl_client_cert_prompt_provider(
3422               \&Git::SVN::Prompt::ssl_client_cert, 2),
3423             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3424               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3425             SVN::Client::get_username_provider(),
3426             SVN::Client::get_ssl_server_trust_prompt_provider(
3427               \&Git::SVN::Prompt::ssl_server_trust),
3428             SVN::Client::get_username_prompt_provider(
3429               \&Git::SVN::Prompt::username, 2),
3430           ]);
3431         my $config = SVN::Core::config_get_config($config_dir);
3432         my $self = SVN::Ra->new(url => $url, auth => $baton,
3433                               config => $config,
3434                               pool => SVN::Pool->new,
3435                               auth_provider_callbacks => $callbacks);
3436         $self->{svn_path} = $url;
3437         $self->{repos_root} = $self->get_repos_root;
3438         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
3439         bless $self, $class;
3442 sub DESTROY {
3443         my $self = shift;
3444         $self->{pool}->clear if $self->{pool};
3445         $self->SUPER::DESTROY(@_);
3448 sub dup {
3449         my ($self) = @_;
3450         my $dup = SVN::Ra->new(pool => SVN::Pool->new,
3451                                 map { $_ => $self->{$_} } qw/config url
3452                      auth auth_provider_callbacks repos_root svn_path/);
3453         bless $dup, ref $self;
3456 sub get_log {
3457         my ($self, @args) = @_;
3458         my $pool = SVN::Pool->new;
3459         $args[4]-- if $args[4] && ! $::_follow_parent;
3460         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3461         my $ret = $self->SUPER::get_log(@args, $pool);
3462         $pool->clear;
3463         $ret;
3466 sub get_commit_editor {
3467         my ($self, $msg, $cb, $pool) = @_;
3468         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3469         $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3472 sub uuid {
3473         my ($self) = @_;
3474         $self->{uuid} ||= $self->get_uuid;
3477 sub gs_do_update {
3478         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3479         my $pool = SVN::Pool->new;
3480         my $reporter = $self->do_update($rev_b, $path, $recurse,
3481                                         $editor, $pool);
3482         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3483         my $new = ($rev_a == $rev_b);
3484         $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3485         $reporter->finish_report($pool);
3486         $pool->clear;
3487         $editor->{git_commit_ok};
3490 sub gs_do_switch {
3491         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3492         my $pool = SVN::Pool->new;
3493         my $reporter = $self->do_switch($rev_b, $path, $recurse,
3494                                         $url_b, $editor, $pool);
3495         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3496         $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3497         $reporter->finish_report($pool);
3498         $pool->clear;
3499         $editor->{git_commit_ok};
3502 sub can_do_switch {
3503         my $self = shift;
3504         unless (defined $can_do_switch) {
3505                 my $pool = SVN::Pool->new;
3506                 my $rep = eval {
3507                         $self->do_switch(1, '', 0, $self->{url},
3508                                          SVN::Delta::Editor->new, $pool);
3509                 };
3510                 if ($@) {
3511                         $can_do_switch = 0;
3512                 } else {
3513                         $rep->abort_report($pool);
3514                         $can_do_switch = 1;
3515                 }
3516                 $pool->clear;
3517         }
3518         $can_do_switch;
3521 __END__
3523 Data structures:
3525 $log_msg hashref as returned by libsvn_log_entry()
3527         msg => 'whitespace-formatted log entry
3528 ',                                              # trailing newline is preserved
3529         revision => '8',                        # integer
3530         date => '2004-02-24T17:01:44.108345Z',  # commit date
3531         author => 'committer name'
3532 };
3534 @mods = array of diff-index line hashes, each element represents one line
3535         of diff-index output
3537 diff-index line ($m hash)
3539         mode_a => first column of diff-index output, no leading ':',
3540         mode_b => second column of diff-index output,
3541         sha1_b => sha1sum of the final blob,
3542         chg => change type [MCRADT],
3543         file_a => original file name of a file (iff chg is 'C' or 'R')
3544         file_b => new/current file name of a file (any chg)
3548 # retval of read_url_paths{,_all}();
3549 $l_map = {
3550         # repository root url
3551         'https://svn.musicpd.org' => {
3552                 # repository path               # GIT_SVN_ID
3553                 'mpd/trunk'             =>      'trunk',
3554                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3555         },
3558 Notes:
3559         I don't trust the each() function on unless I created %hash myself
3560         because the internal iterator may not have started at base.