2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
17 my $LC_ALL = $ENV{LC_ALL};
19 # make sure the svn binary gives consistent output between locales and TZs:
22 $| = 1; # unbuffer STDOUT
24 # properties that we do not log:
25 my %SKIP = ( 'svn:wc:ra_dav:version-url' => 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,
34 sub fatal (@) { print STDERR @_; exit 1 }
35 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
38 if ($SVN::Core::VERSION lt '1.1.0') {
39 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
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';
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/;
53 memoize('revisions_eq');
54 memoize('cmt_metadata');
55 memoize('get_commit_time');
59 foreach (qw/command command_oneline command_noisy command_output_pipe
60 command_input_pipe command_close_pipe/) {
61 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
69 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
70 my $sha1 = qr/[a-f\d]{40}/;
71 my $sha1_short = qr/[a-f\d]{4,40}/;
72 my $_esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
73 my ($_revision,$_stdin,$_help,$_rmdir,$_edit,
74 $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
75 $_repack, $_repack_nr, $_repack_flags, $_q,
76 $_message, $_file, $_no_metadata,
77 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
78 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
79 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m,
80 $_merge, $_strategy, $_dry_run, $_ignore_nodate, $_non_recursive,
81 $_pager, $_color, $_prefix);
82 my (@_branch_from, %tree_map, %users, %rusers);
83 my @repo_path_split_cache;
84 use vars qw/$_follow_parent/;
86 my %fc_opts = ( 'branch|b=s' => \@_branch_from,
87 'follow-parent|follow' => \$_follow_parent,
88 'branch-all-refs|B' => \$_branch_all_refs,
89 'authors-file|A=s' => \$_authors,
90 'repack:i' => \$_repack,
91 'no-metadata' => \$_no_metadata,
93 'username=s' => \$Git::SVN::Prompt::_username,
94 'config-dir=s' => \$Git::SVN::Ra::config_dir,
95 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96 'ignore-nodate' => \$_ignore_nodate,
97 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
99 my ($_trunk, $_tags, $_branches);
100 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
101 'tags|t=s' => \$_tags,
102 'branches|b=s' => \$_branches );
103 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
104 my %cmt_opts = ( 'edit|e' => \$_edit,
106 'find-copies-harder' => \$_find_copies_harder,
108 'copy-similarity|C=i'=> \$_cp_similarity
112 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
113 { 'revision|r=s' => \$_revision, %fc_opts } ],
114 init => [ \&init, "Initialize a repo for tracking" .
115 " (requires URL argument)",
117 dcommit => [ \&dcommit, 'Commit several diffs to merge with upstream',
118 { 'merge|m|M' => \$_merge,
119 'strategy|s=s' => \$_strategy,
120 'dry-run|n' => \$_dry_run,
121 %cmt_opts, %fc_opts } ],
122 'set-tree' => [ \&commit, "Set an SVN repository to a git tree-ish",
123 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
124 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
125 { 'revision|r=i' => \$_revision } ],
126 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
127 { 'copy-remote|remote=s' => \$_cp_remote,
128 'upgrade' => \$_upgrade } ],
129 'graft-branches' => [ \&graft_branches,
130 'Detect merges/branches from already imported history',
131 { 'merge-rx|m' => \@_opt_m,
132 'branch|b=s' => \@_branch_from,
133 'branch-all-refs|B' => \$_branch_all_refs,
134 'no-default-regex' => \$_no_default_regex,
135 'no-graft-copy' => \$_no_graft_copy } ],
136 'multi-init' => [ \&multi_init,
137 'Initialize multiple trees (like git-svnimport)',
138 { %multi_opts, %init_opts,
139 'revision|r=i' => \$_revision,
140 'username=s' => \$Git::SVN::Prompt::_username,
141 'config-dir=s' => \$Git::SVN::Ra::config_dir,
142 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
143 'prefix=s' => \$_prefix,
145 'multi-fetch' => [ \&multi_fetch,
146 'Fetch multiple trees (like git-svnimport)',
148 'log' => [ \&show_log, 'Show commit logs',
149 { 'limit=i' => \$_limit,
150 'revision|r=s' => \$_revision,
151 'verbose|v' => \$_verbose,
152 'incremental' => \$_incremental,
153 'oneline' => \$_oneline,
154 'show-commit' => \$_show_commit,
155 'non-recursive' => \$_non_recursive,
156 'authors-file|A=s' => \$_authors,
158 'pager=s' => \$_pager,
160 'commit-diff' => [ \&commit_diff, 'Commit a diff between two trees',
161 { 'message|m=s' => \$_message,
162 'file|F=s' => \$_file,
163 'revision|r=s' => \$_revision,
168 for (my $i = 0; $i < @ARGV; $i++) {
169 if (defined $cmd{$ARGV[$i]}) {
176 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
178 read_repo_config(\%opts);
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
180 'version|V' => \$_version,
181 'id|i=s' => \$GIT_SVN);
182 exit 1 if (!$rv && $cmd ne 'log');
186 version() if $_version;
187 usage(1) unless defined $cmd;
189 load_authors() if $_authors;
190 load_all_refs() if $_branch_all_refs;
191 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/;
192 $cmd{$cmd}->[0]->(@ARGV);
195 ####################### primary functions ######################
197 my $exit = shift || 0;
198 my $fd = $exit ? \*STDERR : \*STDOUT;
200 git-svn - bidirectional operations between a single Subversion tree and git
201 Usage: $0 <command> [options] [arguments]\n
203 print $fd "Available commands:\n" unless $cmd;
205 foreach (sort keys %cmd) {
206 next if $cmd && $cmd ne $_;
207 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
208 foreach (keys %{$cmd{$_}->[2]}) {
209 # prints out arguments as they should be passed:
210 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
211 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
213 split /\|/,$_)," $x\n";
217 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
218 arbitrary identifier if you're tracking multiple SVN branches/repositories in
219 one git repository and want to keep them separate. See git-svn(1) for more
226 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
231 if (!verify_ref("refs/remotes/$GIT_SVN^0")) {
234 $SVN_URL = shift or undef;
237 command_noisy('update-ref',"refs/remotes/$GIT_SVN","
240 check_upgrade_needed();
243 my ($rev_list, $ctx) = command_output_pipe("rev-list",
244 "refs/remotes/$GIT_SVN");
247 while (<$rev_list>) {
250 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
251 my @commit = grep(/^git-svn-id: /,
252 command(qw/cat-file commit/, $c));
253 next if (!@commit); # skip merges
254 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
255 if (!defined $rev || !$uuid) {
256 croak "Unable to extract revision or UUID from ",
257 "$c, $commit[$#commit]\n";
260 # if we merged or otherwise started elsewhere, this is
261 # how we break out of it
262 next if (defined $svn_uuid && ($uuid ne $svn_uuid));
263 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
265 unless (defined $latest) {
266 if (!$SVN_URL && !$url) {
267 croak "SVN repository location required: $url\n";
274 revdb_set($REVDB, $rev, $c);
275 print "r$rev = $c\n";
276 $newest_rev = $rev if ($rev > $newest_rev);
278 command_close_pipe($rev_list, $ctx);
282 my $url = shift or die "SVN repository location required " .
283 "as a command-line argument\n";
284 $url =~ s!/+$!!; # strip trailing slash
286 if (my $repo_path = shift) {
287 unless (-d $repo_path) {
288 mkpath([$repo_path]);
290 $GIT_DIR = $ENV{GIT_DIR} = $repo_path . "/.git";
295 unless (-d $GIT_DIR) {
296 my @init_db = ('init');
297 push @init_db, "--template=$_template" if defined $_template;
298 push @init_db, "--shared" if defined $_shared;
299 command_noisy(@init_db);
305 fetch_child_id($GIT_SVN, @_);
309 check_upgrade_needed();
310 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
311 my $ret = fetch_lib(@_);
312 if ($ret->{commit} && !verify_ref('refs/heads/master^0')) {
313 command_noisy(qw(update-ref refs/heads/master),$ret->{commit});
320 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
321 $SVN ||= Git::SVN::Ra->new($SVN_URL);
322 my ($last_rev, $last_commit) = svn_grab_base_rev();
323 my ($base, $head) = libsvn_parse_revision($last_rev);
325 return { revision => $last_rev, commit => $last_commit }
327 my $index = set_index($GIT_SVN_INDEX);
329 # limit ourselves and also fork() since get_log won't release memory
330 # after processing a revision and SVN stuff seems to leak
332 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
333 if (defined $last_commit) {
334 unless (-e $GIT_SVN_INDEX) {
335 command_noisy('read-tree', $last_commit);
337 my $x = command_oneline('write-tree');
338 my ($y) = (command(qw/cat-file commit/, $last_commit)
339 =~ /^tree ($sha1)/m);
341 unlink $GIT_SVN_INDEX or croak $!;
342 command_noisy('read-tree', $last_commit);
344 $x = command_oneline('write-tree');
346 print STDERR "trees ($last_commit) $y != $x\n",
347 "Something is seriously wrong...\n";
351 # fork, because using SVN::Pool with get_log() still doesn't
352 # seem to help enough to keep memory usage down.
353 defined(my $pid = fork) or croak $!;
355 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
357 # Yes I'm perfectly aware that the fourth argument
358 # below is the limit revisions number. Unfortunately
359 # performance sucks with it enabled, so it's much
360 # faster to fetch revision ranges instead of relying
362 $SVN->dup->get_log([''], $min, $max, 0, 1, 1,
366 $log_msg = libsvn_fetch(
368 $last_commit = git_commit(
373 $log_msg = libsvn_new_tree(@_);
374 $last_commit = git_commit(
382 ($last_rev, $last_commit) = svn_grab_base_rev();
383 last if ($max >= $head);
386 $max = $head if ($max > $head);
387 $SVN = Git::SVN::Ra->new($SVN_URL);
389 restore_index($index);
390 return { revision => $last_rev, commit => $last_commit };
395 check_upgrade_needed();
396 if ($_stdin || !@commits) {
397 print "Reading from stdin...\n";
400 if (/\b($sha1_short)\b/o) {
401 unshift @commits, $1;
406 foreach my $c (@commits) {
407 my @tmp = command('rev-parse',$c);
408 if (scalar @tmp == 1) {
410 } elsif (scalar @tmp > 1) {
411 push @revs, reverse(command('rev-list',@tmp));
413 die "Failed to rev-parse $c\n";
417 print "Done committing ",scalar @revs," revisions to SVN\n";
422 my ($r_last, $cmt_last) = svn_grab_base_rev();
423 defined $r_last or die "Must have an existing revision to commit\n";
424 my $fetched = fetch();
425 if ($r_last != $fetched->{revision}) {
426 print STDERR "There are new revisions that were fetched ",
427 "and need to be merged (or acknowledged) ",
428 "before committing.\n",
429 "last rev: $r_last\n",
430 " current: $fetched->{revision}\n";
433 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
436 set_svn_commit_env();
437 foreach my $c (@revs) {
438 my $log_msg = get_commit_message($c, $commit_msg);
440 # fork for each commit because there's a memory leak I
441 # can't track down... (it's probably in the SVN code)
442 defined(my $pid = open my $fh, '-|') or croak $!;
444 my $pool = SVN::Pool->new;
445 my $ed = SVN::Git::Editor->new(
449 svn_path => $SVN->{svn_path},
451 $SVN->get_commit_editor(
461 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
463 print "No changes\nr$r_last = $cmt_last\n";
471 my ($r_new, $cmt_new, $no);
475 if (/^r(\d+) = ($sha1)$/o) {
476 ($r_new, $cmt_new) = ($1, $2);
477 } elsif ($_ eq 'No changes') {
482 if (! defined $r_new && ! defined $cmt_new) {
484 die "Failed to parse revision information\n";
487 ($r_last, $cmt_last) = ($r_new, $cmt_new);
495 my $head = shift || 'HEAD';
496 my $gs = "refs/remotes/$GIT_SVN";
497 my @refs = command(qw/rev-list --no-merges/, "$gs..$head");
499 foreach my $d (reverse @refs) {
500 if (!verify_ref("$d~1")) {
502 "has no parent commit, and therefore ",
503 "nothing to diff against.\n",
504 "You should be working from a repository ",
505 "originally created by git-svn\n";
507 unless (defined $last_rev) {
508 (undef, $last_rev, undef) = cmt_metadata("$d~1");
509 unless (defined $last_rev) {
510 die "Unable to extract revision information ",
511 "from commit $d~1\n";
515 print "diff-tree $d~1 $d\n";
517 if (my $r = commit_diff("$d~1", $d, undef, $last_rev)) {
519 } # else: no changes, same $last_rev
524 my @diff = command('diff-tree', 'HEAD', $gs, '--');
527 @finish = qw/rebase/;
528 push @finish, qw/--merge/ if $_merge;
529 push @finish, "--strategy=$_strategy" if $_strategy;
530 print STDERR "W: HEAD and $gs differ, using @finish:\n", @diff;
532 print "No changes between current HEAD and $gs\n",
533 "Resetting to the latest $gs\n";
534 @finish = qw/reset --mixed/;
536 command_noisy(@finish, $gs);
540 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
542 $SVN ||= Git::SVN::Ra->new($SVN_URL);
543 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
544 libsvn_traverse_ignore(\*STDOUT, '', $r);
548 my $gr_file = "$GIT_DIR/info/grafts";
549 my ($grafts, $comments) = read_grafts($gr_file);
553 # temporarily disable our grafts file to make this idempotent
554 chomp($gr_sha1 = command(qw/hash-object -w/,$gr_file));
555 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
558 my $l_map = read_url_paths();
559 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
560 unless ($_no_default_regex) {
561 push @re, (qr/\b(?:merge|merging|merged)\s+with\s+([\w\.\-]+)/i,
562 qr/\b(?:merge|merging|merged)\s+([\w\.\-]+)/i,
563 qr/\b(?:from|of)\s+([\w\.\-]+)/i );
565 foreach my $u (keys %$l_map) {
567 foreach my $p (keys %{$l_map->{$u}}) {
568 graft_merge_msg($grafts,$l_map,$u,$p,@re);
571 unless ($_no_graft_copy) {
572 graft_file_copy_lib($grafts,$l_map,$u);
575 graft_tree_joins($grafts);
577 write_grafts($grafts, $comments, $gr_file);
578 unlink "$gr_file~$gr_sha1" if $gr_sha1;
583 unless (defined $_trunk || defined $_branches || defined $_tags) {
586 if (defined $_trunk) {
587 my $trunk_url = complete_svn_url($url, $_trunk);
589 if ($GIT_SVN eq 'git-svn') {
591 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
594 unless (-d $GIT_SVN_DIR) {
596 print "GIT_SVN_ID set to 'trunk' for ",
597 "$trunk_url ($_trunk)\n";
600 command_noisy('config', 'svn.trunk', $trunk_url);
603 $_prefix = '' unless defined $_prefix;
604 complete_url_ls_init($url, $_branches, '--branches/-b', $_prefix);
605 complete_url_ls_init($url, $_tags, '--tags/-t', $_prefix . 'tags/');
609 # try to do trunk first, since branches/tags
610 # may be descended from it.
611 if (-e "$GIT_DIR/svn/trunk/info/url") {
612 fetch_child_id('trunk', @_);
614 rec_fetch('', "$GIT_DIR/svn", @_);
620 my $r_last = -1; # prevent dupes
621 rload_authors() if $_authors;
627 if (defined $_revision) {
628 if ($_revision =~ /^(\d+):(\d+)$/) {
629 ($r_min, $r_max) = ($1, $2);
630 } elsif ($_revision =~ /^\d+$/) {
631 $r_min = $r_max = $_revision;
633 print STDERR "-r$_revision is not supported, use ",
634 "standard \'git log\' arguments instead\n";
640 @args = (git_svn_log_cmd($r_min, $r_max), @args);
641 my $log = command_output_pipe(@args);
646 if (/^${_esc_color}commit ($sha1_short)/o) {
648 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
650 process_commit($c, $r_min, $r_max, \@k) or
655 } elsif (/^${_esc_color}author (.+) (\d+) ([\-\+]?\d+)$/) {
656 get_author_info($c, $1, $2, $3);
657 } elsif (/^${_esc_color}(?:tree|parent|committer) /) {
659 } elsif (/^${_esc_color}:\d{6} \d{6} $sha1_short/o) {
660 push @{$c->{raw}}, $_;
661 } elsif (/^${_esc_color}[ACRMDT]\t/) {
662 # we could add $SVN->{svn_path} here, but that requires
663 # remote access at the moment (repo_path_split)...
664 s#^(${_esc_color})([ACRMDT])\t#$1 $2 #;
665 push @{$c->{changed}}, $_;
666 } elsif (/^${_esc_color}diff /) {
668 push @{$c->{diff}}, $_;
670 push @{$c->{diff}}, $_;
671 } elsif (/^${_esc_color} (git-svn-id:.+)$/) {
672 ($c->{url}, $c->{r}, undef) = extract_metadata($1);
673 } elsif (s/^${_esc_color} //) {
677 if ($c && defined $c->{r} && $c->{r} != $r_last) {
679 process_commit($c, $r_min, $r_max, \@k);
685 process_commit($_, $r_min, $r_max) foreach reverse @k;
689 print '-' x72,"\n" unless $_incremental || $_oneline;
692 sub commit_diff_usage {
693 print STDERR "Usage: $0 commit-diff <tree-ish> <tree-ish> [<URL>]\n";
698 my $ta = shift or commit_diff_usage();
699 my $tb = shift or commit_diff_usage();
700 if (!eval { $SVN_URL = shift || file_to_s("$GIT_SVN_DIR/info/url") }) {
701 print STDERR "Needed URL or usable git-svn id command-line\n";
705 unless (defined $r) {
706 if (defined $_revision) {
709 die "-r|--revision is a required argument\n";
712 if (defined $_message && defined $_file) {
713 print STDERR "Both --message/-m and --file/-F specified ",
714 "for the commit message.\n",
715 "I have no idea what you mean\n";
718 if (defined $_file) {
719 $_message = file_to_s($_file);
721 $_message ||= get_commit_message($tb,
722 "$GIT_DIR/.svn-commit.tmp.$$")->{msg};
724 $SVN ||= Git::SVN::Ra->new($SVN_URL);
726 $r = $SVN->get_latest_revnum;
727 } elsif ($r !~ /^\d+$/) {
728 die "revision argument: $r not understood by git-svn\n";
731 my $pool = SVN::Pool->new;
732 my $ed = SVN::Git::Editor->new({ r => $r,
735 svn_path => $SVN->{svn_path}
737 $SVN->get_commit_editor($_message,
739 $rev_committed = $_[0];
740 print "Committed $_[0]\n";
745 my $mods = libsvn_checkout_tree($ta, $tb, $ed);
747 print "No changes\n$ta == $tb\n";
755 $_message = $_file = undef;
756 return $rev_committed;
759 ########################### utility functions #########################
763 return 1 if defined $c->{r};
764 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
765 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
766 my @msg = command(qw/cat-file commit/, $c->{c});
767 shift @msg while ($msg[0] ne "\n");
769 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
771 (undef, $c->{r}, undef) = extract_metadata(
772 (grep(/^git-svn-id: /, @msg))[-1]);
774 return defined $c->{r};
780 $dcvar = 'color.diff';
781 $dc = `git-config --get $dcvar`;
783 # nothing at all; fallback to "diff.color"
784 $dcvar = 'diff.color';
785 $dc = `git-config --get $dcvar`;
790 $pc = `git-config --get color.pager`;
792 # does not have it -- fallback to pager.color
793 $pc = `git-config --bool --get pager.color`;
796 $pc = `git-config --bool --get color.pager`;
802 if (-t *STDOUT || (defined $_pager && $pc eq 'true')) {
803 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
807 return 0 if $dc eq 'never';
808 return 1 if $dc eq 'always';
809 chomp($dc = `git-config --bool --get $dcvar`);
810 return ($dc eq 'true');
813 sub git_svn_log_cmd {
814 my ($r_min, $r_max) = @_;
815 my @cmd = (qw/log --abbrev-commit --pretty=raw
816 --default/, "refs/remotes/$GIT_SVN");
817 push @cmd, '-r' unless $_non_recursive;
818 push @cmd, qw/--raw --name-status/ if $_verbose;
819 push @cmd, '--color' if log_use_color();
820 return @cmd unless defined $r_max;
821 if ($r_max == $r_min) {
822 push @cmd, '--max-count=1';
823 if (my $c = revdb_get($REVDB, $r_max)) {
828 $c_max = revdb_get($REVDB, $r_max);
829 $c_min = revdb_get($REVDB, $r_min);
830 if (defined $c_min && defined $c_max) {
831 if ($r_max > $r_max) {
832 push @cmd, "$c_min..$c_max";
834 push @cmd, "$c_max..$c_min";
836 } elsif ($r_max > $r_min) {
847 print "Fetching $id\n";
848 my $ref = "$GIT_DIR/refs/remotes/$id";
849 defined(my $pid = open my $fh, '-|') or croak $!;
851 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
858 check_repack() if (/^r\d+ = $sha1/o);
860 close $fh or croak $?;
864 my ($pfx, $p, @args) = @_;
866 foreach (sort <$p/*>) {
867 if (-r "$_/info/url") {
868 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
869 my $id = $pfx . basename $_;
870 next if $id eq 'trunk';
871 fetch_child_id($id, @args);
878 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
883 sub complete_svn_url {
884 my ($url, $path) = @_;
886 $url =~ s#/+$## if $url;
887 if ($path !~ m#^[a-z\+]+://#) {
888 $path = '/' . $path if ($path !~ m#^/#);
889 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
890 fatal("E: '$path' is not a complete URL ",
891 "and a separate URL is not specified\n");
893 $path = $url . $path;
898 sub complete_url_ls_init {
899 my ($url, $path, $switch, $pfx) = @_;
901 print STDERR "W: $switch not specified\n";
904 my $full_url = complete_svn_url($url, $path);
905 my @ls = libsvn_ls_fullurl($full_url);
906 defined(my $pid = fork) or croak $!;
908 foreach my $u (map { "$full_url/$_" } (grep m!/$!, @ls)) {
910 if ($u !~ m!\Q$full_url\E/(.+)$!) {
911 print STDERR "W: Unrecognized URL: $u\n";
912 die "This should never happen\n";
914 # don't try to init already existing refs
916 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
918 unless (-d $GIT_SVN_DIR) {
919 print "init $u => $id\n";
927 my ($n) = ($switch =~ /^--(\w+)/);
928 command_noisy('config', "svn.$n", $full_url);
935 my @tmp = split m#/#, $_;
937 while (my $x = shift @tmp) {
943 foreach (sort {length $b <=> length $a} keys %common) {
944 if ($common{$_} == @$paths) {
951 # grafts set here are 'stronger' in that they're based on actual tree
952 # matches, and won't be deleted from merge-base checking in write_grafts()
953 sub graft_tree_joins {
955 map_tree_joins() if (@_branch_from && !%tree_map);
956 return unless %tree_map;
960 my @args = (qw/rev-list --pretty=raw/, "refs/remotes/$i");
961 my ($fh, $ctx) = command_output_pipe(@args);
963 next unless /^commit ($sha1)$/o;
965 my ($t) = (<$fh> =~ /^tree ($sha1)$/o);
966 next unless $tree_map{$t};
971 } until ($l =~ /^committer (?:.+) (\d+) ([\-\+]?\d+)$/);
973 my ($s, $tz) = ($1, $2);
974 if ($tz =~ s/^\+//) {
975 $s += tz_to_s_offset($tz);
976 } elsif ($tz =~ s/^\-//) {
977 $s -= tz_to_s_offset($tz);
980 my ($url_a, $r_a, $uuid_a) = cmt_metadata($c);
982 foreach my $p (@{$tree_map{$t}}) {
984 my $mb = eval { command('merge-base', $c, $p) };
985 next unless ($@ || $?);
987 # see if SVN says it's a relative
988 my ($url_b, $r_b, $uuid_b) =
990 next if (defined $url_b &&
992 ($url_a eq $url_b) &&
993 ($uuid_a eq $uuid_b));
994 if ($uuid_a eq $uuid_b) {
996 $grafts->{$c}->{$p} = 2;
998 } elsif ($r_b > $r_a) {
999 $grafts->{$p}->{$c} = 2;
1004 my $ct = get_commit_time($p);
1006 $grafts->{$c}->{$p} = 2;
1007 } elsif ($ct > $s) {
1008 $grafts->{$p}->{$c} = 2;
1010 # what should we do when $ct == $s ?
1013 command_close_pipe($fh, $ctx);
1017 sub graft_file_copy_lib {
1018 my ($grafts, $l_map, $u) = @_;
1019 my $tree_paths = $l_map->{$u};
1020 my $pfx = common_prefix([keys %$tree_paths]);
1021 my ($repo, $path) = repo_path_split($u.$pfx);
1022 $SVN = Git::SVN::Ra->new($repo);
1024 my ($base, $head) = libsvn_parse_revision();
1026 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
1027 my $eh = $SVN::Error::handler;
1028 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
1030 $SVN->dup->get_log([$path], $min, $max, 0, 2, 1,
1032 libsvn_graft_file_copies($grafts, $tree_paths,
1035 last if ($max >= $head);
1038 $max = $head if ($max > $head);
1040 $SVN::Error::handler = $eh;
1043 sub process_merge_msg_matches {
1044 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
1045 my (@strong, @weak);
1046 foreach (@matches) {
1047 # merging with ourselves is not interesting
1049 if ($l_map->{$u}->{$_}) {
1055 foreach my $w (@weak) {
1057 # no exact match, use branch name as regexp.
1058 my $re = qr/\Q$w\E/i;
1059 foreach (keys %{$l_map->{$u}}) {
1061 push @strong, $l_map->{$u}->{$_};
1068 foreach (keys %{$l_map->{$u}}) {
1070 push @strong, $l_map->{$u}->{$_};
1075 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
1076 \s(?:[a-f\d\-]+)$/xsm);
1077 unless (defined $rev) {
1078 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
1079 \@(?:[a-f\d\-]+)/xsm);
1080 return unless defined $rev;
1082 foreach my $m (@strong) {
1083 my ($r0, $s0) = find_rev_before($rev, $m, 1);
1084 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
1088 sub graft_merge_msg {
1089 my ($grafts, $l_map, $u, $p, @re) = @_;
1091 my $x = $l_map->{$u}->{$p};
1092 my $rl = rev_list_raw("refs/remotes/$x");
1093 while (my $c = next_rev_list_entry($rl)) {
1094 foreach my $re (@re) {
1095 my (@br) = ($c->{m} =~ /$re/g);
1097 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1104 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1105 { STDERR => 0 }); };
1108 sub repo_path_split {
1109 my $full_url = shift;
1110 $full_url =~ s#/+$##;
1112 foreach (@repo_path_split_cache) {
1113 if ($full_url =~ s#$_##) {
1115 $full_url =~ s#^/+##;
1116 return ($u, $full_url);
1119 my $tmp = Git::SVN::Ra->new($full_url);
1120 return ($tmp->{repos_root}, $tmp->{svn_path});
1124 defined $SVN_URL or croak "SVN repository location required\n";
1125 unless (-d $GIT_DIR) {
1126 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1128 mkpath([$GIT_SVN_DIR]);
1129 mkpath(["$GIT_SVN_DIR/info"]);
1130 open my $fh, '>>',$REVDB or croak $!;
1132 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1136 sub get_tree_from_treeish {
1138 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1139 my $type = command_oneline(qw/cat-file -t/, $treeish);
1141 while ($type eq 'tag') {
1142 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1144 if ($type eq 'commit') {
1145 $expected = (grep /^tree /, command(qw/cat-file commit/,
1147 ($expected) = ($expected =~ /^tree ($sha1)$/);
1148 die "Unable to get tree from $treeish\n" unless $expected;
1149 } elsif ($type eq 'tree') {
1150 $expected = $treeish;
1152 die "$treeish is a $type, expected tree, tag or commit\n";
1158 my ($from, $treeish) = @_;
1159 print "diff-tree $from $treeish\n";
1160 my @diff_tree = qw(diff-tree -z -r);
1161 if ($_cp_similarity) {
1162 push @diff_tree, "-C$_cp_similarity";
1164 push @diff_tree, '-C';
1166 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1167 push @diff_tree, "-l$_l" if defined $_l;
1168 push @diff_tree, $from, $treeish;
1169 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1173 while (<$diff_fh>) {
1174 chomp $_; # this gets rid of the trailing "\0"
1175 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1176 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1177 push @mods, { mode_a => $1, mode_b => $2,
1178 sha1_b => $3, chg => $4 };
1179 if ($4 =~ /^(?:C|R)$/) {
1184 } elsif ($state eq 'file_a') {
1185 my $x = $mods[$#mods] or croak "Empty array\n";
1186 if ($x->{chg} !~ /^(?:C|R)$/) {
1187 croak "Error parsing $_, $x->{chg}\n";
1191 } elsif ($state eq 'file_b') {
1192 my $x = $mods[$#mods] or croak "Empty array\n";
1193 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1194 croak "Error parsing $_, $x->{chg}\n";
1196 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1197 croak "Error parsing $_, $x->{chg}\n";
1202 croak "Error parsing $_\n";
1205 command_close_pipe($diff_fh, $ctx);
1209 sub libsvn_checkout_tree {
1210 my ($from, $treeish, $ed) = @_;
1211 my $mods = get_diff($from, $treeish);
1212 return $mods unless (scalar @$mods);
1213 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1214 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1216 if (defined $o{$f}) {
1219 croak "Invalid change type: $f\n";
1222 $ed->rmdirs($_q) if $_rmdir;
1226 sub get_commit_message {
1227 my ($commit, $commit_msg) = (@_);
1228 my %log_msg = ( msg => '' );
1229 open my $msg, '>', $commit_msg or croak $!;
1231 my $type = command_oneline(qw/cat-file -t/, $commit);
1232 if ($type eq 'commit' || $type eq 'tag') {
1233 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1238 $in_msg = 1 if (/^\s*$/);
1239 } elsif (/^git-svn-id: /) {
1240 # skip this, we regenerate the correct one
1241 # on re-fetch anyways
1243 print $msg $_ or croak $!;
1246 command_close_pipe($msg_fh, $ctx);
1248 close $msg or croak $!;
1250 if ($_edit || ($type eq 'tree')) {
1251 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1252 system($editor, $commit_msg);
1255 # file_to_s removes all trailing newlines, so just use chomp() here:
1256 open $msg, '<', $commit_msg or croak $!;
1257 { local $/; chomp($log_msg{msg} = <$msg>); }
1258 close $msg or croak $!;
1263 sub set_svn_commit_env {
1264 if (defined $LC_ALL) {
1265 $ENV{LC_ALL} = $LC_ALL;
1267 delete $ENV{LC_ALL};
1272 my ($fh, $c) = command_output_pipe(qw/rev-list --pretty=raw/, @_);
1273 return { fh => $fh, ctx => $c, t => { } };
1276 sub next_rev_list_entry {
1281 if (/^commit ($sha1)$/o) {
1283 $rl->{t} = { c => $1 };
1288 } elsif (/^parent ($sha1)$/o) {
1295 command_close_pipe($fh, $rl->{ctx});
1296 return ($x != $rl->{t}) ? $x : undef;
1300 my ($str, $file, $mode) = @_;
1301 open my $fd,'>',$file or croak $!;
1302 print $fd $str,"\n" or croak $!;
1303 close $fd or croak $!;
1304 chmod ($mode &~ umask, $file) if (defined $mode);
1309 open my $fd,'<',$file or croak "$!: file: $file\n";
1312 close $fd or croak $!;
1317 sub assert_revision_unknown {
1319 if (my $c = revdb_get($REVDB, $r)) {
1320 croak "$r = $c already exists! Why are we refetching it?";
1325 my ($log_msg, @parents) = @_;
1326 assert_revision_unknown($log_msg->{revision});
1327 map_tree_joins() if (@_branch_from && !%tree_map);
1329 my (@tmp_parents, @exec_parents, %seen_parent);
1330 if (my $lparents = $log_msg->{parents}) {
1331 @tmp_parents = @$lparents
1333 # commit parents can be conditionally bound to a particular
1334 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1335 foreach my $p (@parents) {
1336 next unless defined $p;
1337 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1338 if ($1 == $log_msg->{revision}) {
1339 push @tmp_parents, $2;
1342 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1345 my $tree = $log_msg->{tree};
1346 if (!defined $tree) {
1347 my $index = set_index($GIT_SVN_INDEX);
1348 $tree = command_oneline('write-tree');
1350 restore_index($index);
1352 # just in case we clobber the existing ref, we still want that ref
1354 if (my $cur = verify_ref("refs/remotes/$GIT_SVN^0")) {
1356 push @tmp_parents, $cur;
1359 if (exists $tree_map{$tree}) {
1360 foreach my $p (@{$tree_map{$tree}}) {
1362 foreach (@tmp_parents) {
1363 # see if a common parent is found
1364 my $mb = eval { command('merge-base', $_, $p) };
1370 my ($url_p, $r_p, $uuid_p) = cmt_metadata($p);
1371 next if (($SVN->uuid eq $uuid_p) &&
1372 ($log_msg->{revision} > $r_p));
1373 next if (defined $url_p && defined $SVN_URL &&
1374 ($SVN->uuid eq $uuid_p) &&
1375 ($url_p eq $SVN_URL));
1376 push @tmp_parents, $p;
1379 foreach (@tmp_parents) {
1380 next if $seen_parent{$_};
1381 $seen_parent{$_} = 1;
1382 push @exec_parents, $_;
1383 # MAXPARENT is defined to 16 in commit-tree.c:
1384 last if @exec_parents > 16;
1387 set_commit_env($log_msg);
1388 my @exec = ('git-commit-tree', $tree);
1389 push @exec, '-p', $_ foreach @exec_parents;
1390 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1392 print $msg_fh $log_msg->{msg} or croak $!;
1393 unless ($_no_metadata) {
1394 print $msg_fh "\ngit-svn-id: $SVN_URL\@$log_msg->{revision} ",
1395 $SVN->uuid,"\n" or croak $!;
1397 $msg_fh->flush == 0 or croak $!;
1398 close $msg_fh or croak $!;
1399 chomp(my $commit = do { local $/; <$out_fh> });
1400 close $out_fh or croak $!;
1403 if ($commit !~ /^$sha1$/o) {
1404 die "Failed to commit, invalid sha1: $commit\n";
1406 command_noisy('update-ref',"refs/remotes/$GIT_SVN",$commit);
1407 revdb_set($REVDB, $log_msg->{revision}, $commit);
1409 # this output is read via pipe, do not change:
1410 print "r$log_msg->{revision} = $commit\n";
1415 if ($_repack && (--$_repack_nr == 0)) {
1416 $_repack_nr = $_repack;
1417 # repack doesn't use any arguments with spaces in them, does it?
1418 command_noisy('repack', split(/\s+/, $_repack_flags));
1422 sub set_commit_env {
1424 my $author = $log_msg->{author};
1425 if (!defined $author || length $author == 0) {
1426 $author = '(no author)';
1428 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1429 : ($author,$author . '@' . $SVN->uuid);
1430 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1431 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1432 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1435 sub check_upgrade_needed {
1437 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1438 open my $fh, '>>',$REVDB or croak $!;
1441 return unless eval {
1442 command([qw/rev-parse --verify/,"$GIT_SVN-HEAD^0"],
1445 my $head = eval { command('rev-parse',"refs/remotes/$GIT_SVN") };
1447 print STDERR "Please run: $0 rebuild --upgrade\n";
1452 # fills %tree_map with a reverse mapping of trees to commits. Useful
1453 # for finding parents to commit on.
1454 sub map_tree_joins {
1456 foreach my $br (@_branch_from) {
1457 my $pipe = command_output_pipe(qw/rev-list
1458 --topo-order --pretty=raw/, $br);
1460 if (/^commit ($sha1)$/o) {
1463 # if we've seen a commit,
1464 # we've seen its parents
1465 last if $seen{$commit};
1466 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1467 unless (defined $tree) {
1468 die "Failed to parse commit $commit\n";
1470 push @{$tree_map{$tree}}, $commit;
1479 if (@_branch_from) {
1480 print STDERR '--branch|-b parameters are ignored when ',
1481 "--branch-all-refs|-B is passed\n";
1484 # don't worry about rev-list on non-commit objects/tags,
1485 # it shouldn't blow up if a ref is a blob or tree...
1486 @_branch_from = command(qw/rev-parse --symbolic --all/);
1489 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1491 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1492 while (<$authors>) {
1494 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1495 my ($user, $name, $email) = ($1, $2, $3);
1496 $users{$user} = [$name, $email];
1498 close $authors or croak $!;
1502 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1503 while (<$authors>) {
1505 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1506 my ($user, $name, $email) = ($1, $2, $3);
1507 $rusers{"$name <$email>"} = $user;
1509 close $authors or croak $!;
1514 foreach (command(qw/rev-parse --symbolic --all/)) {
1515 next unless s#^refs/remotes/##;
1517 next unless -f "$GIT_DIR/svn/$_/info/url";
1525 defined(my $pid = fork) or croak $!;
1527 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1529 exit 0 if -r $REVDB;
1530 print "Upgrading svn => git mapping...\n";
1531 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1532 open my $fh, '>>',$REVDB or croak $!;
1535 print "Done upgrading. You may now delete the ",
1536 "deprecated $GIT_SVN_DIR/revs directory\n";
1544 sub migration_check {
1545 migrate_revdb() unless (-e $REVDB);
1546 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
1547 print "Upgrading repository...\n";
1548 unless (-d "$GIT_DIR/svn") {
1549 mkdir "$GIT_DIR/svn" or croak $!;
1551 print "Data from a previous version of git-svn exists, but\n\t",
1552 "$GIT_SVN_DIR\n\t(required for this version ",
1553 "($VERSION) of git-svn) does not.\n";
1555 foreach my $x (command(qw/rev-parse --symbolic --all/)) {
1556 next unless $x =~ s#^refs/remotes/##;
1558 next unless -f "$GIT_DIR/$x/info/url";
1559 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
1561 my $dn = dirname("$GIT_DIR/svn/$x");
1562 mkpath([$dn]) unless -d $dn;
1563 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
1565 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
1566 print "Done upgrading.\n";
1569 sub find_rev_before {
1570 my ($r, $id, $eq_ok) = @_;
1571 my $f = "$GIT_DIR/svn/$id/.rev_db";
1572 return (undef,undef) unless -r $f;
1575 if (my $c = revdb_get($f, $r)) {
1580 return (undef, undef);
1584 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
1585 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
1586 $REVDB = "$GIT_SVN_DIR/.rev_db";
1587 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
1592 # convert GetOpt::Long specs for use by git-config
1593 sub read_repo_config {
1594 return unless -d $GIT_DIR;
1596 foreach my $o (keys %$opts) {
1597 my $v = $opts->{$o};
1598 my ($key) = ($o =~ /^([a-z\-]+)/);
1600 my $arg = 'git-config';
1601 $arg .= ' --int' if ($o =~ /[:=]i$/);
1602 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1603 if (ref $v eq 'ARRAY') {
1604 chomp(my @tmp = `$arg --get-all svn.$key`);
1607 chomp(my $tmp = `$arg --get svn.$key`);
1608 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1615 sub set_default_vals {
1616 if (defined $_repack) {
1617 $_repack = 1000 if ($_repack <= 0);
1618 $_repack_nr = $_repack;
1619 $_repack_flags ||= '-d';
1624 my $gr_file = shift;
1625 my ($grafts, $comments) = ({}, {});
1626 if (open my $fh, '<', $gr_file) {
1629 if (/^($sha1)\s+/) {
1632 @{$comments->{$c}} = @tmp;
1635 foreach my $p (split /\s+/, $_) {
1636 $grafts->{$c}->{$p} = 1;
1642 close $fh or croak $!;
1643 @{$comments->{'END'}} = @tmp if @tmp;
1645 return ($grafts, $comments);
1649 my ($grafts, $comments, $gr_file) = @_;
1651 open my $fh, '>', $gr_file or croak $!;
1652 foreach my $c (sort keys %$grafts) {
1653 if ($comments->{$c}) {
1654 print $fh $_ foreach @{$comments->{$c}};
1656 my $p = $grafts->{$c};
1657 my %x; # real parents
1658 delete $p->{$c}; # commits are not self-reproducing...
1659 my $ch = command_output_pipe(qw/cat-file commit/, $c);
1661 if (/^parent ($sha1)/) {
1662 $x{$1} = $p->{$1} = 1;
1667 close $ch; # breaking the pipe
1669 # if real parents are the only ones in the grafts, drop it
1670 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1674 @ip = @jp = keys %$p;
1675 foreach my $i (@ip) {
1676 next if $del{$i} || $p->{$i} == 2;
1677 foreach my $j (@jp) {
1678 next if $i eq $j || $del{$j} || $p->{$j} == 2;
1679 $mb = eval { command('merge-base', $i, $j) };
1686 } elsif ($mb eq $i) {
1693 # if real parents are the only ones in the grafts, drop it
1694 next if join(' ',sort keys %$p) eq join(' ',sort keys %x);
1696 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
1698 if ($comments->{'END'}) {
1699 print $fh $_ foreach @{$comments->{'END'}};
1701 close $fh or croak $!;
1704 sub read_url_paths_all {
1705 my ($l_map, $pfx, $p) = @_;
1708 if (-r "$_/info/url") {
1709 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
1710 my $id = $pfx . basename $_;
1711 my $url = file_to_s("$_/info/url");
1712 my ($u, $p) = repo_path_split($url);
1713 $l_map->{$u}->{$p} = $id;
1720 $x =~ s!^\Q$GIT_DIR\E/svn/!!o;
1721 read_url_paths_all($l_map, $x, $_);
1725 # this one only gets ids that have been imported, not new ones
1726 sub read_url_paths {
1728 git_svn_each(sub { my $x = shift;
1729 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
1730 my ($u, $p) = repo_path_split($url);
1731 $l_map->{$u}->{$p} = $x;
1736 sub extract_metadata {
1737 my $id = shift or return (undef, undef, undef);
1738 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
1740 if (!defined $rev || !$uuid || !$url) {
1741 # some of the original repositories I made had
1742 # identifiers like this:
1743 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1745 return ($url, $rev, $uuid);
1749 return extract_metadata((grep(/^git-svn-id: /,
1750 command(qw/cat-file commit/, shift)))[-1]);
1753 sub get_commit_time {
1755 my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
1757 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
1758 my ($s, $tz) = ($1, $2);
1759 if ($tz =~ s/^\+//) {
1760 $s += tz_to_s_offset($tz);
1761 } elsif ($tz =~ s/^\-//) {
1762 $s -= tz_to_s_offset($tz);
1767 die "Can't get commit time for commit: $cmt\n";
1770 sub tz_to_s_offset {
1773 return ($1 * 60) + ($tz * 3600);
1776 # adapted from pager.c
1778 $_pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
1779 if (!defined $_pager) {
1781 } elsif (length $_pager == 0 || $_pager eq 'cat') {
1787 return unless -t *STDOUT;
1788 pipe my $rfd, my $wfd or return;
1789 defined(my $pid = fork) or croak $!;
1791 open STDOUT, '>&', $wfd or croak $!;
1794 open STDIN, '<&', $rfd or croak $!;
1795 $ENV{LESS} ||= 'FRSX';
1796 exec $_pager or croak "Can't run pager: $! ($_pager)\n";
1799 sub get_author_info {
1800 my ($dest, $author, $t, $tz) = @_;
1801 $author =~ s/(?:^\s*|\s*$)//g;
1802 $dest->{a_raw} = $author;
1805 $_a = $rusers{$author} || undef;
1808 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
1813 # Date::Parse isn't in the standard Perl distro :(
1814 if ($tz =~ s/^\+//) {
1815 $t += tz_to_s_offset($tz);
1816 } elsif ($tz =~ s/^\-//) {
1817 $t -= tz_to_s_offset($tz);
1819 $dest->{t_utc} = $t;
1822 sub process_commit {
1823 my ($c, $r_min, $r_max, $defer) = @_;
1824 if (defined $r_min && defined $r_max) {
1825 if ($r_min == $c->{r} && $r_min == $r_max) {
1829 return 1 if $r_min == $r_max;
1830 if ($r_min < $r_max) {
1831 # we need to reverse the print order
1832 return 0 if (defined $_limit && --$_limit < 0);
1836 if ($r_min != $r_max) {
1837 return 1 if ($r_min < $c->{r});
1838 return 1 if ($r_max > $c->{r});
1841 return 0 if (defined $_limit && --$_limit < 0);
1850 if (my $l = $c->{l}) {
1851 while ($l->[0] =~ /^\s*$/) { shift @$l }
1854 $_l_fmt ||= 'A' . length($c->{r});
1855 print 'r',pack($_l_fmt, $c->{r}),' | ';
1856 print "$c->{c} | " if $_show_commit;
1859 show_commit_normal($c);
1863 sub show_commit_changed_paths {
1865 return unless $c->{changed};
1866 print "Changed paths:\n", @{$c->{changed}};
1869 sub show_commit_normal {
1871 print '-' x72, "\nr$c->{r} | ";
1872 print "$c->{c} | " if $_show_commit;
1873 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
1874 localtime($c->{t_utc})), ' | ';
1877 if (my $l = $c->{l}) {
1878 while ($l->[$#$l] eq "\n" && $#$l > 0
1879 && $l->[($#$l - 1)] eq "\n") {
1882 $nr_line = scalar @$l;
1884 print "1 line\n\n\n";
1886 if ($nr_line == 1) {
1887 $nr_line = '1 line';
1889 $nr_line .= ' lines';
1891 print $nr_line, "\n";
1892 show_commit_changed_paths($c);
1894 print $_ foreach @$l;
1898 show_commit_changed_paths($c);
1902 foreach my $x (qw/raw diff/) {
1905 print $_ foreach @{$c->{$x}}
1910 package Git::SVN::Prompt;
1914 use vars qw/$_no_auth_cache $_username/;
1917 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1918 $may_save = undef if $_no_auth_cache;
1919 $default_username = $_username if defined $_username;
1920 if (defined $default_username && length $default_username) {
1921 if (defined $realm && length $realm) {
1922 print STDERR "Authentication realm: $realm\n";
1925 $cred->username($default_username);
1927 username($cred, $realm, $may_save, $pool);
1929 $cred->password(_read_password("Password for '" .
1930 $cred->username . "': ", $realm));
1931 $cred->may_save($may_save);
1932 $SVN::_Core::SVN_NO_ERROR;
1935 sub ssl_server_trust {
1936 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1937 $may_save = undef if $_no_auth_cache;
1938 print STDERR "Error validating server certificate for '$realm':\n";
1939 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1940 print STDERR " - The certificate is not issued by a trusted ",
1941 "authority. Use the\n",
1942 " fingerprint to validate the certificate manually!\n";
1944 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1945 print STDERR " - The certificate hostname does not match.\n";
1947 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1948 print STDERR " - The certificate is not yet valid.\n";
1950 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1951 print STDERR " - The certificate has expired.\n";
1953 if ($failures & $SVN::Auth::SSL::OTHER) {
1954 print STDERR " - The certificate has an unknown error.\n";
1957 "Certificate information:\n".
1958 " - Hostname: %s\n".
1959 " - Valid: from %s until %s\n".
1961 " - Fingerprint: %s\n",
1962 map $cert_info->$_, qw(hostname valid_from valid_until
1963 issuer_dname fingerprint);
1966 print STDERR $may_save ?
1967 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1968 "(R)eject or accept (t)emporarily? ";
1970 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1971 if ($choice =~ /^t$/i) {
1972 $cred->may_save(undef);
1973 } elsif ($choice =~ /^r$/i) {
1975 } elsif ($may_save && $choice =~ /^p$/i) {
1976 $cred->may_save($may_save);
1980 $cred->accepted_failures($failures);
1981 $SVN::_Core::SVN_NO_ERROR;
1984 sub ssl_client_cert {
1985 my ($cred, $realm, $may_save, $pool) = @_;
1986 $may_save = undef if $_no_auth_cache;
1987 print STDERR "Client certificate filename: ";
1989 chomp(my $filename = <STDIN>);
1990 $cred->cert_file($filename);
1991 $cred->may_save($may_save);
1992 $SVN::_Core::SVN_NO_ERROR;
1995 sub ssl_client_cert_pw {
1996 my ($cred, $realm, $may_save, $pool) = @_;
1997 $may_save = undef if $_no_auth_cache;
1998 $cred->password(_read_password("Password: ", $realm));
1999 $cred->may_save($may_save);
2000 $SVN::_Core::SVN_NO_ERROR;
2004 my ($cred, $realm, $may_save, $pool) = @_;
2005 $may_save = undef if $_no_auth_cache;
2006 if (defined $realm && length $realm) {
2007 print STDERR "Authentication realm: $realm\n";
2010 if (defined $_username) {
2011 $username = $_username;
2013 print STDERR "Username: ";
2015 chomp($username = <STDIN>);
2017 $cred->username($username);
2018 $cred->may_save($may_save);
2019 $SVN::_Core::SVN_NO_ERROR;
2022 sub _read_password {
2023 my ($prompt, $realm) = @_;
2024 print STDERR $prompt;
2026 require Term::ReadKey;
2027 Term::ReadKey::ReadMode('noecho');
2029 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2030 last if $key =~ /[\012\015]/; # \n\r
2033 Term::ReadKey::ReadMode('restore');
2043 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2050 $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
2054 sub libsvn_log_entry {
2055 my ($rev, $author, $date, $msg, $parents, $untracked) = @_;
2056 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2057 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2058 or die "Unable to parse date: $date\n";
2059 if (defined $author && length $author > 0 &&
2060 defined $_authors && ! defined $users{$author}) {
2061 die "Author: $author not defined in $_authors file\n";
2063 $msg = '' if ($rev == 0 && !defined $msg);
2065 open my $un, '>>', "$GIT_SVN_DIR/unhandled.log" or croak $!;
2067 print $un "r$rev\n" or croak $!;
2068 $h = $untracked->{empty};
2069 foreach (sort keys %$h) {
2070 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2071 print $un " $act: ", uri_encode($_), "\n" or croak $!;
2072 warn "W: $act: $_\n";
2074 foreach my $t (qw/dir_prop file_prop/) {
2075 $h = $untracked->{$t} or next;
2076 foreach my $path (sort keys %$h) {
2077 my $ppath = $path eq '' ? '.' : $path;
2078 foreach my $prop (sort keys %{$h->{$path}}) {
2079 next if $SKIP{$prop};
2080 my $v = $h->{$path}->{$prop};
2083 uri_encode($ppath), ' ',
2084 uri_encode($prop), ' ',
2085 uri_encode($v), "\n"
2089 uri_encode($ppath), ' ',
2090 uri_encode($prop), "\n"
2096 foreach my $t (qw/absent_file absent_directory/) {
2097 $h = $untracked->{$t} or next;
2098 foreach my $parent (sort keys %$h) {
2099 foreach my $path (sort @{$h->{$parent}}) {
2101 uri_encode("$parent/$path"), "\n"
2103 warn "W: $t: $parent/$path ",
2104 "Insufficient permissions?\n";
2109 # revprops (make this optional? it's an extra network trip...)
2110 my $rp = $SVN->rev_proplist($rev);
2111 foreach (sort keys %$rp) {
2112 next if /^svn:(?:author|date|log)$/;
2113 print $un " rev_prop: ", uri_encode($_), ' ',
2114 uri_encode($rp->{$_}), "\n";
2116 close $un or croak $!;
2118 { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2119 author => $author, msg => $msg."\n", parents => $parents || [],
2124 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2125 my $ed = SVN::Git::Fetcher->new({ c => $last_commit, q => $_q });
2126 my (undef, $last_rev, undef) = cmt_metadata($last_commit);
2127 unless ($SVN->gs_do_update($last_rev, $rev, '', 1, $ed)) {
2128 die "SVN connection failed somewhere...\n";
2130 libsvn_log_entry($rev, $author, $date, $msg, [$last_commit], $ed);
2133 sub svn_grab_base_rev {
2134 my $c = eval { command_oneline([qw/rev-parse --verify/,
2135 "refs/remotes/$GIT_SVN^0"],
2137 if (defined $c && length $c) {
2138 my ($url, $rev, $uuid) = cmt_metadata($c);
2139 return ($rev, $c) if defined $rev;
2141 if ($_no_metadata) {
2142 my $offset = -41; # from tail
2144 open my $fh, '<', $REVDB or
2145 die "--no-metadata specified and $REVDB not readable\n";
2146 seek $fh, $offset, 2;
2148 defined $rl or return (undef, undef);
2150 while ($c ne $rl && tell $fh != 0) {
2152 seek $fh, $offset, 2;
2154 defined $rl or return (undef, undef);
2158 croak $! if ($rev < -1);
2159 $rev = ($rev - 41) / 41;
2160 close $fh or croak $!;
2163 return (undef, undef);
2166 sub libsvn_parse_revision {
2168 my $head = $SVN->get_latest_revnum();
2169 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2170 return ($base + 1, $head) if (defined $base);
2173 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2174 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2175 if ($_revision =~ /^BASE:(\d+)$/) {
2176 return ($base + 1, $1) if (defined $base);
2179 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2180 die "revision argument: $_revision not understood by git-svn\n",
2181 "Try using the command-line svn client instead\n";
2184 sub libsvn_traverse_ignore {
2185 my ($fh, $path, $r) = @_;
2187 my ($dirent, undef, $props) = $SVN->get_dir($path, $r);
2189 $p =~ s#^\Q$SVN->{svn_path}\E/##;
2190 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2191 if (my $s = $props->{'svn:ignore'}) {
2192 $s =~ s/[\r\n]+/\n/g;
2194 if (length $p == 0) {
2198 $s =~ s#\n#\n/$p/#g;
2199 print $fh "/$p/$s\n";
2202 foreach (sort keys %$dirent) {
2203 next if $dirent->{$_}->kind != $SVN::Node::dir;
2204 libsvn_traverse_ignore($fh, "$path/$_", $r);
2209 my ($path, $r0, $r1) = @_;
2210 return 1 if $r0 == $r1;
2212 # should be OK to use Pool here (r1 - r0) should be small
2213 $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
2214 return 0 if ($nr > 1);
2218 sub libsvn_find_parent_branch {
2219 my ($paths, $rev, $author, $date, $msg) = @_;
2220 my $svn_path = '/'.$SVN->{svn_path};
2222 # look for a parent from another branch:
2223 my $i = $paths->{$svn_path} or return;
2224 my $branch_from = $i->copyfrom_path or return;
2225 my $r = $i->copyfrom_rev;
2226 print STDERR "Found possible branch point: ",
2227 "$branch_from => $svn_path, $r\n";
2228 $branch_from =~ s#^/##;
2230 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
2231 my $url = $SVN->{repos_root};
2232 defined $l_map->{$url} or return;
2233 my $id = $l_map->{$url}->{$branch_from};
2234 if (!defined $id && $_follow_parent) {
2235 print STDERR "Following parent: $branch_from\@$r\n";
2236 # auto create a new branch and follow it
2237 $id = basename($branch_from);
2238 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
2239 while (-r "$GIT_DIR/svn/$id") {
2240 # just grow a tail if we're not unique enough :x
2244 return unless defined $id;
2246 my ($r0, $parent) = find_rev_before($r,$id,1);
2247 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
2248 defined(my $pid = fork) or croak $!;
2250 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2252 $SVN_URL = "$url/$branch_from";
2255 # we can't assume SVN_URL exists at r+1:
2256 $_revision = "0:$r";
2262 ($r0, $parent) = find_rev_before($r,$id,1);
2264 return unless (defined $r0 && defined $parent);
2265 if (revisions_eq($branch_from, $r0, $r)) {
2266 unlink $GIT_SVN_INDEX;
2267 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
2268 command_noisy('read-tree', $parent);
2269 unless ($SVN->can_do_switch) {
2270 return _libsvn_new_tree($paths, $rev, $author, $date,
2273 # do_switch works with svn/trunk >= r22312, but that is not
2274 # included with SVN 1.4.2 (the latest version at the moment),
2275 # so we can't rely on it.
2276 my $ra = Git::SVN::Ra->new("$url/$branch_from");
2277 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
2278 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
2279 die "SVN connection failed somewhere...\n";
2280 return libsvn_log_entry($rev, $author, $date, $msg, [$parent]);
2282 print STDERR "Nope, branch point not imported or unknown\n";
2286 sub libsvn_new_tree {
2287 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2290 my ($paths, $rev, $author, $date, $msg) = @_; # $pool is last
2291 _libsvn_new_tree($paths, $rev, $author, $date, $msg, []);
2294 sub _libsvn_new_tree {
2295 my ($paths, $rev, $author, $date, $msg, $parents) = @_;
2296 my $ed = SVN::Git::Fetcher->new({q => $_q});
2297 unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
2298 die "SVN connection failed somewhere...\n";
2300 libsvn_log_entry($rev, $author, $date, $msg, $parents, $ed);
2303 sub find_graft_path_commit {
2304 my ($tree_paths, $p1, $r1) = @_;
2305 foreach my $x (keys %$tree_paths) {
2306 next unless ($p1 =~ /^\Q$x\E/);
2307 my $i = $tree_paths->{$x};
2308 my ($r0, $parent) = find_rev_before($r1,$i,1);
2309 return $parent if (defined $r0 && $r0 == $r1);
2310 print STDERR "r$r1 of $i not imported\n";
2316 sub find_graft_path_parents {
2317 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2318 foreach my $x (keys %$tree_paths) {
2319 next unless ($p0 =~ /^\Q$x\E/);
2320 my $i = $tree_paths->{$x};
2321 my ($r, $parent) = find_rev_before($r0, $i, 1);
2322 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2323 my ($url_b, undef, $uuid_b) = cmt_metadata($c);
2324 my ($url_a, undef, $uuid_a) = cmt_metadata($parent);
2325 next if ($url_a && $url_b && $url_a eq $url_b &&
2326 $uuid_b eq $uuid_a);
2327 $grafts->{$c}->{$parent} = 1;
2332 sub libsvn_graft_file_copies {
2333 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2334 foreach (keys %$paths) {
2335 my $i = $paths->{$_};
2336 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2338 next unless (defined $p0 && defined $r0);
2343 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2345 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2350 my $old = $ENV{GIT_INDEX_FILE};
2351 $ENV{GIT_INDEX_FILE} = shift;
2358 $ENV{GIT_INDEX_FILE} = $old;
2360 delete $ENV{GIT_INDEX_FILE};
2364 sub libsvn_commit_cb {
2365 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2366 if ($_optimize_commits && $rev == ($r_last + 1)) {
2367 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2368 $log->{tree} = get_tree_from_treeish($c);
2369 my $cmt = git_commit($log, $cmt_last, $c);
2370 my @diff = command('diff-tree', $cmt, $c);
2372 print STDERR "Trees differ: $cmt $c\n",
2373 join('',@diff),"\n";
2381 sub libsvn_ls_fullurl {
2382 my $fullurl = shift;
2383 my $ra = Git::SVN::Ra->new($fullurl);
2385 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
2386 my ($dirent, undef, undef) = $ra->get_dir('', $r);
2387 foreach my $d (sort keys %$dirent) {
2388 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2389 push @ret, "$d/"; # add '/' for compat with cli svn
2395 sub libsvn_skip_unknown_revs {
2397 my $errno = $err->apr_err();
2398 # Maybe the branch we're tracking didn't
2399 # exist when the repo started, so it's
2400 # not an error if it doesn't, just continue
2402 # Wonderfully consistent library, eh?
2403 # 160013 - svn:// and file://
2404 # 175002 - http(s)://
2405 # 175007 - http(s):// (this repo required authorization, too...)
2406 # More codes may be discovered later...
2407 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2410 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2413 # Tie::File seems to be prone to offset errors if revisions get sparse,
2414 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2415 # one of my favorite modules is out :< Next up would be one of the DBM
2416 # modules, but I'm not sure which is most portable... So I'll just
2417 # go with something that's plain-text, but still capable of
2418 # being randomly accessed. So here's my ultra-simple fixed-width
2419 # database. All records are 40 characters + "\n", so it's easy to seek
2420 # to a revision: (41 * rev) is the byte offset.
2421 # A record of 40 0s denotes an empty revision.
2422 # And yes, it's still pretty fast (faster than Tie::File).
2424 my ($file, $rev, $commit) = @_;
2425 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2426 open my $fh, '+<', $file or croak $!;
2427 my $offset = $rev * 41;
2428 # assume that append is the common case:
2429 seek $fh, 0, 2 or croak $!;
2431 if ($pos < $offset) {
2432 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2434 seek $fh, $offset, 0 or croak $!;
2435 print $fh $commit,"\n";
2436 close $fh or croak $!;
2440 my ($file, $rev) = @_;
2442 my $offset = $rev * 41;
2443 open my $fh, '<', $file or croak $!;
2444 seek $fh, $offset, 0;
2445 if (tell $fh == $offset) {
2446 $ret = readline $fh;
2449 $ret = undef if ($ret =~ /^0{40}$/);
2452 close $fh or croak $!;
2456 sub copy_remote_ref {
2457 my $origin = $_cp_remote ? $_cp_remote : 'origin';
2458 my $ref = "refs/remotes/$GIT_SVN";
2459 if (command('ls-remote', $origin, $ref)) {
2460 command_noisy('fetch', $origin, "$ref:$ref");
2461 } elsif ($_cp_remote && !$_upgrade) {
2462 die "Unable to find remote reference: ",
2463 "refs/remotes/$GIT_SVN on $origin\n";
2468 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2469 $SVN::Node::dir.$SVN::Node::unknown.
2470 $SVN::Node::none.$SVN::Node::file.
2471 $SVN::Node::dir.$SVN::Node::unknown.
2472 $SVN::Auth::SSL::CNMISMATCH.
2473 $SVN::Auth::SSL::NOTYETVALID.
2474 $SVN::Auth::SSL::EXPIRED.
2475 $SVN::Auth::SSL::UNKNOWNCA.
2476 $SVN::Auth::SSL::OTHER;
2479 package SVN::Git::Fetcher;
2486 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2488 my ($class, $git_svn) = @_;
2489 my $self = SVN::Delta::Editor->new;
2490 bless $self, $class;
2491 $self->{c} = $git_svn->{c} if exists $git_svn->{c};
2492 $self->{q} = $git_svn->{q};
2493 $self->{empty} = {};
2494 $self->{dir_prop} = {};
2495 $self->{file_prop} = {};
2496 $self->{absent_dir} = {};
2497 $self->{absent_file} = {};
2498 ($self->{gui}, $self->{ctx}) = command_input_pipe(
2499 qw/update-index -z --index-info/);
2500 require Digest::MD5;
2508 sub open_directory {
2509 my ($self, $path, $pb, $rev) = @_;
2514 my ($self, $path, $rev, $pb) = @_;
2515 my $gui = $self->{gui};
2517 # remove entire directories.
2518 if (command('ls-tree', $self->{c}, '--', $path) =~ /^040000 tree/) {
2519 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2521 $self->{c}, '--', $path);
2524 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2525 print "\tD\t$_\n" unless $self->{q};
2527 print "\tD\t$path/\n" unless $self->{q};
2528 command_close_pipe($ls, $ctx);
2529 $self->{empty}->{$path} = 0
2531 print $gui '0 ',0 x 40,"\t",$path,"\0" or croak $!;
2532 print "\tD\t$path\n" unless $self->{q};
2538 my ($self, $path, $pb, $rev) = @_;
2539 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--',$path)
2540 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2541 unless (defined $mode && defined $blob) {
2542 die "$path was not found in commit $self->{c} (r$rev)\n";
2544 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2545 pool => SVN::Pool->new, action => 'M' };
2549 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2550 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2551 delete $self->{empty}->{$dir};
2552 { path => $path, mode_a => 100644, mode_b => 100644,
2553 pool => SVN::Pool->new, action => 'A' };
2557 my ($self, $path, $cp_path, $cp_rev) = @_;
2558 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2559 delete $self->{empty}->{$dir};
2560 $self->{empty}->{$path} = 1;
2564 sub change_dir_prop {
2565 my ($self, $db, $prop, $value) = @_;
2566 $self->{dir_prop}->{$db->{path}} ||= {};
2567 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2571 sub absent_directory {
2572 my ($self, $path, $pb) = @_;
2573 $self->{absent_dir}->{$pb->{path}} ||= [];
2574 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2579 my ($self, $path, $pb) = @_;
2580 $self->{absent_file}->{$pb->{path}} ||= [];
2581 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2585 sub change_file_prop {
2586 my ($self, $fb, $prop, $value) = @_;
2587 if ($prop eq 'svn:executable') {
2588 if ($fb->{mode_b} != 120000) {
2589 $fb->{mode_b} = defined $value ? 100755 : 100644;
2591 } elsif ($prop eq 'svn:special') {
2592 $fb->{mode_b} = defined $value ? 120000 : 100644;
2594 $self->{file_prop}->{$fb->{path}} ||= {};
2595 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2600 sub apply_textdelta {
2601 my ($self, $fb, $exp) = @_;
2602 my $fh = IO::File->new_tmpfile;
2604 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2605 # (but $base does not,) so dup() it for reading in close_file
2606 open my $dup, '<&', $fh or croak $!;
2607 my $base = IO::File->new_tmpfile;
2608 $base->autoflush(1);
2610 defined (my $pid = fork) or croak $!;
2612 open STDOUT, '>&', $base or croak $!;
2613 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2614 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2620 seek $base, 0, 0 or croak $!;
2621 my $md5 = Digest::MD5->new;
2622 $md5->addfile($base);
2623 my $got = $md5->hexdigest;
2624 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2626 " got: $got\n" if ($got ne $exp);
2629 seek $base, 0, 0 or croak $!;
2631 $fb->{base} = $base;
2632 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2636 my ($self, $fb, $exp) = @_;
2638 my $path = $fb->{path};
2639 if (my $fh = $fb->{fh}) {
2640 seek($fh, 0, 0) or croak $!;
2641 my $md5 = Digest::MD5->new;
2643 my $got = $md5->hexdigest;
2644 die "Checksum mismatch: $path\n",
2645 "expected: $exp\n got: $got\n" if ($got ne $exp);
2646 seek($fh, 0, 0) or croak $!;
2647 if ($fb->{mode_b} == 120000) {
2648 read($fh, my $buf, 5) == 5 or croak $!;
2649 $buf eq 'link ' or die "$path has mode 120000",
2650 "but is not a link\n";
2652 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2654 open STDIN, '<&', $fh or croak $!;
2655 exec qw/git-hash-object -w --stdin/ or croak $!;
2657 chomp($hash = do { local $/; <$out> });
2658 close $out or croak $!;
2659 close $fh or croak $!;
2660 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2661 close $fb->{base} or croak $!;
2663 $hash = $fb->{blob} or die "no blob information\n";
2666 my $gui = $self->{gui};
2667 print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
2668 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
2674 eval { command_close_pipe($self->{gui}, $self->{ctx}) };
2675 $self->SUPER::abort_edit(@_);
2680 command_close_pipe($self->{gui}, $self->{ctx});
2681 $self->{git_commit_ok} = 1;
2682 $self->SUPER::close_edit(@_);
2685 package SVN::Git::Editor;
2694 my $git_svn = shift;
2695 my $self = SVN::Delta::Editor->new(@_);
2696 bless $self, $class;
2697 foreach (qw/svn_path c r ra /) {
2698 die "$_ required!\n" unless (defined $git_svn->{$_});
2699 $self->{$_} = $git_svn->{$_};
2701 $self->{pool} = SVN::Pool->new;
2702 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2704 require Digest::MD5;
2709 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2713 (defined $_[1] && length $_[1]) ? $_[1] : ''
2717 my ($self, $path) = @_;
2718 $self->{ra}->{url} . '/' . $self->repo_path($path);
2722 my ($self, $q) = @_;
2723 my $rm = $self->{rm};
2724 delete $rm->{''}; # we never delete the url we're tracking
2727 foreach (keys %$rm) {
2728 my @d = split m#/#, $_;
2732 $c .= '/' . shift @d;
2736 delete $rm->{$self->{svn_path}};
2737 delete $rm->{''}; # we never delete the url we're tracking
2740 my ($fh, $ctx) = command_output_pipe(
2741 qw/ls-tree --name-only -r -z/, $self->{c});
2745 my @dn = split m#/#, $_;
2747 delete $rm->{join '/', @dn};
2754 command_close_pipe($fh, $ctx);
2756 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2757 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2758 $self->close_directory($bat->{$d}, $p);
2759 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2760 print "\tD+\t$d/\n" unless $q;
2761 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2766 sub open_or_add_dir {
2767 my ($self, $full_path, $baton) = @_;
2768 my $t = $self->{ra}->check_path($full_path, $self->{r});
2769 if ($t == $SVN::Node::none) {
2770 return $self->add_directory($full_path, $baton,
2771 undef, -1, $self->{pool});
2772 } elsif ($t == $SVN::Node::dir) {
2773 return $self->open_directory($full_path, $baton,
2774 $self->{r}, $self->{pool});
2776 print STDERR "$full_path already exists in repository at ",
2777 "r$self->{r} and it is not a directory (",
2778 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2783 my ($self, $path) = @_;
2784 my $bat = $self->{bat};
2785 $path = $self->repo_path($path);
2786 return $bat->{''} unless (length $path);
2787 my @p = split m#/+#, $path;
2789 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2792 $c .= '/' . shift @p;
2793 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2799 my ($self, $m, $q) = @_;
2800 my ($dir, $file) = split_path($m->{file_b});
2801 my $pbat = $self->ensure_path($dir);
2802 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2804 print "\tA\t$m->{file_b}\n" unless $q;
2805 $self->chg_file($fbat, $m);
2806 $self->close_file($fbat,undef,$self->{pool});
2810 my ($self, $m, $q) = @_;
2811 my ($dir, $file) = split_path($m->{file_b});
2812 my $pbat = $self->ensure_path($dir);
2813 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2814 $self->url_path($m->{file_a}), $self->{r});
2815 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $q;
2816 $self->chg_file($fbat, $m);
2817 $self->close_file($fbat,undef,$self->{pool});
2821 my ($self, $path, $pbat) = @_;
2822 my $rpath = $self->repo_path($path);
2823 my ($dir, $file) = split_path($rpath);
2824 $self->{rm}->{$dir} = 1;
2825 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2829 my ($self, $m, $q) = @_;
2830 my ($dir, $file) = split_path($m->{file_b});
2831 my $pbat = $self->ensure_path($dir);
2832 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2833 $self->url_path($m->{file_a}), $self->{r});
2834 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $q;
2835 $self->chg_file($fbat, $m);
2836 $self->close_file($fbat,undef,$self->{pool});
2838 ($dir, $file) = split_path($m->{file_a});
2839 $pbat = $self->ensure_path($dir);
2840 $self->delete_entry($m->{file_a}, $pbat);
2844 my ($self, $m, $q) = @_;
2845 my ($dir, $file) = split_path($m->{file_b});
2846 my $pbat = $self->ensure_path($dir);
2847 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2848 $pbat,$self->{r},$self->{pool});
2849 print "\t$m->{chg}\t$m->{file_b}\n" unless $q;
2850 $self->chg_file($fbat, $m);
2851 $self->close_file($fbat,undef,$self->{pool});
2854 sub T { shift->M(@_) }
2856 sub change_file_prop {
2857 my ($self, $fbat, $pname, $pval) = @_;
2858 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2862 my ($self, $fbat, $m) = @_;
2863 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2864 $self->change_file_prop($fbat,'svn:executable','*');
2865 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2866 $self->change_file_prop($fbat,'svn:executable',undef);
2868 my $fh = IO::File->new_tmpfile or croak $!;
2869 if ($m->{mode_b} =~ /^120/) {
2870 print $fh 'link ' or croak $!;
2871 $self->change_file_prop($fbat,'svn:special','*');
2872 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2873 $self->change_file_prop($fbat,'svn:special',undef);
2875 defined(my $pid = fork) or croak $!;
2877 open STDOUT, '>&', $fh or croak $!;
2878 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2882 $fh->flush == 0 or croak $!;
2883 seek $fh, 0, 0 or croak $!;
2885 my $md5 = Digest::MD5->new;
2886 $md5->addfile($fh) or croak $!;
2887 seek $fh, 0, 0 or croak $!;
2889 my $exp = $md5->hexdigest;
2890 my $pool = SVN::Pool->new;
2891 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2892 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2893 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2896 close $fh or croak $!;
2900 my ($self, $m, $q) = @_;
2901 my ($dir, $file) = split_path($m->{file_b});
2902 my $pbat = $self->ensure_path($dir);
2903 print "\tD\t$m->{file_b}\n" unless $q;
2904 $self->delete_entry($m->{file_b}, $pbat);
2909 my ($p,$bat) = ($self->{pool}, $self->{bat});
2910 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2911 $self->close_directory($bat->{$_}, $p);
2913 $self->SUPER::close_edit($p);
2919 $self->SUPER::abort_edit($self->{pool});
2920 $self->{pool}->clear;
2923 package Git::SVN::Ra;
2924 use vars qw/@ISA $config_dir/;
2927 my ($can_do_switch);
2930 # enforce temporary pool usage for some simple functions
2932 foreach (qw/get_latest_revnum rev_proplist get_file
2933 check_path get_dir get_uuid get_repos_root/) {
2936 my \$pool = SVN::Pool->new;
2937 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2939 wantarray ? \@ret : \$ret[0]; }\n";
2945 my ($class, $url) = @_;
2946 SVN::_Core::svn_config_ensure($config_dir, undef);
2947 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2948 SVN::Client::get_simple_provider(),
2949 SVN::Client::get_ssl_server_trust_file_provider(),
2950 SVN::Client::get_simple_prompt_provider(
2951 \&Git::SVN::Prompt::simple, 2),
2952 SVN::Client::get_ssl_client_cert_prompt_provider(
2953 \&Git::SVN::Prompt::ssl_client_cert, 2),
2954 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2955 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2956 SVN::Client::get_username_provider(),
2957 SVN::Client::get_ssl_server_trust_prompt_provider(
2958 \&Git::SVN::Prompt::ssl_server_trust),
2959 SVN::Client::get_username_prompt_provider(
2960 \&Git::SVN::Prompt::username, 2),
2962 my $config = SVN::Core::config_get_config($config_dir);
2963 my $self = SVN::Ra->new(url => $url, auth => $baton,
2965 pool => SVN::Pool->new,
2966 auth_provider_callbacks => $callbacks);
2967 $self->{svn_path} = $url;
2968 $self->{repos_root} = $self->get_repos_root;
2969 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2970 bless $self, $class;
2975 $self->{pool}->clear if $self->{pool};
2976 $self->SUPER::DESTROY(@_);
2981 my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2982 map { $_ => $self->{$_} } qw/config url
2983 auth auth_provider_callbacks repos_root svn_path/);
2984 bless $dup, ref $self;
2988 my ($self, @args) = @_;
2989 my $pool = SVN::Pool->new;
2990 $args[4]-- if $args[4] && ! $::_follow_parent;
2991 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2992 my $ret = $self->SUPER::get_log(@args, $pool);
2997 sub get_commit_editor {
2998 my ($self, $msg, $cb, $pool) = @_;
2999 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3000 $self->SUPER::get_commit_editor($msg, $cb, @lock, $pool);
3005 $self->{uuid} ||= $self->get_uuid;
3009 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
3010 my $pool = SVN::Pool->new;
3011 my $reporter = $self->do_update($rev_b, $path, $recurse,
3013 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3014 my $new = ($rev_a == $rev_b);
3015 $reporter->set_path($path, $rev_a, $new, @lock, $pool);
3016 $reporter->finish_report($pool);
3018 $editor->{git_commit_ok};
3022 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
3023 my $pool = SVN::Pool->new;
3024 my $reporter = $self->do_switch($rev_b, $path, $recurse,
3025 $url_b, $editor, $pool);
3026 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3027 $reporter->set_path($path, $rev_a, 0, @lock, $pool);
3028 $reporter->finish_report($pool);
3030 $editor->{git_commit_ok};
3035 unless (defined $can_do_switch) {
3036 my $pool = SVN::Pool->new;
3038 $self->do_switch(1, '', 0, $self->{url},
3039 SVN::Delta::Editor->new, $pool);
3044 $rep->abort_report($pool);
3056 $log_msg hashref as returned by libsvn_log_entry()
3058 msg => 'whitespace-formatted log entry
3059 ', # trailing newline is preserved
3060 revision => '8', # integer
3061 date => '2004-02-24T17:01:44.108345Z', # commit date
3062 author => 'committer name'
3065 @mods = array of diff-index line hashes, each element represents one line
3066 of diff-index output
3068 diff-index line ($m hash)
3070 mode_a => first column of diff-index output, no leading ':',
3071 mode_b => second column of diff-index output,
3072 sha1_b => sha1sum of the final blob,
3073 chg => change type [MCRADT],
3074 file_a => original file name of a file (iff chg is 'C' or 'R')
3075 file_b => new/current file name of a file (any chg)
3079 # retval of read_url_paths{,_all}();
3081 # repository root url
3082 'https://svn.musicpd.org' => {
3083 # repository path # GIT_SVN_ID
3084 'mpd/trunk' => 'trunk',
3085 'mpd/tags/0.11.5' => 'tags/0.11.5',
3090 I don't trust the each() function on unless I created %hash myself
3091 because the internal iterator may not have started at base.