Code

git-svn: cleanup: put SVN workarounds into their own namespace
[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 qw/command command_oneline command_noisy
53            command_output_pipe command_input_pipe command_close_pipe/;
54 memoize('revisions_eq');
55 memoize('cmt_metadata');
56 memoize('get_commit_time');
58 my ($SVN);
60 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
61 my $sha1 = qr/[a-f\d]{40}/;
62 my $sha1_short = qr/[a-f\d]{4,40}/;
63 my $_esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
64 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
65         $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
66         $_repack, $_repack_nr, $_repack_flags, $_q,
67         $_message, $_file, $_no_metadata,
68         $_template, $_shared, $_no_default_regex, $_no_graft_copy,
69         $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
70         $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
71         $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
72         $_pager, $_color, $_prefix);
73 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
74 my ($_svn_can_do_switch);
75 my @repo_path_split_cache;
76 use vars qw/$_follow_parent/;
78 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
79                 'branch|b=s' => \@_branch_from,
80                 'follow-parent|follow' => \$_follow_parent,
81                 'branch-all-refs|B' => \$_branch_all_refs,
82                 'authors-file|A=s' => \$_authors,
83                 'repack:i' => \$_repack,
84                 'no-metadata' => \$_no_metadata,
85                 'quiet|q' => \$_q,
86                 'username=s' => \$Git::SVN::Prompt::_username,
87                 'config-dir=s' => \$Git::SVN::Ra::config_dir,
88                 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
89                 'ignore-nodate' => \$_ignore_nodate,
90                 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
92 my ($_trunk, $_tags, $_branches);
93 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
94                 'tags|t=s' => \$_tags,
95                 'branches|b=s' => \$_branches );
96 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
97 my %cmt_opts = ( 'edit|e' => \$_edit,
98                 'rmdir' => \$_rmdir,
99                 'find-copies-harder' => \$_find_copies_harder,
100                 'l=i' => \$_l,
101                 'copy-similarity|C=i'=> \$_cp_similarity
102 );
104 my %cmd = (
105         fetch => [ \&cmd_fetch, "Download new revisions from SVN",
106                         { 'revision|r=s' => \$_revision, %fc_opts } ],
107         init => [ \&init, "Initialize a repo for tracking" .
108                           " (requires URL argument)",
109                           \%init_opts ],
110         dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
111                         { 'merge|m|M' => \$_merge,
112                           'strategy|s=s' => \$_strategy,
113                           'dry-run|n' => \$_dry_run,
114                         %cmt_opts, %fc_opts } ],
115         'set-tree' => [ \&commit, "Set an SVN repository to a git tree-ish",
116                         {       'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
117         'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
118                         { 'revision|r=i' => \$_revision } ],
119         rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
120                         { 'no-ignore-externals' => \$_no_ignore_ext,
121                           'copy-remote|remote=s' => \$_cp_remote,
122                           'upgrade' => \$_upgrade } ],
123         'graft-branches' => [ \&graft_branches,
124                         'Detect merges/branches from already imported history',
125                         { 'merge-rx|m' => \@_opt_m,
126                           'branch|b=s' => \@_branch_from,
127                           'branch-all-refs|B' => \$_branch_all_refs,
128                           'no-default-regex' => \$_no_default_regex,
129                           'no-graft-copy' => \$_no_graft_copy } ],
130         'multi-init' => [ \&multi_init,
131                         'Initialize multiple trees (like git-svnimport)',
132                         { %multi_opts, %init_opts,
133                          'revision|r=i' => \$_revision,
134                          'username=s' => \$Git::SVN::Prompt::_username,
135                          'config-dir=s' => \$Git::SVN::Ra::config_dir,
136                          'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
137                          'prefix=s' => \$_prefix,
138                         } ],
139         'multi-fetch' => [ \&multi_fetch,
140                         'Fetch multiple trees (like git-svnimport)',
141                         \%fc_opts ],
142         'log' => [ \&show_log, 'Show commit logs',
143                         { 'limit=i' => \$_limit,
144                           'revision|r=s' => \$_revision,
145                           'verbose|v' => \$_verbose,
146                           'incremental' => \$_incremental,
147                           'oneline' => \$_oneline,
148                           'show-commit' => \$_show_commit,
149                           'non-recursive' => \$_non_recursive,
150                           'authors-file|A=s' => \$_authors,
151                           'color' => \$_color,
152                           'pager=s' => \$_pager,
153                         } ],
154         'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
155                         { 'message|m=s' => \$_message,
156                           'file|F=s' => \$_file,
157                           'revision|r=s' => \$_revision,
158                         %cmt_opts } ],
159 );
161 my $cmd;
162 for (my $i = 0; $i < @ARGV; $i++) {
163         if (defined $cmd{$ARGV[$i]}) {
164                 $cmd = $ARGV[$i];
165                 splice @ARGV, $i, 1;
166                 last;
167         }
168 };
170 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
172 read_repo_config(\%opts);
173 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
174                                 'version|V' => \$_version,
175                                 'id|i=s' => \$GIT_SVN);
176 exit 1 if (!$rv && $cmd ne 'log');
178 set_default_vals();
179 usage(0) if $_help;
180 version() if $_version;
181 usage(1) unless defined $cmd;
182 init_vars();
183 load_authors() if $_authors;
184 load_all_refs() if $_branch_all_refs;
185 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
186 $cmd{$cmd}->[0]->(@ARGV);
187 exit 0;
189 ####################### primary functions ######################
190 sub usage {
191         my $exit = shift || 0;
192         my $fd = $exit ? \*STDERR : \*STDOUT;
193         print $fd <<"";
194 git-svn - bidirectional operations between a single Subversion tree and git
195 Usage: $0 <command> [options] [arguments]\n
197         print $fd "Available commands:\n" unless $cmd;
199         foreach (sort keys %cmd) {
200                 next if $cmd && $cmd ne $_;
201                 print $fd '  ',pack('A17',$_),$cmd{$_}->[1],"\n";
202                 foreach (keys %{$cmd{$_}->[2]}) {
203                         # prints out arguments as they should be passed:
204                         my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
205                         print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
206                                                         "--$_" : "-$_" }
207                                                 split /\|/,$_)," $x\n";
208                 }
209         }
210         print $fd <<"";
211 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
212 arbitrary identifier if you're tracking multiple SVN branches/repositories in
213 one git repository and want to keep them separate.  See git-svn(1) for more
214 information.
216         exit $exit;
219 sub version {
220         print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
221         exit 0;
224 sub rebuild {
225         if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
226                 copy_remote_ref();
227         }
228         $SVN_URL = shift or undef;
229         my $newest_rev = 0;
230         if ($_upgrade) {
231                 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
232                               $GIT_SVN-HEAD");
233         } else {
234                 check_upgrade_needed();
235         }
237         my ($rev_list, $ctx) = command_output_pipe("rev-list",
238                                                    "refs/remotes/$GIT_SVN");
239         my $latest;
240         my $svn_uuid;
241         while (<$rev_list>) {
242                 chomp;
243                 my $c = $_;
244                 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
245                 my @commit = grep(/^git-svn-id: /,
246                                   command(qw/cat-file commit/, $c));
247                 next if (!@commit); # skip merges
248                 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
249                 if (!defined $rev || !$uuid) {
250                         croak "Unable to extract revision or UUID from ",
251                                 "$c, $commit[$#commit]\n";
252                 }
254                 # if we merged or otherwise started elsewhere, this is
255                 # how we break out of it
256                 next if (defined $svn_uuid && ($uuid ne $svn_uuid));
257                 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
259                 unless (defined $latest) {
260                         if (!$SVN_URL && !$url) {
261                                 croak "SVN repository location required: $url\n";
262                         }
263                         $SVN_URL ||= $url;
264                         $svn_uuid ||= $uuid;
265                         setup_git_svn();
266                         $latest = $rev;
267                 }
268                 revdb_set($REVDB, $rev, $c);
269                 print "r$rev = $c\n";
270                 $newest_rev = $rev if ($rev > $newest_rev);
271         }
272         command_close_pipe($rev_list, $ctx);
275 sub init {
276         my $url = shift or die "SVN repository location required " .
277                                 "as a command-line argument\n";
278         $url =~ s!/+$!!; # strip trailing slash
280         if (my $repo_path = shift) {
281                 unless (-d $repo_path) {
282                         mkpath([$repo_path]);
283                 }
284                 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
285                 init_vars();
286         }
288         $SVN_URL = $url;
289         unless (-d $GIT_DIR) {
290                 my @init_db = ('init');
291                 push @init_db, "--template=$_template" if defined $_template;
292                 push @init_db, "--shared" if defined $_shared;
293                 command_noisy(@init_db);
294         }
295         setup_git_svn();
298 sub cmd_fetch {
299         fetch_child_id($GIT_SVN, @_);
302 sub fetch {
303         check_upgrade_needed();
304         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
305         my $ret = fetch_lib(@_);
306         if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
307                 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
308         }
309         return $ret;
312 sub fetch_lib {
313         my (@parents) = @_;
314         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
315         $SVN ||= Git::SVN::Ra->new($SVN_URL);
316         my ($last_rev, $last_commit) = svn_grab_base_rev();
317         my ($base, $head) = libsvn_parse_revision($last_rev);
318         if ($base > $head) {
319                 return { revision => $last_rev, commit => $last_commit }
320         }
321         my $index = set_index($GIT_SVN_INDEX);
323         # limit ourselves and also fork() since get_log won't release memory
324         # after processing a revision and SVN stuff seems to leak
325         my $inc = 1000;
326         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
327         if (defined $last_commit) {
328                 unless (-e $GIT_SVN_INDEX) {
329                         command_noisy('read-tree', $last_commit);
330                 }
331                 my $x = command_oneline('write-tree');
332                 my ($y) = (command(qw/cat-file commit/, $last_commit)
333                                                         =~ /^tree ($sha1)/m);
334                 if ($y ne $x) {
335                         unlink $GIT_SVN_INDEX or croak $!;
336                         command_noisy('read-tree', $last_commit);
337                 }
338                 $x = command_oneline('write-tree');
339                 if ($y ne $x) {
340                         print STDERR "trees ($last_commit) $y != $x\n",
341                                  "Something is seriously wrong...\n";
342                 }
343         }
344         while (1) {
345                 # fork, because using SVN::Pool with get_log() still doesn't
346                 # seem to help enough to keep memory usage down.
347                 defined(my $pid = fork) or croak $!;
348                 if (!$pid) {
349                         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
351                         # Yes I'm perfectly aware that the fourth argument
352                         # below is the limit revisions number.  Unfortunately
353                         # performance sucks with it enabled, so it's much
354                         # faster to fetch revision ranges instead of relying
355                         # on the limiter.
356                         $SVN->dup->get_log([''], $min, $max, 0, 1, 1,
357                                 sub {
358                                         my $log_msg;
359                                         if ($last_commit) {
360                                                 $log_msg = libsvn_fetch(
361                                                         $last_commit, @_);
362                                                 $last_commit = git_commit(
363                                                         $log_msg,
364                                                         $last_commit,
365                                                         @parents);
366                                         } else {
367                                                 $log_msg = libsvn_new_tree(@_);
368                                                 $last_commit = git_commit(
369                                                         $log_msg, @parents);
370                                         }
371                                 });
372                         exit 0;
373                 }
374                 waitpid $pid, 0;
375                 croak $? if $?;
376                 ($last_rev, $last_commit) = svn_grab_base_rev();
377                 last if ($max >= $head);
378                 $min = $max + 1;
379                 $max += $inc;
380                 $max = $head if ($max > $head);
381                 $SVN = Git::SVN::Ra->new($SVN_URL);
382         }
383         restore_index($index);
384         return { revision => $last_rev, commit => $last_commit };
387 sub commit {
388         my (@commits) = @_;
389         check_upgrade_needed();
390         if ($_stdin || !@commits) {
391                 print "Reading from stdin...\n";
392                 @commits = ();
393                 while (<STDIN>) {
394                         if (/\b($sha1_short)\b/o) {
395                                 unshift @commits, $1;
396                         }
397                 }
398         }
399         my @revs;
400         foreach my $c (@commits) {
401                 my @tmp = command('rev-parse',$c);
402                 if (scalar @tmp == 1) {
403                         push @revs, $tmp[0];
404                 } elsif (scalar @tmp > 1) {
405                         push @revs, reverse(command('rev-list',@tmp));
406                 } else {
407                         die "Failed to rev-parse $c\n";
408                 }
409         }
410         commit_lib(@revs);
411         print "Done committing ",scalar @revs," revisions to SVN\n";
414 sub commit_lib {
415         my (@revs) = @_;
416         my ($r_last, $cmt_last) = svn_grab_base_rev();
417         defined $r_last or die "Must have an existing revision to commit\n";
418         my $fetched = fetch();
419         if ($r_last != $fetched->{revision}) {
420                 print STDERR "There are new revisions that were fetched ",
421                                 "and need to be merged (or acknowledged) ",
422                                 "before committing.\n",
423                                 "last rev: $r_last\n",
424                                 " current: $fetched->{revision}\n";
425                 exit 1;
426         }
427         my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
429         my $repo;
430         set_svn_commit_env();
431         foreach my $c (@revs) {
432                 my $log_msg = get_commit_message($c, $commit_msg);
434                 # fork for each commit because there's a memory leak I
435                 # can't track down... (it's probably in the SVN code)
436                 defined(my $pid = open my $fh, '-|') or croak $!;
437                 if (!$pid) {
438                         my $pool = SVN::Pool->new;
439                         my $ed = SVN::Git::Editor->new(
440                                         {       r => $r_last,
441                                                 ra => $SVN->dup,
442                                                 c => $c,
443                                                 svn_path => $SVN->{svn_path},
444                                         },
445                                         $SVN->get_commit_editor(
446                                                 $log_msg->{msg},
447                                                 sub {
448                                                         libsvn_commit_cb(
449                                                                 @_, $c,
450                                                                 $log_msg->{msg},
451                                                                 $r_last,
452                                                                 $cmt_last)
453                                                 }, $pool)
454                                         );
455                         my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
456                         if (@$mods == 0) {
457                                 print "No changes\nr$r_last = $cmt_last\n";
458                                 $ed->abort_edit;
459                         } else {
460                                 $ed->close_edit;
461                         }
462                         $pool->clear;
463                         exit 0;
464                 }
465                 my ($r_new, $cmt_new, $no);
466                 while (<$fh>) {
467                         print $_;
468                         chomp;
469                         if (/^r(\d+) = ($sha1)$/o) {
470                                 ($r_new, $cmt_new) = ($1, $2);
471                         } elsif ($_ eq 'No changes') {
472                                 $no = 1;
473                         }
474                 }
475                 close $fh or exit 1;
476                 if (! defined $r_new && ! defined $cmt_new) {
477                         unless ($no) {
478                                 die "Failed to parse revision information\n";
479                         }
480                 } else {
481                         ($r_last, $cmt_last) = ($r_new, $cmt_new);
482                 }
483         }
484         $ENV{LC_ALL} = 'C';
485         unlink $commit_msg;
488 sub dcommit {
489         my $head = shift || 'HEAD';
490         my $gs = "refs/remotes/$GIT_SVN";
491         my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
492         my $last_rev;
493         foreach my $d (reverse @refs) {
494                 if (!verify_ref("$d~1")) {
495                         die "Commit $d\n",
496                             "has no parent commit, and therefore ",
497                             "nothing to diff against.\n",
498                             "You should be working from a repository ",
499                             "originally created by git-svn\n";
500                 }
501                 unless (defined $last_rev) {
502                         (undef, $last_rev, undef) = cmt_metadata("$d~1");
503                         unless (defined $last_rev) {
504                                 die "Unable to extract revision information ",
505                                     "from commit $d~1\n";
506                         }
507                 }
508                 if ($_dry_run) {
509                         print "diff-tree $d~1 $d\n";
510                 } else {
511                         if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
512                                 $last_rev = $r;
513                         } # else: no changes, same $last_rev
514                 }
515         }
516         return if $_dry_run;
517         fetch();
518         my @diff = command('diff-tree', 'HEAD', $gs, '--');
519         my @finish;
520         if (@diff) {
521                 @finish = qw/rebase/;
522                 push @finish, qw/--merge/ if $_merge;
523                 push @finish, "--strategy=$_strategy" if $_strategy;
524                 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
525         } else {
526                 print "No changes between current HEAD and $gs\n",
527                       "Resetting to the latest $gs\n";
528                 @finish = qw/reset --mixed/;
529         }
530         command_noisy(@finish, $gs);
533 sub show_ignore {
534         $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
535         my $repo;
536         $SVN ||= Git::SVN::Ra->new($SVN_URL);
537         my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
538         libsvn_traverse_ignore(\*STDOUT, '', $r);
541 sub graft_branches {
542         my $gr_file = "$GIT_DIR/info/grafts";
543         my ($grafts, $comments) = read_grafts($gr_file);
544         my $gr_sha1;
546         if (%$grafts) {
547                 # temporarily disable our grafts file to make this idempotent
548                 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
549                 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
550         }
552         my $l_map = read_url_paths();
553         my @re = map { qr/$_/is } @_opt_m if @_opt_m;
554         unless ($_no_default_regex) {
555                 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
556                         qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
557                         qr/\b(?:from|of)\s+([\w\.\-]+)/i );
558         }
559         foreach my $u (keys %$l_map) {
560                 if (@re) {
561                         foreach my $p (keys %{$l_map->{$u}}) {
562                                 graft_merge_msg($grafts,$l_map,$u,$p,@re);
563                         }
564                 }
565                 unless ($_no_graft_copy) {
566                         graft_file_copy_lib($grafts,$l_map,$u);
567                 }
568         }
569         graft_tree_joins($grafts);
571         write_grafts($grafts, $comments, $gr_file);
572         unlink "$gr_file~$gr_sha1" if $gr_sha1;
575 sub multi_init {
576         my $url = shift;
577         unless (defined $_trunk || defined $_branches || defined $_tags) {
578                 usage(1);
579         }
580         if (defined $_trunk) {
581                 my $trunk_url = complete_svn_url($url, $_trunk);
582                 my $ch_id;
583                 if ($GIT_SVN eq 'git-svn') {
584                         $ch_id = 1;
585                         $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
586                 }
587                 init_vars();
588                 unless (-d $GIT_SVN_DIR) {
589                         if ($ch_id) {
590                                 print "GIT_SVN_ID set to 'trunk' for ",
591                                       "$trunk_url ($_trunk)\n";
592                         }
593                         init($trunk_url);
594                         command_noisy('config', 'svn.trunk', $trunk_url);
595                 }
596         }
597         $_prefix = '' unless defined $_prefix;
598         complete_url_ls_init($url, $_branches, '--branches/-b', $_prefix);
599         complete_url_ls_init($url, $_tags, '--tags/-t', $_prefix . 'tags/');
602 sub multi_fetch {
603         # try to do trunk first, since branches/tags
604         # may be descended from it.
605         if (-e "$GIT_DIR/svn/trunk/info/url") {
606                 fetch_child_id('trunk', @_);
607         }
608         rec_fetch('', "$GIT_DIR/svn", @_);
611 sub show_log {
612         my (@args) = @_;
613         my ($r_min, $r_max);
614         my $r_last = -1; # prevent dupes
615         rload_authors() if $_authors;
616         if (defined $TZ) {
617                 $ENV{TZ} = $TZ;
618         } else {
619                 delete $ENV{TZ};
620         }
621         if (defined $_revision) {
622                 if ($_revision =~ /^(\d+):(\d+)$/) {
623                         ($r_min, $r_max) = ($1, $2);
624                 } elsif ($_revision =~ /^\d+$/) {
625                         $r_min = $r_max = $_revision;
626                 } else {
627                         print STDERR "-r$_revision is not supported, use ",
628                                 "standard \'git log\' arguments instead\n";
629                         exit 1;
630                 }
631         }
633         config_pager();
634         @args = (git_svn_log_cmd($r_min, $r_max), @args);
635         my $log = command_output_pipe(@args);
636         run_pager();
637         my (@k, $c, $d);
639         while (<$log>) {
640                 if (/^${_esc_color}commit ($sha1_short)/o) {
641                         my $cmt = $1;
642                         if ($c && cmt_showable($c) && $c->{r} != $r_last) {
643                                 $r_last = $c->{r};
644                                 process_commit($c, $r_min, $r_max, \@k) or
645                                                                 goto out;
646                         }
647                         $d = undef;
648                         $c = { c => $cmt };
649                 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
650                         get_author_info($c, $1, $2, $3);
651                 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
652                         # ignore
653                 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
654                         push @{$c->{raw}}, $_;
655                 } elsif (/^${_esc_color}[ACRMDT]\t/) {
656                         # we could add $SVN->{svn_path} here, but that requires
657                         # remote access at the moment (repo_path_split)...
658                         s#^(${_esc_color})([ACRMDT])\t#$1   $2 #;
659                         push @{$c->{changed}}, $_;
660                 } elsif (/^${_esc_color}diff /) {
661                         $d = 1;
662                         push @{$c->{diff}}, $_;
663                 } elsif ($d) {
664                         push @{$c->{diff}}, $_;
665                 } elsif (/^${_esc_color}    (git-svn-id:.+)$/) {
666                         ($c->{url}, $c->{r}, undef) = extract_metadata($1);
667                 } elsif (s/^${_esc_color}    //) {
668                         push @{$c->{l}}, $_;
669                 }
670         }
671         if ($c && defined $c->{r} && $c->{r} != $r_last) {
672                 $r_last = $c->{r};
673                 process_commit($c, $r_min, $r_max, \@k);
674         }
675         if (@k) {
676                 my $swap = $r_max;
677                 $r_max = $r_min;
678                 $r_min = $swap;
679                 process_commit($_, $r_min, $r_max) foreach reverse @k;
680         }
681 out:
682         close $log;
683         print '-' x72,"\n" unless $_incremental || $_oneline;
686 sub commit_diff_usage {
687         print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
688         exit 1
691 sub commit_diff {
692         my $ta = shift or commit_diff_usage();
693         my $tb = shift or commit_diff_usage();
694         if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
695                 print STDERR "Needed URL or usable git-svn id command-line\n";
696                 commit_diff_usage();
697         }
698         my $r = shift;
699         unless (defined $r) {
700                 if (defined $_revision) {
701                         $r = $_revision
702                 } else {
703                         die "-r|--revision is a required argument\n";
704                 }
705         }
706         if (defined $_message && defined $_file) {
707                 print STDERR "Both --message/-m and --file/-F specified ",
708                                 "for the commit message.\n",
709                                 "I have no idea what you mean\n";
710                 exit 1;
711         }
712         if (defined $_file) {
713                 $_message = file_to_s($_file);
714         } else {
715                 $_message ||= get_commit_message($tb,
716                                         "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
717         }
718         $SVN ||= Git::SVN::Ra->new($SVN_URL);
719         if ($r eq 'HEAD') {
720                 $r = $SVN->get_latest_revnum;
721         } elsif ($r !~ /^\d+$/) {
722                 die "revision argument: $r not understood by git-svn\n";
723         }
724         my $rev_committed;
725         my $pool = SVN::Pool->new;
726         my $ed = SVN::Git::Editor->new({        r => $r,
727                                                 ra => $SVN->dup,
728                                                 c => $tb,
729                                                 svn_path => $SVN->{svn_path}
730                                         },
731                                 $SVN->get_commit_editor($_message,
732                                         sub {
733                                                 $rev_committed = $_[0];
734                                                 print "Committed $_[0]\n";
735                                         },
736                                         $pool)
737                                 );
738         eval {
739                 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
740                 if (@$mods == 0) {
741                         print "No changes\n$ta == $tb\n";
742                         $ed->abort_edit;
743                 } else {
744                         $ed->close_edit;
745                 }
746         };
747         $pool->clear;
748         fatal "$@\n" if $@;
749         $_message = $_file = undef;
750         return $rev_committed;
753 ########################### utility functions #########################
755 sub cmt_showable {
756         my ($c) = @_;
757         return 1 if defined $c->{r};
758         if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
759                                 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
760                 my @msg = command(qw/cat-file commit/, $c->{c});
761                 shift @msg while ($msg[0] ne "\n");
762                 shift @msg;
763                 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
765                 (undef, $c->{r}, undef) = extract_metadata(
766                                 (grep(/^git-svn-id: /, @msg))[-1]);
767         }
768         return defined $c->{r};
771 sub log_use_color {
772         return 1 if $_color;
773         my ($dc, $dcvar);
774         $dcvar = 'color.diff';
775         $dc = `git-config --get $dcvar`;
776         if ($dc eq '') {
777                 # nothing at all; fallback to "diff.color"
778                 $dcvar = 'diff.color';
779                 $dc = `git-config --get $dcvar`;
780         }
781         chomp($dc);
782         if ($dc eq 'auto') {
783                 my $pc;
784                 $pc = `git-config --get color.pager`;
785                 if ($pc eq '') {
786                         # does not have it -- fallback to pager.color
787                         $pc = `git-config --bool --get pager.color`;
788                 }
789                 else {
790                         $pc = `git-config --bool --get color.pager`;
791                         if ($?) {
792                                 $pc = 'false';
793                         }
794                 }
795                 chomp($pc);
796                 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
797                         return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
798                 }
799                 return 0;
800         }
801         return 0 if $dc eq 'never';
802         return 1 if $dc eq 'always';
803         chomp($dc = `git-config --bool --get $dcvar`);
804         return ($dc eq 'true');
807 sub git_svn_log_cmd {
808         my ($r_min, $r_max) = @_;
809         my @cmd = (qw/log --abbrev-commit --pretty=raw
810                         --default/, "refs/remotes/$GIT_SVN");
811         push @cmd, '-r' unless $_non_recursive;
812         push @cmd, qw/--raw --name-status/ if $_verbose;
813         push @cmd, '--color' if log_use_color();
814         return @cmd unless defined $r_max;
815         if ($r_max == $r_min) {
816                 push @cmd, '--max-count=1';
817                 if (my $c = revdb_get($REVDB, $r_max)) {
818                         push @cmd, $c;
819                 }
820         } else {
821                 my ($c_min, $c_max);
822                 $c_max = revdb_get($REVDB, $r_max);
823                 $c_min = revdb_get($REVDB, $r_min);
824                 if (defined $c_min && defined $c_max) {
825                         if ($r_max > $r_max) {
826                                 push @cmd, "$c_min..$c_max";
827                         } else {
828                                 push @cmd, "$c_max..$c_min";
829                         }
830                 } elsif ($r_max > $r_min) {
831                         push @cmd, $c_max;
832                 } else {
833                         push @cmd, $c_min;
834                 }
835         }
836         return @cmd;
839 sub fetch_child_id {
840         my $id = shift;
841         print "Fetching $id\n";
842         my $ref = "$GIT_DIR/refs/remotes/$id";
843         defined(my $pid = open my $fh, '-|') or croak $!;
844         if (!$pid) {
845                 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
846                 init_vars();
847                 fetch(@_);
848                 exit 0;
849         }
850         while (<$fh>) {
851                 print $_;
852                 check_repack() if (/^r\d+ = $sha1/o);
853         }
854         close $fh or croak $?;
857 sub rec_fetch {
858         my ($pfx, $p, @args) = @_;
859         my @dir;
860         foreach (sort <$p/*>) {
861                 if (-r "$_/info/url") {
862                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
863                         my $id = $pfx . basename $_;
864                         next if $id eq 'trunk';
865                         fetch_child_id($id, @args);
866                 } elsif (-d $_) {
867                         push @dir, $_;
868                 }
869         }
870         foreach (@dir) {
871                 my $x = $_;
872                 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
873                 rec_fetch($x, $_);
874         }
877 sub complete_svn_url {
878         my ($url, $path) = @_;
879         $path =~ s#/+$##;
880         $url =~ s#/+$## if $url;
881         if ($path !~ m#^[a-z\+]+://#) {
882                 $path = '/' . $path if ($path !~ m#^/#);
883                 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
884                         fatal("E: '$path' is not a complete URL ",
885                               "and a separate URL is not specified\n");
886                 }
887                 $path = $url . $path;
888         }
889         return $path;
892 sub complete_url_ls_init {
893         my ($url, $path, $switch, $pfx) = @_;
894         unless ($path) {
895                 print STDERR "W: $switch not specified\n";
896                 return;
897         }
898         my $full_url = complete_svn_url($url, $path);
899         my @ls = libsvn_ls_fullurl($full_url);
900         defined(my $pid = fork) or croak $!;
901         if (!$pid) {
902                 foreach my $u (map { "$full_url/$_" } (grep m!/$!, @ls)) {
903                         $u =~ s#/+$##;
904                         if ($u !~ m!\Q$full_url\E/(.+)$!) {
905                                 print STDERR "W: Unrecognized URL: $u\n";
906                                 die "This should never happen\n";
907                         }
908                         # don't try to init already existing refs
909                         my $id = $pfx.$1;
910                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
911                         init_vars();
912                         unless (-d $GIT_SVN_DIR) {
913                                 print "init $u => $id\n";
914                                 init($u);
915                         }
916                 }
917                 exit 0;
918         }
919         waitpid $pid, 0;
920         croak $? if $?;
921         my ($n) = ($switch =~ /^--(\w+)/);
922         command_noisy('config', "svn.$n", $full_url);
925 sub common_prefix {
926         my $paths = shift;
927         my %common;
928         foreach (@$paths) {
929                 my @tmp = split m#/#, $_;
930                 my $p = '';
931                 while (my $x = shift @tmp) {
932                         $p .= "/$x";
933                         $common{$p} ||= 0;
934                         $common{$p}++;
935                 }
936         }
937         foreach (sort {length $b <=> length $a} keys %common) {
938                 if ($common{$_} == @$paths) {
939                         return $_;
940                 }
941         }
942         return '';
945 # grafts set here are 'stronger' in that they're based on actual tree
946 # matches, and won't be deleted from merge-base checking in write_grafts()
947 sub graft_tree_joins {
948         my $grafts = shift;
949         map_tree_joins() if (@_branch_from && !%tree_map);
950         return unless %tree_map;
952         git_svn_each(sub {
953                 my $i = shift;
954                 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
955                 my ($fh, $ctx) = command_output_pipe(@args);
956                 while (<$fh>) {
957                         next unless /^commit ($sha1)$/o;
958                         my $c = $1;
959                         my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
960                         next unless $tree_map{$t};
962                         my $l;
963                         do {
964                                 $l = readline $fh;
965                         } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
967                         my ($s, $tz) = ($1, $2);
968                         if ($tz =~ s/^\+//) {
969                                 $s += tz_to_s_offset($tz);
970                         } elsif ($tz =~ s/^\-//) {
971                                 $s -= tz_to_s_offset($tz);
972                         }
974                         my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
976                         foreach my $p (@{$tree_map{$t}}) {
977                                 next if $p eq $c;
978                                 my $mb = eval { command('merge-base', $c, $p) };
979                                 next unless ($@ || $?);
980                                 if (defined $r_a) {
981                                         # see if SVN says it's a relative
982                                         my ($url_b, $r_b, $uuid_b) =
983                                                         cmt_metadata($p);
984                                         next if (defined $url_b &&
985                                                         defined $url_a &&
986                                                         ($url_a eq $url_b) &&
987                                                         ($uuid_a eq $uuid_b));
988                                         if ($uuid_a eq $uuid_b) {
989                                                 if ($r_b < $r_a) {
990                                                         $grafts->{$c}->{$p} = 2;
991                                                         next;
992                                                 } elsif ($r_b > $r_a) {
993                                                         $grafts->{$p}->{$c} = 2;
994                                                         next;
995                                                 }
996                                         }
997                                 }
998                                 my $ct = get_commit_time($p);
999                                 if ($ct < $s) {
1000                                         $grafts->{$c}->{$p} = 2;
1001                                 } elsif ($ct > $s) {
1002                                         $grafts->{$p}->{$c} = 2;
1003                                 }
1004                                 # what should we do when $ct == $s ?
1005                         }
1006                 }
1007                 command_close_pipe($fh, $ctx);
1008         });
1011 sub graft_file_copy_lib {
1012         my ($grafts, $l_map, $u) = @_;
1013         my $tree_paths = $l_map->{$u};
1014         my $pfx = common_prefix([keys %$tree_paths]);
1015         my ($repo, $path) = repo_path_split($u.$pfx);
1016         $SVN = Git::SVN::Ra->new($repo);
1018         my ($base, $head) = libsvn_parse_revision();
1019         my $inc = 1000;
1020         my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1021         my $eh = $SVN::Error::handler;
1022         $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1023         while (1) {
1024                 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
1025                         sub {
1026                                 libsvn_graft_file_copies($grafts, $tree_paths,
1027                                                         $path, @_);
1028                         });
1029                 last if ($max >= $head);
1030                 $min = $max + 1;
1031                 $max += $inc;
1032                 $max = $head if ($max > $head);
1033         }
1034         $SVN::Error::handler = $eh;
1037 sub process_merge_msg_matches {
1038         my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1039         my (@strong, @weak);
1040         foreach (@matches) {
1041                 # merging with ourselves is not interesting
1042                 next if $_ eq $p;
1043                 if ($l_map->{$u}->{$_}) {
1044                         push @strong, $_;
1045                 } else {
1046                         push @weak, $_;
1047                 }
1048         }
1049         foreach my $w (@weak) {
1050                 last if @strong;
1051                 # no exact match, use branch name as regexp.
1052                 my $re = qr/\Q$w\E/i;
1053                 foreach (keys %{$l_map->{$u}}) {
1054                         if (/$re/) {
1055                                 push @strong, $l_map->{$u}->{$_};
1056                                 last;
1057                         }
1058                 }
1059                 last if @strong;
1060                 $w = basename($w);
1061                 $re = qr/\Q$w\E/i;
1062                 foreach (keys %{$l_map->{$u}}) {
1063                         if (/$re/) {
1064                                 push @strong, $l_map->{$u}->{$_};
1065                                 last;
1066                         }
1067                 }
1068         }
1069         my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1070                                         \s(?:[a-f\d\-]+)$/xsm);
1071         unless (defined $rev) {
1072                 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1073                                         \@(?:[a-f\d\-]+)/xsm);
1074                 return unless defined $rev;
1075         }
1076         foreach my $m (@strong) {
1077                 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1078                 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1079         }
1082 sub graft_merge_msg {
1083         my ($grafts, $l_map, $u, $p, @re) = @_;
1085         my $x = $l_map->{$u}->{$p};
1086         my $rl = rev_list_raw("refs/remotes/$x");
1087         while (my $c = next_rev_list_entry($rl)) {
1088                 foreach my $re (@re) {
1089                         my (@br) = ($c->{m} =~ /$re/g);
1090                         next unless @br;
1091                         process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1092                 }
1093         }
1096 sub verify_ref {
1097         my ($ref) = @_;
1098         eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1099                                { STDERR => 0 }); };
1102 sub repo_path_split {
1103         my $full_url = shift;
1104         $full_url =~ s#/+$##;
1106         foreach (@repo_path_split_cache) {
1107                 if ($full_url =~ s#$_##) {
1108                         my $u = $1;
1109                         $full_url =~ s#^/+##;
1110                         return ($u, $full_url);
1111                 }
1112         }
1113         my $tmp = Git::SVN::Ra->new($full_url);
1114         return ($tmp->{repos_root}, $tmp->{svn_path});
1117 sub setup_git_svn {
1118         defined $SVN_URL or croak "SVN repository location required\n";
1119         unless (-d $GIT_DIR) {
1120                 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1121         }
1122         mkpath([$GIT_SVN_DIR]);
1123         mkpath(["$GIT_SVN_DIR/info"]);
1124         open my $fh, '>>',$REVDB or croak $!;
1125         close $fh;
1126         s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1130 sub get_tree_from_treeish {
1131         my ($treeish) = @_;
1132         croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1133         my $type = command_oneline(qw/cat-file -t/, $treeish);
1134         my $expected;
1135         while ($type eq 'tag') {
1136                 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1137         }
1138         if ($type eq 'commit') {
1139                 $expected = (grep /^tree /, command(qw/cat-file commit/,
1140                                                     $treeish))[0];
1141                 ($expected) = ($expected =~ /^tree ($sha1)$/);
1142                 die "Unable to get tree from $treeish\n" unless $expected;
1143         } elsif ($type eq 'tree') {
1144                 $expected = $treeish;
1145         } else {
1146                 die "$treeish is a $type, expected tree, tag or commit\n";
1147         }
1148         return $expected;
1151 sub get_diff {
1152         my ($from, $treeish) = @_;
1153         print "diff-tree $from $treeish\n";
1154         my @diff_tree = qw(diff-tree -z -r);
1155         if ($_cp_similarity) {
1156                 push @diff_tree, "-C$_cp_similarity";
1157         } else {
1158                 push @diff_tree, '-C';
1159         }
1160         push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1161         push @diff_tree, "-l$_l" if defined $_l;
1162         push @diff_tree, $from, $treeish;
1163         my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1164         local $/ = "\0";
1165         my $state = 'meta';
1166         my @mods;
1167         while (<$diff_fh>) {
1168                 chomp $_; # this gets rid of the trailing "\0"
1169                 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1170                                         $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1171                         push @mods, {   mode_a => $1, mode_b => $2,
1172                                         sha1_b => $3, chg => $4 };
1173                         if ($4 =~ /^(?:C|R)$/) {
1174                                 $state = 'file_a';
1175                         } else {
1176                                 $state = 'file_b';
1177                         }
1178                 } elsif ($state eq 'file_a') {
1179                         my $x = $mods[$#mods] or croak "Empty array\n";
1180                         if ($x->{chg} !~ /^(?:C|R)$/) {
1181                                 croak "Error parsing $_, $x->{chg}\n";
1182                         }
1183                         $x->{file_a} = $_;
1184                         $state = 'file_b';
1185                 } elsif ($state eq 'file_b') {
1186                         my $x = $mods[$#mods] or croak "Empty array\n";
1187                         if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1188                                 croak "Error parsing $_, $x->{chg}\n";
1189                         }
1190                         if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1191                                 croak "Error parsing $_, $x->{chg}\n";
1192                         }
1193                         $x->{file_b} = $_;
1194                         $state = 'meta';
1195                 } else {
1196                         croak "Error parsing $_\n";
1197                 }
1198         }
1199         command_close_pipe($diff_fh, $ctx);
1200         return \@mods;
1203 sub libsvn_checkout_tree {
1204         my ($from, $treeish, $ed) = @_;
1205         my $mods = get_diff($from, $treeish);
1206         return $mods unless (scalar @$mods);
1207         my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1208         foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1209                 my $f = $m->{chg};
1210                 if (defined $o{$f}) {
1211                         $ed->$f($m, $_q);
1212                 } else {
1213                         croak "Invalid change type: $f\n";
1214                 }
1215         }
1216         $ed->rmdirs($_q) if $_rmdir;
1217         return $mods;
1220 sub get_commit_message {
1221         my ($commit, $commit_msg) = (@_);
1222         my %log_msg = ( msg => '' );
1223         open my $msg, '>', $commit_msg or croak $!;
1225         my $type = command_oneline(qw/cat-file -t/, $commit);
1226         if ($type eq 'commit' || $type eq 'tag') {
1227                 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1228                                                          $type, $commit);
1229                 my $in_msg = 0;
1230                 while (<$msg_fh>) {
1231                         if (!$in_msg) {
1232                                 $in_msg = 1 if (/^\s*$/);
1233                         } elsif (/^git-svn-id: /) {
1234                                 # skip this, we regenerate the correct one
1235                                 # on re-fetch anyways
1236                         } else {
1237                                 print $msg $_ or croak $!;
1238                         }
1239                 }
1240                 command_close_pipe($msg_fh, $ctx);
1241         }
1242         close $msg or croak $!;
1244         if ($_edit || ($type eq 'tree')) {
1245                 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1246                 system($editor, $commit_msg);
1247         }
1249         # file_to_s removes all trailing newlines, so just use chomp() here:
1250         open $msg, '<', $commit_msg or croak $!;
1251         { local $/; chomp($log_msg{msg} = <$msg>); }
1252         close $msg or croak $!;
1254         return \%log_msg;
1257 sub set_svn_commit_env {
1258         if (defined $LC_ALL) {
1259                 $ENV{LC_ALL} = $LC_ALL;
1260         } else {
1261                 delete $ENV{LC_ALL};
1262         }
1265 sub rev_list_raw {
1266         my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1267         return { fh => $fh, ctx => $c, t => { } };
1270 sub next_rev_list_entry {
1271         my $rl = shift;
1272         my $fh = $rl->{fh};
1273         my $x = $rl->{t};
1274         while (<$fh>) {
1275                 if (/^commit ($sha1)$/o) {
1276                         if ($x->{c}) {
1277                                 $rl->{t} = { c => $1 };
1278                                 return $x;
1279                         } else {
1280                                 $x->{c} = $1;
1281                         }
1282                 } elsif (/^parent ($sha1)$/o) {
1283                         $x->{p}->{$1} = 1;
1284                 } elsif (s/^    //) {
1285                         $x->{m} ||= '';
1286                         $x->{m} .= $_;
1287                 }
1288         }
1289         command_close_pipe($fh, $rl->{ctx});
1290         return ($x != $rl->{t}) ? $x : undef;
1293 sub s_to_file {
1294         my ($str, $file, $mode) = @_;
1295         open my $fd,'>',$file or croak $!;
1296         print $fd $str,"\n" or croak $!;
1297         close $fd or croak $!;
1298         chmod ($mode &~ umask, $file) if (defined $mode);
1301 sub file_to_s {
1302         my $file = shift;
1303         open my $fd,'<',$file or croak "$!: file: $file\n";
1304         local $/;
1305         my $ret = <$fd>;
1306         close $fd or croak $!;
1307         $ret =~ s/\s*$//s;
1308         return $ret;
1311 sub assert_revision_unknown {
1312         my $r = shift;
1313         if (my $c = revdb_get($REVDB, $r)) {
1314                 croak "$r = $c already exists! Why are we refetching it?";
1315         }
1318 sub git_commit {
1319         my ($log_msg, @parents) = @_;
1320         assert_revision_unknown($log_msg->{revision});
1321         map_tree_joins() if (@_branch_from && !%tree_map);
1323         my (@tmp_parents, @exec_parents, %seen_parent);
1324         if (my $lparents = $log_msg->{parents}) {
1325                 @tmp_parents = @$lparents
1326         }
1327         # commit parents can be conditionally bound to a particular
1328         # svn revision via: "svn_revno=commit_sha1", filter them out here:
1329         foreach my $p (@parents) {
1330                 next unless defined $p;
1331                 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1332                         if ($1 == $log_msg->{revision}) {
1333                                 push @tmp_parents, $2;
1334                         }
1335                 } else {
1336                         push @tmp_parents, $p if $p =~ /$sha1_short/o;
1337                 }
1338         }
1339         my $tree = $log_msg->{tree};
1340         if (!defined $tree) {
1341                 my $index = set_index($GIT_SVN_INDEX);
1342                 $tree = command_oneline('write-tree');
1343                 croak $? if $?;
1344                 restore_index($index);
1345         }
1346         # just in case we clobber the existing ref, we still want that ref
1347         # as our parent:
1348         if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1349                 chomp $cur;
1350                 push @tmp_parents, $cur;
1351         }
1353         if (exists $tree_map{$tree}) {
1354                 foreach my $p (@{$tree_map{$tree}}) {
1355                         my $skip;
1356                         foreach (@tmp_parents) {
1357                                 # see if a common parent is found
1358                                 my $mb = eval { command('merge-base', $_, $p) };
1359                                 next if ($@ || $?);
1360                                 $skip = 1;
1361                                 last;
1362                         }
1363                         next if $skip;
1364                         my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1365                         next if (($SVN->uuid eq $uuid_p) &&
1366                                                 ($log_msg->{revision} > $r_p));
1367                         next if (defined $url_p && defined $SVN_URL &&
1368                                                 ($SVN->uuid eq $uuid_p) &&
1369                                                 ($url_p eq $SVN_URL));
1370                         push @tmp_parents, $p;
1371                 }
1372         }
1373         foreach (@tmp_parents) {
1374                 next if $seen_parent{$_};
1375                 $seen_parent{$_} = 1;
1376                 push @exec_parents, $_;
1377                 # MAXPARENT is defined to 16 in commit-tree.c:
1378                 last if @exec_parents > 16;
1379         }
1381         set_commit_env($log_msg);
1382         my @exec = ('git-commit-tree', $tree);
1383         push @exec, '-p', $_  foreach @exec_parents;
1384         defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1385                                                                 or croak $!;
1386         print $msg_fh $log_msg->{msg} or croak $!;
1387         unless ($_no_metadata) {
1388                 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1389                                         $SVN->uuid,"\n" or croak $!;
1390         }
1391         $msg_fh->flush == 0 or croak $!;
1392         close $msg_fh or croak $!;
1393         chomp(my $commit = do { local $/; <$out_fh> });
1394         close $out_fh or croak $!;
1395         waitpid $pid, 0;
1396         croak $? if $?;
1397         if ($commit !~ /^$sha1$/o) {
1398                 die "Failed to commit, invalid sha1: $commit\n";
1399         }
1400         command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1401         revdb_set($REVDB, $log_msg->{revision}, $commit);
1403         # this output is read via pipe, do not change:
1404         print "r$log_msg->{revision} = $commit\n";
1405         return $commit;
1408 sub check_repack {
1409         if ($_repack && (--$_repack_nr == 0)) {
1410                 $_repack_nr = $_repack;
1411                 # repack doesn't use any arguments with spaces in them, does it?
1412                 command_noisy('repack', split(/\s+/, $_repack_flags));
1413         }
1416 sub set_commit_env {
1417         my ($log_msg) = @_;
1418         my $author = $log_msg->{author};
1419         if (!defined $author || length $author == 0) {
1420                 $author = '(no author)';
1421         }
1422         my ($name,$email) = defined $users{$author} ?  @{$users{$author}}
1423                                 : ($author,$author . '@' . $SVN->uuid);
1424         $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1425         $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1426         $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1429 sub check_upgrade_needed {
1430         if (!-r $REVDB) {
1431                 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1432                 open my $fh, '>>',$REVDB or croak $!;
1433                 close $fh;
1434         }
1435         return unless eval {
1436                 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1437                         {STDERR => 0});
1438         };
1439         my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1440         if ($@ || !$head) {
1441                 print STDERR "Please run: $0 rebuild --upgrade\n";
1442                 exit 1;
1443         }
1446 # fills %tree_map with a reverse mapping of trees to commits.  Useful
1447 # for finding parents to commit on.
1448 sub map_tree_joins {
1449         my %seen;
1450         foreach my $br (@_branch_from) {
1451                 my $pipe = command_output_pipe(qw/rev-list
1452                                             --topo-order --pretty=raw/, $br);
1453                 while (<$pipe>) {
1454                         if (/^commit ($sha1)$/o) {
1455                                 my $commit = $1;
1457                                 # if we've seen a commit,
1458                                 # we've seen its parents
1459                                 last if $seen{$commit};
1460                                 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1461                                 unless (defined $tree) {
1462                                         die "Failed to parse commit $commit\n";
1463                                 }
1464                                 push @{$tree_map{$tree}}, $commit;
1465                                 $seen{$commit} = 1;
1466                         }
1467                 }
1468                 close $pipe;
1469         }
1472 sub load_all_refs {
1473         if (@_branch_from) {
1474                 print STDERR '--branch|-b parameters are ignored when ',
1475                         "--branch-all-refs|-B is passed\n";
1476         }
1478         # don't worry about rev-list on non-commit objects/tags,
1479         # it shouldn't blow up if a ref is a blob or tree...
1480         @_branch_from = command(qw/rev-parse --symbolic --all/);
1483 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1484 sub load_authors {
1485         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1486         while (<$authors>) {
1487                 chomp;
1488                 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1489                 my ($user, $name, $email) = ($1, $2, $3);
1490                 $users{$user} = [$name, $email];
1491         }
1492         close $authors or croak $!;
1495 sub rload_authors {
1496         open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1497         while (<$authors>) {
1498                 chomp;
1499                 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1500                 my ($user, $name, $email) = ($1, $2, $3);
1501                 $rusers{"$name <$email>"} = $user;
1502         }
1503         close $authors or croak $!;
1506 sub git_svn_each {
1507         my $sub = shift;
1508         foreach (command(qw/rev-parse --symbolic --all/)) {
1509                 next unless s#^refs/remotes/##;
1510                 chomp $_;
1511                 next unless -f "$GIT_DIR/svn/$_/info/url";
1512                 &$sub($_);
1513         }
1516 sub migrate_revdb {
1517         git_svn_each(sub {
1518                 my $id = shift;
1519                 defined(my $pid = fork) or croak $!;
1520                 if (!$pid) {
1521                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1522                         init_vars();
1523                         exit 0 if -r $REVDB;
1524                         print "Upgrading svn => git mapping...\n";
1525                         -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1526                         open my $fh, '>>',$REVDB or croak $!;
1527                         close $fh;
1528                         rebuild();
1529                         print "Done upgrading. You may now delete the ",
1530                                 "deprecated $GIT_SVN_DIR/revs directory\n";
1531                         exit 0;
1532                 }
1533                 waitpid $pid, 0;
1534                 croak $? if $?;
1535         });
1538 sub migration_check {
1539         migrate_revdb() unless (-e $REVDB);
1540         return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1541         print "Upgrading repository...\n";
1542         unless (-d "$GIT_DIR/svn") {
1543                 mkdir "$GIT_DIR/svn" or croak $!;
1544         }
1545         print "Data from a previous version of git-svn exists, but\n\t",
1546                                 "$GIT_SVN_DIR\n\t(required for this version ",
1547                                 "($VERSION) of git-svn) does not.\n";
1549         foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1550                 next unless $x =~ s#^refs/remotes/##;
1551                 chomp $x;
1552                 next unless -f "$GIT_DIR/$x/info/url";
1553                 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1554                 next unless $u;
1555                 my $dn = dirname("$GIT_DIR/svn/$x");
1556                 mkpath([$dn]) unless -d $dn;
1557                 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1558         }
1559         migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1560         print "Done upgrading.\n";
1563 sub find_rev_before {
1564         my ($r, $id, $eq_ok) = @_;
1565         my $f = "$GIT_DIR/svn/$id/.rev_db";
1566         return (undef,undef) unless -r $f;
1567         --$r unless $eq_ok;
1568         while ($r > 0) {
1569                 if (my $c = revdb_get($f, $r)) {
1570                         return ($r, $c);
1571                 }
1572                 --$r;
1573         }
1574         return (undef, undef);
1577 sub init_vars {
1578         $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1579         $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1580         $REVDB = "$GIT_SVN_DIR/.rev_db";
1581         $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1582         $SVN_URL = undef;
1583         %tree_map = ();
1586 # convert GetOpt::Long specs for use by git-config
1587 sub read_repo_config {
1588         return unless -d $GIT_DIR;
1589         my $opts = shift;
1590         foreach my $o (keys %$opts) {
1591                 my $v = $opts->{$o};
1592                 my ($key) = ($o =~ /^([a-z\-]+)/);
1593                 $key =~ s/-//g;
1594                 my $arg = 'git-config';
1595                 $arg .= ' --int' if ($o =~ /[:=]i$/);
1596                 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1597                 if (ref $v eq 'ARRAY') {
1598                         chomp(my @tmp = `$arg --get-all svn.$key`);
1599                         @$v = @tmp if @tmp;
1600                 } else {
1601                         chomp(my $tmp = `$arg --get svn.$key`);
1602                         if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1603                                 $$v = $tmp;
1604                         }
1605                 }
1606         }
1609 sub set_default_vals {
1610         if (defined $_repack) {
1611                 $_repack = 1000 if ($_repack <= 0);
1612                 $_repack_nr = $_repack;
1613                 $_repack_flags ||= '-d';
1614         }
1617 sub read_grafts {
1618         my $gr_file = shift;
1619         my ($grafts, $comments) = ({}, {});
1620         if (open my $fh, '<', $gr_file) {
1621                 my @tmp;
1622                 while (<$fh>) {
1623                         if (/^($sha1)\s+/) {
1624                                 my $c = $1;
1625                                 if (@tmp) {
1626                                         @{$comments->{$c}} = @tmp;
1627                                         @tmp = ();
1628                                 }
1629                                 foreach my $p (split /\s+/, $_) {
1630                                         $grafts->{$c}->{$p} = 1;
1631                                 }
1632                         } else {
1633                                 push @tmp, $_;
1634                         }
1635                 }
1636                 close $fh or croak $!;
1637                 @{$comments->{'END'}} = @tmp if @tmp;
1638         }
1639         return ($grafts, $comments);
1642 sub write_grafts {
1643         my ($grafts, $comments, $gr_file) = @_;
1645         open my $fh, '>', $gr_file or croak $!;
1646         foreach my $c (sort keys %$grafts) {
1647                 if ($comments->{$c}) {
1648                         print $fh $_ foreach @{$comments->{$c}};
1649                 }
1650                 my $p = $grafts->{$c};
1651                 my %x; # real parents
1652                 delete $p->{$c}; # commits are not self-reproducing...
1653                 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1654                 while (<$ch>) {
1655                         if (/^parent ($sha1)/) {
1656                                 $x{$1} = $p->{$1} = 1;
1657                         } else {
1658                                 last unless /^\S/;
1659                         }
1660                 }
1661                 close $ch; # breaking the pipe
1663                 # if real parents are the only ones in the grafts, drop it
1664                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1666                 my (@ip, @jp, $mb);
1667                 my %del = %x;
1668                 @ip = @jp = keys %$p;
1669                 foreach my $i (@ip) {
1670                         next if $del{$i} || $p->{$i} == 2;
1671                         foreach my $j (@jp) {
1672                                 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1673                                 $mb = eval { command('merge-base', $i, $j) };
1674                                 next unless $mb;
1675                                 chomp $mb;
1676                                 next if $x{$mb};
1677                                 if ($mb eq $j) {
1678                                         delete $p->{$i};
1679                                         $del{$i} = 1;
1680                                 } elsif ($mb eq $i) {
1681                                         delete $p->{$j};
1682                                         $del{$j} = 1;
1683                                 }
1684                         }
1685                 }
1687                 # if real parents are the only ones in the grafts, drop it
1688                 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1690                 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1691         }
1692         if ($comments->{'END'}) {
1693                 print $fh $_ foreach @{$comments->{'END'}};
1694         }
1695         close $fh or croak $!;
1698 sub read_url_paths_all {
1699         my ($l_map, $pfx, $p) = @_;
1700         my @dir;
1701         foreach (<$p/*>) {
1702                 if (-r "$_/info/url") {
1703                         $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1704                         my $id = $pfx . basename $_;
1705                         my $url = file_to_s("$_/info/url");
1706                         my ($u, $p) = repo_path_split($url);
1707                         $l_map->{$u}->{$p} = $id;
1708                 } elsif (-d $_) {
1709                         push @dir, $_;
1710                 }
1711         }
1712         foreach (@dir) {
1713                 my $x = $_;
1714                 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1715                 read_url_paths_all($l_map, $x, $_);
1716         }
1719 # this one only gets ids that have been imported, not new ones
1720 sub read_url_paths {
1721         my $l_map = {};
1722         git_svn_each(sub { my $x = shift;
1723                         my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1724                         my ($u, $p) = repo_path_split($url);
1725                         $l_map->{$u}->{$p} = $x;
1726                         });
1727         return $l_map;
1730 sub extract_metadata {
1731         my $id = shift or return (undef, undef, undef);
1732         my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1733                                                         \s([a-f\d\-]+)$/x);
1734         if (!defined $rev || !$uuid || !$url) {
1735                 # some of the original repositories I made had
1736                 # identifiers like this:
1737                 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1738         }
1739         return ($url, $rev, $uuid);
1742 sub cmt_metadata {
1743         return extract_metadata((grep(/^git-svn-id: /,
1744                 command(qw/cat-file commit/, shift)))[-1]);
1747 sub get_commit_time {
1748         my $cmt = shift;
1749         my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1750         while (<$fh>) {
1751                 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1752                 my ($s, $tz) = ($1, $2);
1753                 if ($tz =~ s/^\+//) {
1754                         $s += tz_to_s_offset($tz);
1755                 } elsif ($tz =~ s/^\-//) {
1756                         $s -= tz_to_s_offset($tz);
1757                 }
1758                 close $fh;
1759                 return $s;
1760         }
1761         die "Can't get commit time for commit: $cmt\n";
1764 sub tz_to_s_offset {
1765         my ($tz) = @_;
1766         $tz =~ s/(\d\d)$//;
1767         return ($1 * 60) + ($tz * 3600);
1770 # adapted from pager.c
1771 sub config_pager {
1772         $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
1773         if (!defined $_pager) {
1774                 $_pager = 'less';
1775         } elsif (length $_pager == 0 || $_pager eq 'cat') {
1776                 $_pager = undef;
1777         }
1780 sub run_pager {
1781         return unless -t *STDOUT;
1782         pipe my $rfd, my $wfd or return;
1783         defined(my $pid = fork) or croak $!;
1784         if (!$pid) {
1785                 open STDOUT, '>&', $wfd or croak $!;
1786                 return;
1787         }
1788         open STDIN, '<&', $rfd or croak $!;
1789         $ENV{LESS} ||= 'FRSX';
1790         exec $_pager or croak "Can't run pager: $! ($_pager)\n";
1793 sub get_author_info {
1794         my ($dest, $author, $t, $tz) = @_;
1795         $author =~ s/(?:^\s*|\s*$)//g;
1796         $dest->{a_raw} = $author;
1797         my $_a;
1798         if ($_authors) {
1799                 $_a = $rusers{$author} || undef;
1800         }
1801         if (!$_a) {
1802                 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
1803         }
1804         $dest->{t} = $t;
1805         $dest->{tz} = $tz;
1806         $dest->{a} = $_a;
1807         # Date::Parse isn't in the standard Perl distro :(
1808         if ($tz =~ s/^\+//) {
1809                 $t += tz_to_s_offset($tz);
1810         } elsif ($tz =~ s/^\-//) {
1811                 $t -= tz_to_s_offset($tz);
1812         }
1813         $dest->{t_utc} = $t;
1816 sub process_commit {
1817         my ($c, $r_min, $r_max, $defer) = @_;
1818         if (defined $r_min && defined $r_max) {
1819                 if ($r_min == $c->{r} && $r_min == $r_max) {
1820                         show_commit($c);
1821                         return 0;
1822                 }
1823                 return 1 if $r_min == $r_max;
1824                 if ($r_min < $r_max) {
1825                         # we need to reverse the print order
1826                         return 0 if (defined $_limit && --$_limit < 0);
1827                         push @$defer, $c;
1828                         return 1;
1829                 }
1830                 if ($r_min != $r_max) {
1831                         return 1 if ($r_min < $c->{r});
1832                         return 1 if ($r_max > $c->{r});
1833                 }
1834         }
1835         return 0 if (defined $_limit && --$_limit < 0);
1836         show_commit($c);
1837         return 1;
1840 sub show_commit {
1841         my $c = shift;
1842         if ($_oneline) {
1843                 my $x = "\n";
1844                 if (my $l = $c->{l}) {
1845                         while ($l->[0] =~ /^\s*$/) { shift @$l }
1846                         $x = $l->[0];
1847                 }
1848                 $_l_fmt ||= 'A' . length($c->{r});
1849                 print 'r',pack($_l_fmt, $c->{r}),' | ';
1850                 print "$c->{c} | " if $_show_commit;
1851                 print $x;
1852         } else {
1853                 show_commit_normal($c);
1854         }
1857 sub show_commit_changed_paths {
1858         my ($c) = @_;
1859         return unless $c->{changed};
1860         print "Changed paths:\n", @{$c->{changed}};
1863 sub show_commit_normal {
1864         my ($c) = @_;
1865         print '-' x72, "\nr$c->{r} | ";
1866         print "$c->{c} | " if $_show_commit;
1867         print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
1868                                  localtime($c->{t_utc})), ' | ';
1869         my $nr_line = 0;
1871         if (my $l = $c->{l}) {
1872                 while ($l->[$#$l] eq "\n" && $#$l > 0
1873                                           && $l->[($#$l - 1)] eq "\n") {
1874                         pop @$l;
1875                 }
1876                 $nr_line = scalar @$l;
1877                 if (!$nr_line) {
1878                         print "1 line\n\n\n";
1879                 } else {
1880                         if ($nr_line == 1) {
1881                                 $nr_line = '1 line';
1882                         } else {
1883                                 $nr_line .= ' lines';
1884                         }
1885                         print $nr_line, "\n";
1886                         show_commit_changed_paths($c);
1887                         print "\n";
1888                         print $_ foreach @$l;
1889                 }
1890         } else {
1891                 print "1 line\n";
1892                 show_commit_changed_paths($c);
1893                 print "\n";
1895         }
1896         foreach my $x (qw/raw diff/) {
1897                 if ($c->{$x}) {
1898                         print "\n";
1899                         print $_ foreach @{$c->{$x}}
1900                 }
1901         }
1904 package Git::SVN::Prompt;
1905 use strict;
1906 use warnings;
1907 require SVN::Core;
1908 use vars qw/$_no_auth_cache $_username/;
1910 sub simple {
1911         my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1912         $may_save = undef if $_no_auth_cache;
1913         $default_username = $_username if defined $_username;
1914         if (defined $default_username && length $default_username) {
1915                 if (defined $realm && length $realm) {
1916                         print STDERR "Authentication realm: $realm\n";
1917                         STDERR->flush;
1918                 }
1919                 $cred->username($default_username);
1920         } else {
1921                 username($cred, $realm, $may_save, $pool);
1922         }
1923         $cred->password(_read_password("Password for '" .
1924                                        $cred->username . "': ", $realm));
1925         $cred->may_save($may_save);
1926         $SVN::_Core::SVN_NO_ERROR;
1929 sub ssl_server_trust {
1930         my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1931         $may_save = undef if $_no_auth_cache;
1932         print STDERR "Error validating server certificate for '$realm':\n";
1933         if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1934                 print STDERR " - The certificate is not issued by a trusted ",
1935                       "authority. Use the\n",
1936                       "   fingerprint to validate the certificate manually!\n";
1937         }
1938         if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1939                 print STDERR " - The certificate hostname does not match.\n";
1940         }
1941         if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1942                 print STDERR " - The certificate is not yet valid.\n";
1943         }
1944         if ($failures & $SVN::Auth::SSL::EXPIRED) {
1945                 print STDERR " - The certificate has expired.\n";
1946         }
1947         if ($failures & $SVN::Auth::SSL::OTHER) {
1948                 print STDERR " - The certificate has an unknown error.\n";
1949         }
1950         printf STDERR
1951                 "Certificate information:\n".
1952                 " - Hostname: %s\n".
1953                 " - Valid: from %s until %s\n".
1954                 " - Issuer: %s\n".
1955                 " - Fingerprint: %s\n",
1956                 map $cert_info->$_, qw(hostname valid_from valid_until
1957                                        issuer_dname fingerprint);
1958         my $choice;
1959 prompt:
1960         print STDERR $may_save ?
1961               "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1962               "(R)eject or accept (t)emporarily? ";
1963         STDERR->flush;
1964         $choice = lc(substr(<STDIN> || 'R', 0, 1));
1965         if ($choice =~ /^t$/i) {
1966                 $cred->may_save(undef);
1967         } elsif ($choice =~ /^r$/i) {
1968                 return -1;
1969         } elsif ($may_save && $choice =~ /^p$/i) {
1970                 $cred->may_save($may_save);
1971         } else {
1972                 goto prompt;
1973         }
1974         $cred->accepted_failures($failures);
1975         $SVN::_Core::SVN_NO_ERROR;
1978 sub ssl_client_cert {
1979         my ($cred, $realm, $may_save, $pool) = @_;
1980         $may_save = undef if $_no_auth_cache;
1981         print STDERR "Client certificate filename: ";
1982         STDERR->flush;
1983         chomp(my $filename = <STDIN>);
1984         $cred->cert_file($filename);
1985         $cred->may_save($may_save);
1986         $SVN::_Core::SVN_NO_ERROR;
1989 sub ssl_client_cert_pw {
1990         my ($cred, $realm, $may_save, $pool) = @_;
1991         $may_save = undef if $_no_auth_cache;
1992         $cred->password(_read_password("Password: ", $realm));
1993         $cred->may_save($may_save);
1994         $SVN::_Core::SVN_NO_ERROR;
1997 sub username {
1998         my ($cred, $realm, $may_save, $pool) = @_;
1999         $may_save = undef if $_no_auth_cache;
2000         if (defined $realm && length $realm) {
2001                 print STDERR "Authentication realm: $realm\n";
2002         }
2003         my $username;
2004         if (defined $_username) {
2005                 $username = $_username;
2006         } else {
2007                 print STDERR "Username: ";
2008                 STDERR->flush;
2009                 chomp($username = <STDIN>);
2010         }
2011         $cred->username($username);
2012         $cred->may_save($may_save);
2013         $SVN::_Core::SVN_NO_ERROR;
2016 sub _read_password {
2017         my ($prompt, $realm) = @_;
2018         print STDERR $prompt;
2019         STDERR->flush;
2020         require Term::ReadKey;
2021         Term::ReadKey::ReadMode('noecho');
2022         my $password = '';
2023         while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2024                 last if $key =~ /[\012\015]/; # \n\r
2025                 $password .= $key;
2026         }
2027         Term::ReadKey::ReadMode('restore');
2028         print STDERR "\n";
2029         STDERR->flush;
2030         $password;
2033 package main;
2035 sub uri_encode {
2036         my ($f) = @_;
2037         $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2038         $f
2041 sub uri_decode {
2042         my ($f) = @_;
2043         $f =~ tr/+/ /;
2044         $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2045         $f
2048 sub libsvn_log_entry {
2049         my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2050         my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2051                                          (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2052                                 or die "Unable to parse date: $date\n";
2053         if (defined $author && length $author > 0 &&
2054             defined $_authors && ! defined $users{$author}) {
2055                 die "Author: $author not defined in $_authors file\n";
2056         }
2057         $msg = '' if ($rev == 0 && !defined $msg);
2059         open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2060         my $h;
2061         print $un "r$rev\n" or croak $!;
2062         $h = $untracked->{empty};
2063         foreach (sort keys %$h) {
2064                 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2065                 print $un "  $act: ", uri_encode($_), "\n" or croak $!;
2066                 warn "W: $act: $_\n";
2067         }
2068         foreach my $t (qw/dir_prop file_prop/) {
2069                 $h = $untracked->{$t} or next;
2070                 foreach my $path (sort keys %$h) {
2071                         my $ppath = $path eq '' ? '.' : $path;
2072                         foreach my $prop (sort keys %{$h->{$path}}) {
2073                                 next if $SKIP{$prop};
2074                                 my $v = $h->{$path}->{$prop};
2075                                 if (defined $v) {
2076                                         print $un "  +$t: ",
2077                                                   uri_encode($ppath), ' ',
2078                                                   uri_encode($prop), ' ',
2079                                                   uri_encode($v), "\n"
2080                                                   or croak $!;
2081                                 } else {
2082                                         print $un "  -$t: ",
2083                                                   uri_encode($ppath), ' ',
2084                                                   uri_encode($prop), "\n"
2085                                                   or croak $!;
2086                                 }
2087                         }
2088                 }
2089         }
2090         foreach my $t (qw/absent_file absent_directory/) {
2091                 $h = $untracked->{$t} or next;
2092                 foreach my $parent (sort keys %$h) {
2093                         foreach my $path (sort @{$h->{$parent}}) {
2094                                 print $un "  $t: ",
2095                                       uri_encode("$parent/$path"), "\n"
2096                                       or croak $!;
2097                                 warn "W: $t: $parent/$path ",
2098                                      "Insufficient permissions?\n";
2099                         }
2100                 }
2101         }
2103         # revprops (make this optional? it's an extra network trip...)
2104         my $rp = $SVN->rev_proplist($rev);
2105         foreach (sort keys %$rp) {
2106                 next if /^svn:(?:author|date|log)$/;
2107                 print $un "  rev_prop: ", uri_encode($_), ' ',
2108                           uri_encode($rp->{$_}), "\n";
2109         }
2110         close $un or croak $!;
2112         { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2113           author => $author, msg => $msg."\n", parents => $parents || [],
2114           revprops => $rp }
2117 sub libsvn_fetch {
2118         my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2119         my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2120         my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2121         unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2122                 die "SVN connection failed somewhere...\n";
2123         }
2124         libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2127 sub svn_grab_base_rev {
2128         my $c = eval { command_oneline([qw/rev-parse --verify/,
2129                                         "refs/remotes/$GIT_SVN^0"],
2130                                         { STDERR => 0 }) };
2131         if (defined $c && length $c) {
2132                 my ($url, $rev, $uuid) = cmt_metadata($c);
2133                 return ($rev, $c) if defined $rev;
2134         }
2135         if ($_no_metadata) {
2136                 my $offset = -41; # from tail
2137                 my $rl;
2138                 open my $fh, '<', $REVDB or
2139                         die "--no-metadata specified and $REVDB not readable\n";
2140                 seek $fh, $offset, 2;
2141                 $rl = readline $fh;
2142                 defined $rl or return (undef, undef);
2143                 chomp $rl;
2144                 while ($c ne $rl && tell $fh != 0) {
2145                         $offset -= 41;
2146                         seek $fh, $offset, 2;
2147                         $rl = readline $fh;
2148                         defined $rl or return (undef, undef);
2149                         chomp $rl;
2150                 }
2151                 my $rev = tell $fh;
2152                 croak $! if ($rev < -1);
2153                 $rev =  ($rev - 41) / 41;
2154                 close $fh or croak $!;
2155                 return ($rev, $c);
2156         }
2157         return (undef, undef);
2160 sub libsvn_parse_revision {
2161         my $base = shift;
2162         my $head = $SVN->get_latest_revnum();
2163         if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2164                 return ($base + 1, $head) if (defined $base);
2165                 return (0, $head);
2166         }
2167         return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2168         return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2169         if ($_revision =~ /^BASE:(\d+)$/) {
2170                 return ($base + 1, $1) if (defined $base);
2171                 return (0, $head);
2172         }
2173         return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2174         die "revision argument: $_revision not understood by git-svn\n",
2175                 "Try using the command-line svn client instead\n";
2178 sub libsvn_traverse_ignore {
2179         my ($fh, $path, $r) = @_;
2180         $path =~ s#^/+##g;
2181         my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2182         my $p = $path;
2183         $p =~ s#^\Q$SVN->{svn_path}\E/##;
2184         print $fh length $p ? "\n# $p\n" : "\n# /\n";
2185         if (my $s = $props->{'svn:ignore'}) {
2186                 $s =~ s/[\r\n]+/\n/g;
2187                 chomp $s;
2188                 if (length $p == 0) {
2189                         $s =~ s#\n#\n/$p#g;
2190                         print $fh "/$s\n";
2191                 } else {
2192                         $s =~ s#\n#\n/$p/#g;
2193                         print $fh "/$p/$s\n";
2194                 }
2195         }
2196         foreach (sort keys %$dirent) {
2197                 next if $dirent->{$_}->kind != $SVN::Node::dir;
2198                 libsvn_traverse_ignore($fh, "$path/$_", $r);
2199         }
2202 sub revisions_eq {
2203         my ($path, $r0, $r1) = @_;
2204         return 1 if $r0 == $r1;
2205         my $nr = 0;
2206         # should be OK to use Pool here (r1 - r0) should be small
2207         $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2208         return 0 if ($nr > 1);
2209         return 1;
2212 sub libsvn_find_parent_branch {
2213         my ($paths, $rev, $author, $date, $msg) = @_;
2214         my $svn_path = '/'.$SVN->{svn_path};
2216         # look for a parent from another branch:
2217         my $i = $paths->{$svn_path} or return;
2218         my $branch_from = $i->copyfrom_path or return;
2219         my $r = $i->copyfrom_rev;
2220         print STDERR  "Found possible branch point: ",
2221                                 "$branch_from => $svn_path, $r\n";
2222         $branch_from =~ s#^/##;
2223         my $l_map = {};
2224         read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2225         my $url = $SVN->{repos_root};
2226         defined $l_map->{$url} or return;
2227         my $id = $l_map->{$url}->{$branch_from};
2228         if (!defined $id && $_follow_parent) {
2229                 print STDERR "Following parent: $branch_from\@$r\n";
2230                 # auto create a new branch and follow it
2231                 $id = basename($branch_from);
2232                 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2233                 while (-r "$GIT_DIR/svn/$id") {
2234                         # just grow a tail if we're not unique enough :x
2235                         $id .= '-';
2236                 }
2237         }
2238         return unless defined $id;
2240         my ($r0, $parent) = find_rev_before($r,$id,1);
2241         if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2242                 defined(my $pid = fork) or croak $!;
2243                 if (!$pid) {
2244                         $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2245                         init_vars();
2246                         $SVN_URL = "$url/$branch_from";
2247                         $SVN = undef;
2248                         setup_git_svn();
2249                         # we can't assume SVN_URL exists at r+1:
2250                         $_revision = "0:$r";
2251                         fetch_lib();
2252                         exit 0;
2253                 }
2254                 waitpid $pid, 0;
2255                 croak $? if $?;
2256                 ($r0, $parent) = find_rev_before($r,$id,1);
2257         }
2258         return unless (defined $r0 && defined $parent);
2259         if (revisions_eq($branch_from, $r0, $r)) {
2260                 unlink $GIT_SVN_INDEX;
2261                 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2262                 command_noisy('read-tree', $parent);
2263                 unless ($SVN->can_do_switch) {
2264                         return _libsvn_new_tree($paths, $rev, $author, $date,
2265                                                 $msg, [$parent]);
2266                 }
2267                 # do_switch works with svn/trunk >= r22312, but that is not
2268                 # included with SVN 1.4.2 (the latest version at the moment),
2269                 # so we can't rely on it.
2270                 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2271                 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2272                 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2273                                    die "SVN connection failed somewhere...\n";
2274                 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2275         }
2276         print STDERR "Nope, branch point not imported or unknown\n";
2277         return undef;
2280 sub libsvn_new_tree {
2281         if (my $log_entry = libsvn_find_parent_branch(@_)) {
2282                 return $log_entry;
2283         }
2284         my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2285         _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2288 sub _libsvn_new_tree {
2289         my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2290         my $ed = SVN::Git::Fetcher->new({q => $_q});
2291         unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2292                 die "SVN connection failed somewhere...\n";
2293         }
2294         libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2297 sub find_graft_path_commit {
2298         my ($tree_paths, $p1, $r1) = @_;
2299         foreach my $x (keys %$tree_paths) {
2300                 next unless ($p1 =~ /^\Q$x\E/);
2301                 my $i = $tree_paths->{$x};
2302                 my ($r0, $parent) = find_rev_before($r1,$i,1);
2303                 return $parent if (defined $r0 && $r0 == $r1);
2304                 print STDERR "r$r1 of $i not imported\n";
2305                 next;
2306         }
2307         return undef;
2310 sub find_graft_path_parents {
2311         my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2312         foreach my $x (keys %$tree_paths) {
2313                 next unless ($p0 =~ /^\Q$x\E/);
2314                 my $i = $tree_paths->{$x};
2315                 my ($r, $parent) = find_rev_before($r0, $i, 1);
2316                 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2317                         my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2318                         my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2319                         next if ($url_a && $url_b && $url_a eq $url_b &&
2320                                                         $uuid_b eq $uuid_a);
2321                         $grafts->{$c}->{$parent} = 1;
2322                 }
2323         }
2326 sub libsvn_graft_file_copies {
2327         my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2328         foreach (keys %$paths) {
2329                 my $i = $paths->{$_};
2330                 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2331                                         $i->copyfrom_rev);
2332                 next unless (defined $p0 && defined $r0);
2334                 my $p1 = $_;
2335                 $p1 =~ s#^/##;
2336                 $p0 =~ s#^/##;
2337                 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2338                 next unless $c;
2339                 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2340         }
2343 sub set_index {
2344         my $old = $ENV{GIT_INDEX_FILE};
2345         $ENV{GIT_INDEX_FILE} = shift;
2346         return $old;
2349 sub restore_index {
2350         my ($old) = @_;
2351         if (defined $old) {
2352                 $ENV{GIT_INDEX_FILE} = $old;
2353         } else {
2354                 delete $ENV{GIT_INDEX_FILE};
2355         }
2358 sub libsvn_commit_cb {
2359         my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2360         if ($_optimize_commits && $rev == ($r_last + 1)) {
2361                 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2362                 $log->{tree} = get_tree_from_treeish($c);
2363                 my $cmt = git_commit($log, $cmt_last, $c);
2364                 my @diff = command('diff-tree', $cmt, $c);
2365                 if (@diff) {
2366                         print STDERR "Trees differ: $cmt $c\n",
2367                                         join('',@diff),"\n";
2368                         exit 1;
2369                 }
2370         } else {
2371                 fetch("$rev=$c");
2372         }
2375 sub libsvn_ls_fullurl {
2376         my $fullurl = shift;
2377         my $ra = Git::SVN::Ra->new($fullurl);
2378         my @ret;
2379         my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
2380         my ($dirent, undef, undef) = $ra->get_dir('', $r);
2381         foreach my $d (sort keys %$dirent) {
2382                 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2383                         push @ret, "$d/"; # add '/' for compat with cli svn
2384                 }
2385         }
2386         return @ret;
2389 sub libsvn_skip_unknown_revs {
2390         my $err = shift;
2391         my $errno = $err->apr_err();
2392         # Maybe the branch we're tracking didn't
2393         # exist when the repo started, so it's
2394         # not an error if it doesn't, just continue
2395         #
2396         # Wonderfully consistent library, eh?
2397         # 160013 - svn:// and file://
2398         # 175002 - http(s)://
2399         # 175007 - http(s):// (this repo required authorization, too...)
2400         #   More codes may be discovered later...
2401         if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2402                 return;
2403         }
2404         croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2405 };
2407 # Tie::File seems to be prone to offset errors if revisions get sparse,
2408 # it's not that fast, either.  Tie::File is also not in Perl 5.6.  So
2409 # one of my favorite modules is out :<  Next up would be one of the DBM
2410 # modules, but I'm not sure which is most portable...  So I'll just
2411 # go with something that's plain-text, but still capable of
2412 # being randomly accessed.  So here's my ultra-simple fixed-width
2413 # database.  All records are 40 characters + "\n", so it's easy to seek
2414 # to a revision: (41 * rev) is the byte offset.
2415 # A record of 40 0s denotes an empty revision.
2416 # And yes, it's still pretty fast (faster than Tie::File).
2417 sub revdb_set {
2418         my ($file, $rev, $commit) = @_;
2419         length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2420         open my $fh, '+<', $file or croak $!;
2421         my $offset = $rev * 41;
2422         # assume that append is the common case:
2423         seek $fh, 0, 2 or croak $!;
2424         my $pos = tell $fh;
2425         if ($pos < $offset) {
2426                 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2427         }
2428         seek $fh, $offset, 0 or croak $!;
2429         print $fh $commit,"\n";
2430         close $fh or croak $!;
2433 sub revdb_get {
2434         my ($file, $rev) = @_;
2435         my $ret;
2436         my $offset = $rev * 41;
2437         open my $fh, '<', $file or croak $!;
2438         seek $fh, $offset, 0;
2439         if (tell $fh == $offset) {
2440                 $ret = readline $fh;
2441                 if (defined $ret) {
2442                         chomp $ret;
2443                         $ret = undef if ($ret =~ /^0{40}$/);
2444                 }
2445         }
2446         close $fh or croak $!;
2447         return $ret;
2450 sub copy_remote_ref {
2451         my $origin = $_cp_remote ? $_cp_remote : 'origin';
2452         my $ref = "refs/remotes/$GIT_SVN";
2453         if (command('ls-remote', $origin, $ref)) {
2454                 command_noisy('fetch', $origin, "$ref:$ref");
2455         } elsif ($_cp_remote && !$_upgrade) {
2456                 die "Unable to find remote reference: ",
2457                                 "refs/remotes/$GIT_SVN on $origin\n";
2458         }
2462         my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2463                                 $SVN::Node::dir.$SVN::Node::unknown.
2464                                 $SVN::Node::none.$SVN::Node::file.
2465                                 $SVN::Node::dir.$SVN::Node::unknown.
2466                                 $SVN::Auth::SSL::CNMISMATCH.
2467                                 $SVN::Auth::SSL::NOTYETVALID.
2468                                 $SVN::Auth::SSL::EXPIRED.
2469                                 $SVN::Auth::SSL::UNKNOWNCA.
2470                                 $SVN::Auth::SSL::OTHER;
2473 package SVN::Git::Fetcher;
2474 use vars qw/@ISA/;
2475 use strict;
2476 use warnings;
2477 use Carp qw/croak/;
2478 use IO::File qw//;
2479 use Git qw/command command_oneline command_noisy
2480            command_output_pipe command_input_pipe command_close_pipe/;
2482 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2483 sub new {
2484         my ($class, $git_svn) = @_;
2485         my $self = SVN::Delta::Editor->new;
2486         bless $self, $class;
2487         $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2488         $self->{q} = $git_svn->{q};
2489         $self->{empty} = {};
2490         $self->{dir_prop} = {};
2491         $self->{file_prop} = {};
2492         $self->{absent_dir} = {};
2493         $self->{absent_file} = {};
2494         ($self->{gui}, $self->{ctx}) = command_input_pipe(
2495                                              qw/update-index -z --index-info/);
2496         require Digest::MD5;
2497         $self;
2500 sub open_root {
2501         { path => '' };
2504 sub open_directory {
2505         my ($self, $path, $pb, $rev) = @_;
2506         { path => $path };
2509 sub delete_entry {
2510         my ($self, $path, $rev, $pb) = @_;
2511         my $gui = $self->{gui};
2513         # remove entire directories.
2514         if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2515                 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2516                                                      -r --name-only -z/,
2517                                                      $self->{c}, '--', $path);
2518                 local $/ = "\0";
2519                 while (<$ls>) {
2520                         print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2521                         print "\tD\t$_\n" unless $self->{q};
2522                 }
2523                 print "\tD\t$path/\n" unless $self->{q};
2524                 command_close_pipe($ls, $ctx);
2525                 $self->{empty}->{$path} = 0
2526         } else {
2527                 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
2528                 print "\tD\t$path\n" unless $self->{q};
2529         }
2530         undef;
2533 sub open_file {
2534         my ($self, $path, $pb, $rev) = @_;
2535         my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
2536                              =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2537         unless (defined $mode && defined $blob) {
2538                 die "$path was not found in commit $self->{c} (r$rev)\n";
2539         }
2540         { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2541           pool => SVN::Pool->new, action => 'M' };
2544 sub add_file {
2545         my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2546         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2547         delete $self->{empty}->{$dir};
2548         { path => $path, mode_a => 100644, mode_b => 100644,
2549           pool => SVN::Pool->new, action => 'A' };
2552 sub add_directory {
2553         my ($self, $path, $cp_path, $cp_rev) = @_;
2554         my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2555         delete $self->{empty}->{$dir};
2556         $self->{empty}->{$path} = 1;
2557         { path => $path };
2560 sub change_dir_prop {
2561         my ($self, $db, $prop, $value) = @_;
2562         $self->{dir_prop}->{$db->{path}} ||= {};
2563         $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2564         undef;
2567 sub absent_directory {
2568         my ($self, $path, $pb) = @_;
2569         $self->{absent_dir}->{$pb->{path}} ||= [];
2570         push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2571         undef;
2574 sub absent_file {
2575         my ($self, $path, $pb) = @_;
2576         $self->{absent_file}->{$pb->{path}} ||= [];
2577         push @{$self->{absent_file}->{$pb->{path}}}, $path;
2578         undef;
2581 sub change_file_prop {
2582         my ($self, $fb, $prop, $value) = @_;
2583         if ($prop eq 'svn:executable') {
2584                 if ($fb->{mode_b} != 120000) {
2585                         $fb->{mode_b} = defined $value ? 100755 : 100644;
2586                 }
2587         } elsif ($prop eq 'svn:special') {
2588                 $fb->{mode_b} = defined $value ? 120000 : 100644;
2589         } else {
2590                 $self->{file_prop}->{$fb->{path}} ||= {};
2591                 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2592         }
2593         undef;
2596 sub apply_textdelta {
2597         my ($self, $fb, $exp) = @_;
2598         my $fh = IO::File->new_tmpfile;
2599         $fh->autoflush(1);
2600         # $fh gets auto-closed() by SVN::TxDelta::apply(),
2601         # (but $base does not,) so dup() it for reading in close_file
2602         open my $dup, '<&', $fh or croak $!;
2603         my $base = IO::File->new_tmpfile;
2604         $base->autoflush(1);
2605         if ($fb->{blob}) {
2606                 defined (my $pid = fork) or croak $!;
2607                 if (!$pid) {
2608                         open STDOUT, '>&', $base or croak $!;
2609                         print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2610                         exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2611                 }
2612                 waitpid $pid, 0;
2613                 croak $? if $?;
2615                 if (defined $exp) {
2616                         seek $base, 0, 0 or croak $!;
2617                         my $md5 = Digest::MD5->new;
2618                         $md5->addfile($base);
2619                         my $got = $md5->hexdigest;
2620                         die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2621                             "expected: $exp\n",
2622                             "     got: $got\n" if ($got ne $exp);
2623                 }
2624         }
2625         seek $base, 0, 0 or croak $!;
2626         $fb->{fh} = $dup;
2627         $fb->{base} = $base;
2628         [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2631 sub close_file {
2632         my ($self, $fb, $exp) = @_;
2633         my $hash;
2634         my $path = $fb->{path};
2635         if (my $fh = $fb->{fh}) {
2636                 seek($fh, 0, 0) or croak $!;
2637                 my $md5 = Digest::MD5->new;
2638                 $md5->addfile($fh);
2639                 my $got = $md5->hexdigest;
2640                 die "Checksum mismatch: $path\n",
2641                     "expected: $exp\n    got: $got\n" if ($got ne $exp);
2642                 seek($fh, 0, 0) or croak $!;
2643                 if ($fb->{mode_b} == 120000) {
2644                         read($fh, my $buf, 5) == 5 or croak $!;
2645                         $buf eq 'link ' or die "$path has mode 120000",
2646                                                "but is not a link\n";
2647                 }
2648                 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2649                 if (!$pid) {
2650                         open STDIN, '<&', $fh or croak $!;
2651                         exec qw/git-hash-object -w --stdin/ or croak $!;
2652                 }
2653                 chomp($hash = do { local $/; <$out> });
2654                 close $out or croak $!;
2655                 close $fh or croak $!;
2656                 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2657                 close $fb->{base} or croak $!;
2658         } else {
2659                 $hash = $fb->{blob} or die "no blob information\n";
2660         }
2661         $fb->{pool}->clear;
2662         my $gui = $self->{gui};
2663         print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
2664         print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
2665         undef;
2668 sub abort_edit {
2669         my $self = shift;
2670         eval { command_close_pipe($self->{gui}, $self->{ctx}) };
2671         $self->SUPER::abort_edit(@_);
2674 sub close_edit {
2675         my $self = shift;
2676         command_close_pipe($self->{gui}, $self->{ctx});
2677         $self->{git_commit_ok} = 1;
2678         $self->SUPER::close_edit(@_);
2681 package SVN::Git::Editor;
2682 use vars qw/@ISA/;
2683 use strict;
2684 use warnings;
2685 use Carp qw/croak/;
2686 use IO::File;
2687 use Git qw/command command_oneline command_noisy
2688            command_output_pipe command_input_pipe command_close_pipe/;
2690 sub new {
2691         my $class = shift;
2692         my $git_svn = shift;
2693         my $self = SVN::Delta::Editor->new(@_);
2694         bless $self, $class;
2695         foreach (qw/svn_path c r ra /) {
2696                 die "$_ required!\n" unless (defined $git_svn->{$_});
2697                 $self->{$_} = $git_svn->{$_};
2698         }
2699         $self->{pool} = SVN::Pool->new;
2700         $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2701         $self->{rm} = { };
2702         require Digest::MD5;
2703         return $self;
2706 sub split_path {
2707         return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2710 sub repo_path {
2711         (defined $_[1] && length $_[1]) ? $_[1] : ''
2714 sub url_path {
2715         my ($self, $path) = @_;
2716         $self->{ra}->{url} . '/' . $self->repo_path($path);
2719 sub rmdirs {
2720         my ($self, $q) = @_;
2721         my $rm = $self->{rm};
2722         delete $rm->{''}; # we never delete the url we're tracking
2723         return unless %$rm;
2725         foreach (keys %$rm) {
2726                 my @d = split m#/#, $_;
2727                 my $c = shift @d;
2728                 $rm->{$c} = 1;
2729                 while (@d) {
2730                         $c .= '/' . shift @d;
2731                         $rm->{$c} = 1;
2732                 }
2733         }
2734         delete $rm->{$self->{svn_path}};
2735         delete $rm->{''}; # we never delete the url we're tracking
2736         return unless %$rm;
2738         my ($fh, $ctx) = command_output_pipe(
2739                                    qw/ls-tree --name-only -r -z/, $self->{c});
2740         local $/ = "\0";
2741         while (<$fh>) {
2742                 chomp;
2743                 my @dn = split m#/#, $_;
2744                 while (pop @dn) {
2745                         delete $rm->{join '/', @dn};
2746                 }
2747                 unless (%$rm) {
2748                         close $fh;
2749                         return;
2750                 }
2751         }
2752         command_close_pipe($fh, $ctx);
2754         my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2755         foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2756                 $self->close_directory($bat->{$d}, $p);
2757                 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2758                 print "\tD+\t$d/\n" unless $q;
2759                 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2760                 delete $bat->{$d};
2761         }
2764 sub open_or_add_dir {
2765         my ($self, $full_path, $baton) = @_;
2766         my $t = $self->{ra}->check_path($full_path, $self->{r});
2767         if ($t == $SVN::Node::none) {
2768                 return $self->add_directory($full_path, $baton,
2769                                                 undef, -1, $self->{pool});
2770         } elsif ($t == $SVN::Node::dir) {
2771                 return $self->open_directory($full_path, $baton,
2772                                                 $self->{r}, $self->{pool});
2773         }
2774         print STDERR "$full_path already exists in repository at ",
2775                 "r$self->{r} and it is not a directory (",
2776                 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2777         exit 1;
2780 sub ensure_path {
2781         my ($self, $path) = @_;
2782         my $bat = $self->{bat};
2783         $path = $self->repo_path($path);
2784         return $bat->{''} unless (length $path);
2785         my @p = split m#/+#, $path;
2786         my $c = shift @p;
2787         $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2788         while (@p) {
2789                 my $c0 = $c;
2790                 $c .= '/' . shift @p;
2791                 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2792         }
2793         return $bat->{$c};
2796 sub A {
2797         my ($self, $m, $q) = @_;
2798         my ($dir, $file) = split_path($m->{file_b});
2799         my $pbat = $self->ensure_path($dir);
2800         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2801                                         undef, -1);
2802         print "\tA\t$m->{file_b}\n" unless $q;
2803         $self->chg_file($fbat, $m);
2804         $self->close_file($fbat,undef,$self->{pool});
2807 sub C {
2808         my ($self, $m, $q) = @_;
2809         my ($dir, $file) = split_path($m->{file_b});
2810         my $pbat = $self->ensure_path($dir);
2811         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2812                                 $self->url_path($m->{file_a}), $self->{r});
2813         print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
2814         $self->chg_file($fbat, $m);
2815         $self->close_file($fbat,undef,$self->{pool});
2818 sub delete_entry {
2819         my ($self, $path, $pbat) = @_;
2820         my $rpath = $self->repo_path($path);
2821         my ($dir, $file) = split_path($rpath);
2822         $self->{rm}->{$dir} = 1;
2823         $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2826 sub R {
2827         my ($self, $m, $q) = @_;
2828         my ($dir, $file) = split_path($m->{file_b});
2829         my $pbat = $self->ensure_path($dir);
2830         my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2831                                 $self->url_path($m->{file_a}), $self->{r});
2832         print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
2833         $self->chg_file($fbat, $m);
2834         $self->close_file($fbat,undef,$self->{pool});
2836         ($dir, $file) = split_path($m->{file_a});
2837         $pbat = $self->ensure_path($dir);
2838         $self->delete_entry($m->{file_a}, $pbat);
2841 sub M {
2842         my ($self, $m, $q) = @_;
2843         my ($dir, $file) = split_path($m->{file_b});
2844         my $pbat = $self->ensure_path($dir);
2845         my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2846                                 $pbat,$self->{r},$self->{pool});
2847         print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
2848         $self->chg_file($fbat, $m);
2849         $self->close_file($fbat,undef,$self->{pool});
2852 sub T { shift->M(@_) }
2854 sub change_file_prop {
2855         my ($self, $fbat, $pname, $pval) = @_;
2856         $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2859 sub chg_file {
2860         my ($self, $fbat, $m) = @_;
2861         if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2862                 $self->change_file_prop($fbat,'svn:executable','*');
2863         } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2864                 $self->change_file_prop($fbat,'svn:executable',undef);
2865         }
2866         my $fh = IO::File->new_tmpfile or croak $!;
2867         if ($m->{mode_b} =~ /^120/) {
2868                 print $fh 'link ' or croak $!;
2869                 $self->change_file_prop($fbat,'svn:special','*');
2870         } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2871                 $self->change_file_prop($fbat,'svn:special',undef);
2872         }
2873         defined(my $pid = fork) or croak $!;
2874         if (!$pid) {
2875                 open STDOUT, '>&', $fh or croak $!;
2876                 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2877         }
2878         waitpid $pid, 0;
2879         croak $? if $?;
2880         $fh->flush == 0 or croak $!;
2881         seek $fh, 0, 0 or croak $!;
2883         my $md5 = Digest::MD5->new;
2884         $md5->addfile($fh) or croak $!;
2885         seek $fh, 0, 0 or croak $!;
2887         my $exp = $md5->hexdigest;
2888         my $pool = SVN::Pool->new;
2889         my $atd = $self->apply_textdelta($fbat, undef, $pool);
2890         my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2891         die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2892         $pool->clear;
2894         close $fh or croak $!;
2897 sub D {
2898         my ($self, $m, $q) = @_;
2899         my ($dir, $file) = split_path($m->{file_b});
2900         my $pbat = $self->ensure_path($dir);
2901         print "\tD\t$m->{file_b}\n" unless $q;
2902         $self->delete_entry($m->{file_b}, $pbat);
2905 sub close_edit {
2906         my ($self) = @_;
2907         my ($p,$bat) = ($self->{pool}, $self->{bat});
2908         foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2909                 $self->close_directory($bat->{$_}, $p);
2910         }
2911         $self->SUPER::close_edit($p);
2912         $p->clear;
2915 sub abort_edit {
2916         my ($self) = @_;
2917         $self->SUPER::abort_edit($self->{pool});
2918         $self->{pool}->clear;
2921 package Git::SVN::Ra;
2922 use vars qw/@ISA $config_dir/;
2923 use strict;
2924 use warnings;
2925 my ($can_do_switch);
2927 BEGIN {
2928         # enforce temporary pool usage for some simple functions
2929         my $e;
2930         foreach (qw/get_latest_revnum rev_proplist get_file
2931                     check_path get_dir get_uuid get_repos_root/) {
2932                 $e .= "sub $_ {
2933                         my \$self = shift;
2934                         my \$pool = SVN::Pool->new;
2935                         my \@ret = \$self->SUPER::$_(\@_,\$pool);
2936                         \$pool->clear;
2937                         wantarray ? \@ret : \$ret[0]; }\n";
2938         }
2939         eval $e;
2942 sub new {
2943         my ($class, $url) = @_;
2944         SVN::_Core::svn_config_ensure($config_dir, undef);
2945         my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2946             SVN::Client::get_simple_provider(),
2947             SVN::Client::get_ssl_server_trust_file_provider(),
2948             SVN::Client::get_simple_prompt_provider(
2949               \&Git::SVN::Prompt::simple, 2),
2950             SVN::Client::get_ssl_client_cert_prompt_provider(
2951               \&Git::SVN::Prompt::ssl_client_cert, 2),
2952             SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2953               \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2954             SVN::Client::get_username_provider(),
2955             SVN::Client::get_ssl_server_trust_prompt_provider(
2956               \&Git::SVN::Prompt::ssl_server_trust),
2957             SVN::Client::get_username_prompt_provider(
2958               \&Git::SVN::Prompt::username, 2),
2959           ]);
2960         my $config = SVN::Core::config_get_config($config_dir);
2961         my $self = SVN::Ra->new(url => $url, auth => $baton,
2962                               config => $config,
2963                               pool => SVN::Pool->new,
2964                               auth_provider_callbacks => $callbacks);
2965         $self->{svn_path} = $url;
2966         $self->{repos_root} = $self->get_repos_root;
2967         $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2968         bless $self, $class;
2971 sub DESTROY {
2972         my $self = shift;
2973         $self->{pool}->clear if $self->{pool};
2974         $self->SUPER::DESTROY(@_);
2977 sub dup {
2978         my ($self) = @_;
2979         my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2980                                 map { $_ => $self->{$_} } qw/config url
2981                      auth auth_provider_callbacks repos_root svn_path/);
2982         bless $dup, ref $self;
2985 sub get_log {
2986         my ($self, @args) = @_;
2987         my $pool = SVN::Pool->new;
2988         $args[4]-- if $args[4] && ! $::_follow_parent;
2989         splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2990         my $ret = $self->SUPER::get_log(@args, $pool);
2991         $pool->clear;
2992         $ret;
2995 sub get_commit_editor {
2996         my ($self, $msg, $cb, $pool) = @_;
2997         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2998         $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3001 sub uuid {
3002         my ($self) = @_;
3003         $self->{uuid} ||= $self->get_uuid;
3006 sub gs_do_update {
3007         my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3008         my $pool = SVN::Pool->new;
3009         my $reporter = $self->do_update($rev_b, $path, $recurse,
3010                                         $editor, $pool);
3011         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3012         my $new = ($rev_a == $rev_b);
3013         $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3014         $reporter->finish_report($pool);
3015         $pool->clear;
3016         $editor->{git_commit_ok};
3019 sub gs_do_switch {
3020         my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3021         my $pool = SVN::Pool->new;
3022         my $reporter = $self->do_switch($rev_b, $path, $recurse,
3023                                         $url_b, $editor, $pool);
3024         my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3025         $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3026         $reporter->finish_report($pool);
3027         $pool->clear;
3028         $editor->{git_commit_ok};
3031 sub can_do_switch {
3032         my $self = shift;
3033         unless (defined $can_do_switch) {
3034                 my $pool = SVN::Pool->new;
3035                 my $rep = eval {
3036                         $self->do_switch(1, '', 0, $self->{url},
3037                                          SVN::Delta::Editor->new, $pool);
3038                 };
3039                 if ($@) {
3040                         $can_do_switch = 0;
3041                 } else {
3042                         $rep->abort_report($pool);
3043                         $can_do_switch = 1;
3044                 }
3045                 $pool->clear;
3046         }
3047         $can_do_switch;
3050 __END__
3052 Data structures:
3054 $log_msg hashref as returned by libsvn_log_entry()
3056         msg => 'whitespace-formatted log entry
3057 ',                                              # trailing newline is preserved
3058         revision => '8',                        # integer
3059         date => '2004-02-24T17:01:44.108345Z',  # commit date
3060         author => 'committer name'
3061 };
3063 @mods = array of diff-index line hashes, each element represents one line
3064         of diff-index output
3066 diff-index line ($m hash)
3068         mode_a => first column of diff-index output, no leading ':',
3069         mode_b => second column of diff-index output,
3070         sha1_b => sha1sum of the final blob,
3071         chg => change type [MCRADT],
3072         file_a => original file name of a file (iff chg is 'C' or 'R')
3073         file_b => new/current file name of a file (any chg)
3077 # retval of read_url_paths{,_all}();
3078 $l_map = {
3079         # repository root url
3080         'https://svn.musicpd.org' => {
3081                 # repository path               # GIT_SVN_ID
3082                 'mpd/trunk'             =>      'trunk',
3083                 'mpd/tags/0.11.5'       =>      'tags/0.11.5',
3084         },
3087 Notes:
3088         I don't trust the each() function on unless I created %hash myself
3089         because the internal iterator may not have started at base.