2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '1.1.1-broken';
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:
23 # If SVN:: library support is added, please make the dependencies
24 # optional and preserve the capability to use the command-line client.
25 # use eval { require SVN::... } to make it lazy load
26 # We don't use any modules not in the standard Perl distribution:
29 use File::Basename qw/dirname basename/;
30 use File::Path qw/mkpath/;
31 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
33 use POSIX qw/strftime/;
36 memoize('revisions_eq');
38 my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
39 $_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
41 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
42 my $sha1 = qr/[a-f\d]{40}/;
43 my $sha1_short = qr/[a-f\d]{4,40}/;
44 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
45 $_find_copies_harder, $_l, $_cp_similarity,
46 $_repack, $_repack_nr, $_repack_flags,
47 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
48 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
49 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
50 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
51 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
52 my @repo_path_split_cache;
54 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
55 'branch|b=s' => \@_branch_from,
56 'branch-all-refs|B' => \$_branch_all_refs,
57 'authors-file|A=s' => \$_authors,
58 'repack:i' => \$_repack,
59 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
61 my ($_trunk, $_tags, $_branches);
62 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
63 'tags|t=s' => \$_tags,
64 'branches|b=s' => \$_branches );
65 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
67 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
68 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
71 fetch => [ \&fetch, "Download new revisions from SVN",
72 { 'revision|r=s' => \$_revision, %fc_opts } ],
73 init => [ \&init, "Initialize a repo for tracking" .
74 " (requires URL argument)",
76 commit => [ \&commit, "Commit git revisions to SVN",
77 { 'stdin|' => \$_stdin,
80 'find-copies-harder' => \$_find_copies_harder,
82 'copy-similarity|C=i'=> \$_cp_similarity,
85 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
86 { 'revision|r=i' => \$_revision } ],
87 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
88 { 'no-ignore-externals' => \$_no_ignore_ext,
89 'upgrade' => \$_upgrade } ],
90 'graft-branches' => [ \&graft_branches,
91 'Detect merges/branches from already imported history',
92 { 'merge-rx|m' => \@_opt_m,
93 'no-default-regex' => \$_no_default_regex,
94 'no-graft-copy' => \$_no_graft_copy } ],
95 'multi-init' => [ \&multi_init,
96 'Initialize multiple trees (like git-svnimport)',
97 { %multi_opts, %fc_opts } ],
98 'multi-fetch' => [ \&multi_fetch,
99 'Fetch multiple trees (like git-svnimport)',
101 'log' => [ \&show_log, 'Show commit logs',
102 { 'limit=i' => \$_limit,
103 'revision|r=s' => \$_revision,
104 'verbose|v' => \$_verbose,
105 'incremental' => \$_incremental,
106 'oneline' => \$_oneline,
107 'show-commit' => \$_show_commit,
108 'authors-file|A=s' => \$_authors,
113 for (my $i = 0; $i < @ARGV; $i++) {
114 if (defined $cmd{$ARGV[$i]}) {
121 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
123 read_repo_config(\%opts);
124 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
125 'version|V' => \$_version,
126 'id|i=s' => \$GIT_SVN);
127 exit 1 if (!$rv && $cmd ne 'log');
131 version() if $_version;
132 usage(1) unless defined $cmd;
134 load_authors() if $_authors;
135 load_all_refs() if $_branch_all_refs;
137 migration_check() unless $cmd =~ /^(?:init|multi-init)$/;
138 $cmd{$cmd}->[0]->(@ARGV);
141 ####################### primary functions ######################
143 my $exit = shift || 0;
144 my $fd = $exit ? \*STDERR : \*STDOUT;
146 git-svn - bidirectional operations between a single Subversion tree and git
147 Usage: $0 <command> [options] [arguments]\n
149 print $fd "Available commands:\n" unless $cmd;
151 foreach (sort keys %cmd) {
152 next if $cmd && $cmd ne $_;
153 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
154 foreach (keys %{$cmd{$_}->[2]}) {
155 # prints out arguments as they should be passed:
156 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
157 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
159 split /\|/,$_)," $x\n";
163 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
164 arbitrary identifier if you're tracking multiple SVN branches/repositories in
165 one git repository and want to keep them separate. See git-svn(1) for more
172 print "git-svn version $VERSION\n";
177 $SVN_URL = shift or undef;
180 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
182 check_upgrade_needed();
185 my $pid = open(my $rev_list,'-|');
186 defined $pid or croak $!;
188 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
191 while (<$rev_list>) {
194 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
195 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
196 next if (!@commit); # skip merges
197 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
198 if (!$rev || !$uuid) {
199 croak "Unable to extract revision or UUID from ",
200 "$c, $commit[$#commit]\n";
203 # if we merged or otherwise started elsewhere, this is
204 # how we break out of it
205 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
206 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
208 unless (defined $latest) {
209 if (!$SVN_URL && !$url) {
210 croak "SVN repository location required: $url\n";
217 revdb_set($REVDB, $rev, $c);
218 print "r$rev = $c\n";
219 $newest_rev = $rev if ($rev > $newest_rev);
221 close $rev_list or croak $?;
223 goto out if $_use_lib;
224 if (!chdir $SVN_WC) {
225 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
226 chdir $SVN_WC or croak $!;
230 defined $pid or croak $!;
232 my @svn_up = qw(svn up);
233 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
234 sys(@svn_up,"-r$newest_rev");
235 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
237 exec('git-write-tree') or croak $!;
244 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
245 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
251 $SVN_URL = shift or die "SVN repository location required " .
252 "as a command-line argument\n";
253 $SVN_URL =~ s!/+$!!; # strip trailing slash
254 unless (-d $GIT_DIR) {
255 my @init_db = ('git-init-db');
256 push @init_db, "--template=$_template" if defined $_template;
257 push @init_db, "--shared" if defined $_shared;
264 check_upgrade_needed();
265 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
266 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
267 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
268 refs/heads/master^0))) {
269 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
276 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
277 unless ($_revision) {
278 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
280 push @log_args, "-r$_revision";
281 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
283 my $svn_log = svn_log_raw(@log_args);
285 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
286 # don't need last_revision from grab_base_rev() because
287 # user could've specified a different revision to skip (they
288 # didn't want to import certain revisions into git for whatever
289 # reason, so trust $base->{revision} instead.
290 my (undef, $last_commit) = svn_grab_base_rev();
291 unless (-d $SVN_WC) {
292 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
293 chdir $SVN_WC or croak $!;
295 $last_commit = git_commit($base, @parents);
296 assert_tree($last_commit);
298 chdir $SVN_WC or croak $!;
300 # looks like a user manually cp'd and svn switch'ed
301 unless ($last_commit) {
302 sys(qw/svn revert -R ./);
303 assert_svn_wc_clean($base->{revision});
304 $last_commit = git_commit($base, @parents);
305 assert_tree($last_commit);
308 my @svn_up = qw(svn up);
309 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
311 while (my $log_msg = next_log_entry($svn_log)) {
312 if ($last->{revision} >= $log_msg->{revision}) {
313 croak "Out of order: last >= current: ",
314 "$last->{revision} >= $log_msg->{revision}\n";
316 # Revert is needed for cases like:
317 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
318 # I can't seem to reproduce something like that on a test...
319 sys(qw/svn revert -R ./);
320 assert_svn_wc_clean($last->{revision});
321 sys(@svn_up,"-r$log_msg->{revision}");
322 $last_commit = git_commit($log_msg, $last_commit, @parents);
325 close $svn_log->{fh};
326 $last->{commit} = $last_commit;
332 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
334 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
335 $SVN_LOG ||= libsvn_connect($repo);
336 $SVN ||= libsvn_connect($repo);
337 my ($last_rev, $last_commit) = svn_grab_base_rev();
338 my ($base, $head) = libsvn_parse_revision($last_rev);
340 return { revision => $last_rev, commit => $last_commit }
342 my $index = set_index($GIT_SVN_INDEX);
344 # limit ourselves and also fork() since get_log won't release memory
345 # after processing a revision and SVN stuff seems to leak
347 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
349 if (defined $last_commit) {
350 unless (-e $GIT_SVN_INDEX) {
351 sys(qw/git-read-tree/, $last_commit);
353 chomp (my $x = `git-write-tree`);
354 my ($y) = (`git-cat-file commit $last_commit`
355 =~ /^tree ($sha1)/m);
357 unlink $GIT_SVN_INDEX or croak $!;
358 sys(qw/git-read-tree/, $last_commit);
360 chomp ($x = `git-write-tree`);
362 print STDERR "trees ($last_commit) $y != $x\n",
363 "Something is seriously wrong...\n";
367 # fork, because using SVN::Pool with get_log() still doesn't
368 # seem to help enough to keep memory usage down.
369 defined(my $pid = fork) or croak $!;
371 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
373 # Yes I'm perfectly aware that the fourth argument
374 # below is the limit revisions number. Unfortunately
375 # performance sucks with it enabled, so it's much
376 # faster to fetch revision ranges instead of relying
378 $SVN_LOG->get_log( '/'.$SVN_PATH, $min, $max, 0, 1, 1,
382 $log_msg = libsvn_fetch(
384 $last_commit = git_commit(
389 $log_msg = libsvn_new_tree(@_);
390 $last_commit = git_commit(
398 ($last_rev, $last_commit) = svn_grab_base_rev();
399 last if ($max >= $head);
402 $max = $head if ($max > $head);
404 restore_index($index);
405 return { revision => $last_rev, commit => $last_commit };
410 check_upgrade_needed();
411 if ($_stdin || !@commits) {
412 print "Reading from stdin...\n";
415 if (/\b($sha1_short)\b/o) {
416 unshift @commits, $1;
421 foreach my $c (@commits) {
422 chomp(my @tmp = safe_qx('git-rev-parse',$c));
423 if (scalar @tmp == 1) {
425 } elsif (scalar @tmp > 1) {
426 push @revs, reverse (safe_qx('git-rev-list',@tmp));
428 die "Failed to rev-parse $c\n";
432 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
433 print "Done committing ",scalar @revs," revisions to SVN\n";
439 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
440 my $info = svn_info('.');
441 my $fetched = fetch();
442 if ($info->{Revision} != $fetched->{revision}) {
443 print STDERR "There are new revisions that were fetched ",
444 "and need to be merged (or acknowledged) ",
445 "before committing.\n";
448 $info = svn_info('.');
451 foreach my $c (@revs) {
452 my $mods = svn_checkout_tree($last, $c);
453 if (scalar @$mods == 0) {
454 print "Skipping, no changes detected\n";
457 $last = svn_commit_tree($last, $c);
463 my ($r_last, $cmt_last) = svn_grab_base_rev();
464 defined $r_last or die "Must have an existing revision to commit\n";
465 my $fetched = fetch();
466 if ($r_last != $fetched->{revision}) {
467 print STDERR "There are new revisions that were fetched ",
468 "and need to be merged (or acknowledged) ",
469 "before committing.\n",
470 "last rev: $r_last\n",
471 " current: $fetched->{revision}\n";
475 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
476 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
478 foreach my $c (@revs) {
479 # fork for each commit because there's a memory leak I
480 # can't track down... (it's probably in the SVN code)
481 defined(my $pid = open my $fh, '-|') or croak $!;
483 if (defined $LC_ALL) {
484 $ENV{LC_ALL} = $LC_ALL;
488 my $log_msg = get_commit_message($c, $commit_msg);
489 my $ed = SVN::Git::Editor->new(
493 svn_path => $SVN_PATH
495 $SVN->get_commit_editor(
506 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
508 print "No changes\nr$r_last = $cmt_last\n";
515 my ($r_new, $cmt_new, $no);
519 if (/^r(\d+) = ($sha1)$/o) {
520 ($r_new, $cmt_new) = ($1, $2);
521 } elsif ($_ eq 'No changes') {
525 close $fh or croak $?;
526 if (! defined $r_new && ! defined $cmt_new) {
528 die "Failed to parse revision information\n";
531 ($r_last, $cmt_last) = ($r_new, $cmt_new);
538 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
539 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
542 sub show_ignore_cmd {
543 require File::Find or die $!;
544 if (defined $_revision) {
545 die "-r/--revision option doesn't work unless the Perl SVN ",
546 "libraries are used\n";
548 chdir $SVN_WC or croak $!;
550 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
552 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
553 }}, no_chdir=>1},'.');
556 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
558 foreach my $i (sort keys %ign) {
559 print "\n# ",$i,"\n";
560 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
564 sub show_ignore_lib {
566 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
567 $SVN ||= libsvn_connect($repo);
568 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
569 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
573 my $gr_file = "$GIT_DIR/info/grafts";
574 my ($grafts, $comments) = read_grafts($gr_file);
578 # temporarily disable our grafts file to make this idempotent
579 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
580 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
583 my $l_map = read_url_paths();
584 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
585 unless ($_no_default_regex) {
586 push @re, ( qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
587 qr/\b(?:from|of)\s+(\S.+)/is );
589 foreach my $u (keys %$l_map) {
591 foreach my $p (keys %{$l_map->{$u}}) {
592 graft_merge_msg($grafts,$l_map,$u,$p);
595 unless ($_no_graft_copy) {
597 graft_file_copy_lib($grafts,$l_map,$u);
599 graft_file_copy_cmd($grafts,$l_map,$u);
604 write_grafts($grafts, $comments, $gr_file);
605 unlink "$gr_file~$gr_sha1" if $gr_sha1;
612 $url =~ s#/+$## if $url;
613 if ($_trunk !~ m#^[a-z\+]+://#) {
614 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
616 print STDERR "E: '$_trunk' is not a complete URL ",
617 "and a separate URL is not specified\n";
620 $_trunk = $url . $_trunk;
622 if ($GIT_SVN eq 'git-svn') {
623 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
624 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
628 complete_url_ls_init($url, $_branches, '--branches/-b', '');
629 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
633 # try to do trunk first, since branches/tags
634 # may be descended from it.
635 if (-e "$GIT_DIR/svn/trunk/info/url") {
636 fetch_child_id('trunk', @_);
638 rec_fetch('', "$GIT_DIR/svn", @_);
644 my $r_last = -1; # prevent dupes
645 rload_authors() if $_authors;
651 if (defined $_revision) {
652 if ($_revision =~ /^(\d+):(\d+)$/) {
653 ($r_min, $r_max) = ($1, $2);
654 } elsif ($_revision =~ /^\d+$/) {
655 $r_min = $r_max = $_revision;
657 print STDERR "-r$_revision is not supported, use ",
658 "standard \'git log\' arguments instead\n";
663 my $pid = open(my $log,'-|');
664 defined $pid or croak $!;
666 my @rl = (qw/git-log --abbrev-commit --pretty=raw
667 --default/, "remotes/$GIT_SVN");
668 push @rl, '--raw' if $_verbose;
669 exec(@rl, @args) or croak $!;
674 if (/^commit ($sha1_short)/o) {
676 if ($c && defined $c->{r} && $c->{r} != $r_last) {
678 process_commit($c, $r_min, $r_max, \@k) or
683 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
684 get_author_info($c, $1, $2, $3);
685 } elsif (/^(?:tree|parent|committer) /) {
687 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
688 push @{$c->{raw}}, $_;
691 push @{$c->{diff}}, $_;
693 push @{$c->{diff}}, $_;
694 } elsif (/^ (git-svn-id:.+)$/) {
695 my ($url, $rev, $uuid) = extract_metadata($1);
701 if ($c && defined $c->{r} && $c->{r} != $r_last) {
703 process_commit($c, $r_min, $r_max, \@k);
709 process_commit($_, $r_min, $r_max) foreach reverse @k;
713 print '-' x72,"\n" unless $_incremental || $_oneline;
716 ########################### utility functions #########################
720 print "Fetching $id\n";
721 my $ref = "$GIT_DIR/refs/remotes/$id";
722 my $ca = file_to_s($ref) if (-r $ref);
723 defined(my $pid = fork) or croak $!;
725 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
732 return unless $_repack || -r $ref;
734 my $cb = file_to_s($ref);
736 defined($pid = open my $fh, '-|') or croak $!;
737 my $url = file_to_s("$GIT_DIR/svn/$id/info/url");
740 exec qw/git-rev-list --pretty=raw/,
741 $ca ? "$ca..$cb" : $cb or croak $!;
744 if (/^ git-svn-id: $url\@\d+ [a-f0-9\-]+$/) {
746 } elsif (/^ git-svn-id: \S+\@\d+ [a-f0-9\-]+$/) {
754 my ($pfx, $p, @args) = @_;
756 foreach (sort <$p/*>) {
757 if (-r "$_/info/url") {
758 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
759 my $id = $pfx . basename $_;
760 next if $id eq 'trunk';
761 fetch_child_id($id, @args);
768 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
773 sub complete_url_ls_init {
774 my ($url, $var, $switch, $pfx) = @_;
776 print STDERR "W: $switch not specified\n";
780 if ($var !~ m#^[a-z\+]+://#) {
781 $var = '/' . $var if ($var !~ m#^/#);
783 print STDERR "E: '$var' is not a complete URL ",
784 "and a separate URL is not specified\n";
789 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
790 : safe_qx(qw/svn ls --non-interactive/, $var));
792 defined(my $pid = fork) or croak $!;
794 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
796 if ($u !~ m!\Q$var\E/(.+)$!) {
797 print STDERR "W: Unrecognized URL: $u\n";
798 die "This should never happen\n";
801 print "init $u => $id\n";
802 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
816 my @tmp = split m#/#, $_;
818 while (my $x = shift @tmp) {
824 foreach (sort {length $b <=> length $a} keys %common) {
825 if ($common{$_} == @$paths) {
832 # this isn't funky-filename safe, but good enough for now...
833 sub graft_file_copy_cmd {
834 my ($grafts, $l_map, $u) = @_;
835 my $paths = $l_map->{$u};
836 my $pfx = common_prefix([keys %$paths]);
837 $SVN_URL ||= $u.$pfx;
838 my $pid = open my $fh, '-|';
839 defined $pid or croak $!;
841 my @exec = qw/svn log -v/;
842 push @exec, "-r$_revision" if defined $_revision;
843 exec @exec, $u.$pfx or croak $!;
845 my ($r, $mp) = (undef, undef);
850 } elsif (/^r(\d+) \| /) {
851 $r = $1 unless defined $r;
852 } elsif (/^Changed paths:/) {
854 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
855 my ($p1, $p0, $r0) = ($1, $2, $3);
856 my $c = find_graft_path_commit($paths, $p1, $r);
858 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
863 sub graft_file_copy_lib {
864 my ($grafts, $l_map, $u) = @_;
865 my $tree_paths = $l_map->{$u};
866 my $pfx = common_prefix([keys %$tree_paths]);
867 my ($repo, $path) = repo_path_split($u.$pfx);
868 $SVN_LOG ||= libsvn_connect($repo);
869 $SVN ||= libsvn_connect($repo);
871 my ($base, $head) = libsvn_parse_revision();
873 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
874 my $eh = $SVN::Error::handler;
875 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
877 my $pool = SVN::Pool->new;
878 $SVN_LOG->get_log( "/$path", $min, $max, 0, 1, 1,
880 libsvn_graft_file_copies($grafts, $tree_paths,
884 last if ($max >= $head);
887 $max = $head if ($max > $head);
889 $SVN::Error::handler = $eh;
892 sub process_merge_msg_matches {
893 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
896 # merging with ourselves is not interesting
898 if ($l_map->{$u}->{$_}) {
904 foreach my $w (@weak) {
906 # no exact match, use branch name as regexp.
907 my $re = qr/\Q$w\E/i;
908 foreach (keys %{$l_map->{$u}}) {
917 foreach (keys %{$l_map->{$u}}) {
924 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
925 \s(?:[a-f\d\-]+)$/xsm);
926 unless (defined $rev) {
927 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
928 \@(?:[a-f\d\-]+)/xsm);
929 return unless defined $rev;
931 foreach my $m (@strong) {
932 my ($r0, $s0) = find_rev_before($rev, $m);
933 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
937 sub graft_merge_msg {
938 my ($grafts, $l_map, $u, $p, @re) = @_;
940 my $x = $l_map->{$u}->{$p};
941 my $rl = rev_list_raw($x);
942 while (my $c = next_rev_list_entry($rl)) {
943 foreach my $re (@re) {
944 my (@br) = ($c->{m} =~ /$re/g);
946 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
954 my $pool = SVN::Pool->new;
955 $SVN_UUID = $SVN->get_uuid($pool);
958 my $info = shift || svn_info('.');
959 $SVN_UUID = $info->{'Repository UUID'} or
960 croak "Repository UUID unreadable\n";
966 defined $pid or croak $!;
968 open my $null, '>', '/dev/null' or croak $!;
969 open STDERR, '>&', $null or croak $!;
970 open STDOUT, '>&', $null or croak $!;
977 sub repo_path_split {
978 my $full_url = shift;
979 $full_url =~ s#/+$##;
981 foreach (@repo_path_split_cache) {
982 if ($full_url =~ s#$_##) {
984 $full_url =~ s#^/+##;
985 return ($u, $full_url);
989 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
991 my @paths = split(m#/+#, $path);
995 $SVN = libsvn_connect($url);
996 last if (defined $SVN &&
997 defined eval { $SVN->get_latest_revnum });
998 my $n = shift @paths || last;
1002 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1003 my $n = shift @paths || last;
1007 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1008 $path = join('/',@paths);
1009 return ($url, $path);
1013 defined $SVN_URL or croak "SVN repository location required\n";
1014 unless (-d $GIT_DIR) {
1015 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1017 mkpath([$GIT_SVN_DIR]);
1018 mkpath(["$GIT_SVN_DIR/info"]);
1019 open my $fh, '>>',$REVDB or croak $!;
1021 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1025 sub assert_svn_wc_clean {
1026 return if $_use_lib;
1028 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1029 my $lcr = svn_info('.')->{'Last Changed Rev'};
1030 if ($svn_rev != $lcr) {
1031 print STDERR "Checking for copy-tree ... ";
1032 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1033 "-r$lcr:$svn_rev")));
1035 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1037 print STDERR "OK!\n";
1040 my @status = grep(!/^Performing status on external/,(`svn status`));
1041 @status = grep(!/^\s*$/,@status);
1042 if (scalar @status) {
1043 print STDERR "Tree ($SVN_WC) is not clean:\n";
1044 print STDERR $_ foreach @status;
1049 sub get_tree_from_treeish {
1051 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1052 chomp(my $type = `git-cat-file -t $treeish`);
1054 while ($type eq 'tag') {
1055 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1057 if ($type eq 'commit') {
1058 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1059 ($expected) = ($expected =~ /^tree ($sha1)$/);
1060 die "Unable to get tree from $treeish\n" unless $expected;
1061 } elsif ($type eq 'tree') {
1062 $expected = $treeish;
1064 die "$treeish is a $type, expected tree, tag or commit\n";
1070 return if $_use_lib;
1072 my $expected = get_tree_from_treeish($treeish);
1074 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1076 unlink $tmpindex or croak $!;
1078 my $old_index = set_index($tmpindex);
1080 chomp(my $tree = `git-write-tree`);
1081 restore_index($old_index);
1082 if ($tree ne $expected) {
1083 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1088 sub parse_diff_tree {
1089 my $diff_fh = shift;
1093 while (<$diff_fh>) {
1094 chomp $_; # this gets rid of the trailing "\0"
1095 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1096 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1097 push @mods, { mode_a => $1, mode_b => $2,
1098 sha1_b => $3, chg => $4 };
1099 if ($4 =~ /^(?:C|R)$/) {
1104 } elsif ($state eq 'file_a') {
1105 my $x = $mods[$#mods] or croak "Empty array\n";
1106 if ($x->{chg} !~ /^(?:C|R)$/) {
1107 croak "Error parsing $_, $x->{chg}\n";
1111 } elsif ($state eq 'file_b') {
1112 my $x = $mods[$#mods] or croak "Empty array\n";
1113 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1114 croak "Error parsing $_, $x->{chg}\n";
1116 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1117 croak "Error parsing $_, $x->{chg}\n";
1122 croak "Error parsing $_\n";
1125 close $diff_fh or croak $?;
1130 sub svn_check_prop_executable {
1132 return if -l $m->{file_b};
1133 if ($m->{mode_b} =~ /755$/) {
1134 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1135 if ($m->{mode_a} !~ /755$/) {
1136 sys(qw(svn propset svn:executable 1), $m->{file_b});
1138 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1139 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1140 sys(qw(svn propdel svn:executable), $m->{file_b});
1141 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1142 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1146 sub svn_ensure_parent_path {
1147 my $dir_b = dirname(shift);
1148 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1149 mkpath([$dir_b]) unless (-d $dir_b);
1150 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1153 sub precommit_check {
1155 my (%rm_file, %rmdir_check, %added_check);
1157 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1158 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1159 if ($m->{chg} eq 'R') {
1160 if (-d $m->{file_b}) {
1161 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1163 # dir/$file => dir/file/$file
1164 my $dirname = dirname($m->{file_b});
1165 while ($dirname ne File::Spec->curdir) {
1166 if ($dirname ne $m->{file_a}) {
1167 $dirname = dirname($dirname);
1170 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1172 # baz/zzz => baz (baz is a file)
1173 $dirname = dirname($m->{file_a});
1174 while ($dirname ne File::Spec->curdir) {
1175 if ($dirname ne $m->{file_b}) {
1176 $dirname = dirname($dirname);
1179 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1182 if ($m->{chg} =~ /^(D|R)$/) {
1183 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1184 $rm_file{ $m->{$t} } = 1;
1185 my $dirname = dirname( $m->{$t} );
1186 my $basename = basename( $m->{$t} );
1187 $rmdir_check{$dirname}->{$basename} = 1;
1188 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1189 if (-d $m->{file_b}) {
1190 err_dir_to_file($m->{file_b});
1192 my $dirname = dirname( $m->{file_b} );
1193 my $basename = basename( $m->{file_b} );
1194 $added_check{$dirname}->{$basename} = 1;
1195 while ($dirname ne File::Spec->curdir) {
1196 if ($rm_file{$dirname}) {
1197 err_file_to_dir($m->{file_b});
1199 $dirname = dirname $dirname;
1203 return (\%rmdir_check, \%added_check);
1205 sub err_dir_to_file {
1207 print STDERR "Node change from directory to file ",
1208 "is not supported by Subversion: ",$file,"\n";
1211 sub err_file_to_dir {
1213 print STDERR "Node change from file to directory ",
1214 "is not supported by Subversion: ",$file,"\n";
1221 my ($from, $treeish) = @_;
1223 print "diff-tree $from $treeish\n";
1224 my $pid = open my $diff_fh, '-|';
1225 defined $pid or croak $!;
1227 my @diff_tree = qw(git-diff-tree -z -r);
1228 if ($_cp_similarity) {
1229 push @diff_tree, "-C$_cp_similarity";
1231 push @diff_tree, '-C';
1233 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1234 push @diff_tree, "-l$_l" if defined $_l;
1235 exec(@diff_tree, $from, $treeish) or croak $!;
1237 return parse_diff_tree($diff_fh);
1240 sub svn_checkout_tree {
1241 my ($from, $treeish) = @_;
1242 my $mods = get_diff($from->{commit}, $treeish);
1243 return $mods unless (scalar @$mods);
1244 my ($rm, $add) = precommit_check($mods);
1246 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1247 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1248 if ($m->{chg} eq 'C') {
1249 svn_ensure_parent_path( $m->{file_b} );
1250 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1251 apply_mod_line_blob($m);
1252 svn_check_prop_executable($m);
1253 } elsif ($m->{chg} eq 'D') {
1254 sys(qw(svn rm --force), $m->{file_b});
1255 } elsif ($m->{chg} eq 'R') {
1256 svn_ensure_parent_path( $m->{file_b} );
1257 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1258 apply_mod_line_blob($m);
1259 svn_check_prop_executable($m);
1260 } elsif ($m->{chg} eq 'M') {
1261 apply_mod_line_blob($m);
1262 svn_check_prop_executable($m);
1263 } elsif ($m->{chg} eq 'T') {
1264 sys(qw(svn rm --force),$m->{file_b});
1265 apply_mod_line_blob($m);
1266 sys(qw(svn add --force), $m->{file_b});
1267 svn_check_prop_executable($m);
1268 } elsif ($m->{chg} eq 'A') {
1269 svn_ensure_parent_path( $m->{file_b} );
1270 apply_mod_line_blob($m);
1271 sys(qw(svn add --force), $m->{file_b});
1272 svn_check_prop_executable($m);
1274 croak "Invalid chg: $m->{chg}\n";
1278 assert_tree($treeish);
1279 if ($_rmdir) { # remove empty directories
1280 handle_rmdir($rm, $add);
1282 assert_tree($treeish);
1286 sub libsvn_checkout_tree {
1287 my ($from, $treeish, $ed) = @_;
1288 my $mods = get_diff($from, $treeish);
1289 return $mods unless (scalar @$mods);
1290 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1291 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1293 if (defined $o{$f}) {
1296 croak "Invalid change type: $f\n";
1299 $ed->rmdirs if $_rmdir;
1303 # svn ls doesn't work with respect to the current working tree, but what's
1304 # in the repository. There's not even an option for it... *sigh*
1305 # (added files don't show up and removed files remain in the ls listing)
1306 sub svn_ls_current {
1307 my ($dir, $rm, $add) = @_;
1308 chomp(my @ls = safe_qx('svn','ls',$dir));
1311 s#/$##; # trailing slashes are evil
1312 push @ret, $_ unless $rm->{$dir}->{$_};
1314 if (exists $add->{$dir}) {
1315 push @ret, keys %{$add->{$dir}};
1321 my ($rm, $add) = @_;
1323 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1324 my $ls = svn_ls_current($dir, $rm, $add);
1325 next if (scalar @$ls);
1326 sys(qw(svn rm --force),$dir);
1328 my $dn = dirname $dir;
1329 $rm->{ $dn }->{ basename $dir } = 1;
1330 $ls = svn_ls_current($dn, $rm, $add);
1331 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1332 sys(qw(svn rm --force),$dn);
1333 $dir = basename $dn;
1335 $rm->{ $dn }->{ $dir } = 1;
1336 $ls = svn_ls_current($dn, $rm, $add);
1341 sub get_commit_message {
1342 my ($commit, $commit_msg) = (@_);
1343 my %log_msg = ( msg => '' );
1344 open my $msg, '>', $commit_msg or croak $!;
1346 print "commit: $commit\n";
1347 chomp(my $type = `git-cat-file -t $commit`);
1348 if ($type eq 'commit') {
1349 my $pid = open my $msg_fh, '-|';
1350 defined $pid or croak $!;
1353 exec(qw(git-cat-file commit), $commit) or croak $!;
1358 $in_msg = 1 if (/^\s*$/);
1359 } elsif (/^git-svn-id: /) {
1360 # skip this, we regenerate the correct one
1361 # on re-fetch anyways
1363 print $msg $_ or croak $!;
1366 close $msg_fh or croak $?;
1368 close $msg or croak $!;
1370 if ($_edit || ($type eq 'tree')) {
1371 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1372 system($editor, $commit_msg);
1375 # file_to_s removes all trailing newlines, so just use chomp() here:
1376 open $msg, '<', $commit_msg or croak $!;
1377 { local $/; chomp($log_msg{msg} = <$msg>); }
1378 close $msg or croak $!;
1383 sub svn_commit_tree {
1384 my ($last, $commit) = @_;
1385 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1386 my $log_msg = get_commit_message($commit, $commit_msg);
1387 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1388 print "Committing $commit: $oneline\n";
1390 if (defined $LC_ALL) {
1391 $ENV{LC_ALL} = $LC_ALL;
1393 delete $ENV{LC_ALL};
1395 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1398 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1399 if (!defined $committed) {
1400 my $out = join("\n",@ci_output);
1401 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1402 $out, "\n\nAssuming English locale...";
1403 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1404 defined $committed or die " FAILED!\n",
1405 "Commit output failed to parse committed revision!\n",
1406 print STDERR " OK\n";
1409 my @svn_up = qw(svn up);
1410 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1411 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1412 push @svn_up, "-r$committed";
1414 my $info = svn_info('.');
1415 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1416 if ($info->{'Last Changed Rev'} != $committed) {
1417 croak "$info->{'Last Changed Rev'} != $committed\n"
1419 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1420 /(\d{4})\-(\d\d)\-(\d\d)\s
1421 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1422 or croak "Failed to parse date: $date\n";
1423 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1424 $log_msg->{author} = $info->{'Last Changed Author'};
1425 $log_msg->{revision} = $committed;
1426 $log_msg->{msg} .= "\n";
1427 $log_msg->{parents} = [ $last->{commit} ];
1428 $log_msg->{commit} = git_commit($log_msg, $commit);
1431 # resync immediately
1432 push @svn_up, "-r$last->{revision}";
1434 return fetch("$committed=$commit");
1439 my $pid = open my $fh, '-|';
1440 defined $pid or croak $!;
1442 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1444 return { fh => $fh, t => { } };
1447 sub next_rev_list_entry {
1452 if (/^commit ($sha1)$/o) {
1454 $rl->{t} = { c => $1 };
1459 } elsif (/^parent ($sha1)$/o) {
1466 return ($x != $rl->{t}) ? $x : undef;
1469 # read the entire log into a temporary file (which is removed ASAP)
1470 # and store the file handle + parser state
1472 my (@log_args) = @_;
1473 my $log_fh = IO::File->new_tmpfile or croak $!;
1475 defined $pid or croak $!;
1477 open STDOUT, '>&', $log_fh or croak $!;
1478 exec (qw(svn log), @log_args) or croak $!
1482 seek $log_fh, 0, 0 or croak $!;
1483 return { state => 'sep', fh => $log_fh };
1486 sub next_log_entry {
1487 my $log = shift; # retval of svn_log_raw()
1489 my $fh = $log->{fh};
1494 if ($log->{state} eq 'msg') {
1495 if ($ret->{lines}) {
1496 $ret->{msg} .= $_."\n";
1497 unless(--$ret->{lines}) {
1498 $log->{state} = 'sep';
1501 croak "Log parse error at: $_\n",
1507 if ($log->{state} ne 'sep') {
1508 croak "Log parse error at: $_\n",
1509 "state: $log->{state}\n",
1513 $log->{state} = 'rev';
1515 # if we have an empty log message, put something there:
1517 $ret->{msg} ||= "\n";
1518 delete $ret->{lines};
1523 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1525 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1526 ($lines) = ($lines =~ /(\d+)/);
1527 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1528 /(\d{4})\-(\d\d)\-(\d\d)\s
1529 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1530 or croak "Failed to parse date: $date\n";
1531 $ret = { revision => $rev,
1532 date => "$tz $Y-$m-$d $H:$M:$S",
1536 if (defined $_authors && ! defined $users{$author}) {
1537 die "Author: $author not defined in ",
1540 $log->{state} = 'msg_start';
1543 # skip the first blank line of the message:
1544 if ($log->{state} eq 'msg_start' && /^$/) {
1545 $log->{state} = 'msg';
1546 } elsif ($log->{state} eq 'msg') {
1547 if ($ret->{lines}) {
1548 $ret->{msg} .= $_."\n";
1549 unless (--$ret->{lines}) {
1550 $log->{state} = 'sep';
1553 croak "Log parse error at: $_\n",
1554 $ret->{revision},"\n";
1562 my $url = shift || $SVN_URL;
1564 my $pid = open my $info_fh, '-|';
1565 defined $pid or croak $!;
1568 exec(qw(svn info),$url) or croak $!;
1572 # only single-lines seem to exist in svn info output
1573 while (<$info_fh>) {
1575 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1577 push @{$ret->{-order}}, $1;
1580 close $info_fh or croak $?;
1584 sub sys { system(@_) == 0 or croak $? }
1587 my ($from, $to) = @_;
1588 my $es = svn_propget_base('svn:eol-style', $to);
1589 open my $rfd, '<', $from or croak $!;
1590 binmode $rfd or croak $!;
1591 open my $wfd, '>', $to or croak $!;
1592 binmode $wfd or croak $!;
1593 eol_cp_fd($rfd, $wfd, $es);
1594 close $rfd or croak $!;
1595 close $wfd or croak $!;
1599 my ($rfd, $wfd, $es) = @_;
1600 my $eol = defined $es ? $EOL{$es} : undef;
1605 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1608 if ($buf =~ /\015$/) {
1610 defined($r = sysread($rfd,$c,1)) or croak $!;
1611 $buf .= $c if $r > 0;
1613 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1616 for ($w = 0; $w < $r; $w += $t) {
1617 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1623 sub do_update_index {
1624 my ($z_cmd, $cmd, $no_text_base) = @_;
1626 my $z = open my $p, '-|';
1627 defined $z or croak $!;
1628 unless ($z) { exec @$z_cmd or croak $! }
1630 my $pid = open my $ui, '|-';
1631 defined $pid or croak $!;
1633 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1636 while (my $x = <$p>) {
1638 if (!$no_text_base && lstat $x && ! -l _ &&
1639 svn_propget_base('svn:keywords', $x)) {
1640 my $mode = -x _ ? 0755 : 0644;
1641 my ($v,$d,$f) = File::Spec->splitpath($x);
1642 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1643 'text-base',"$f.svn-base");
1646 $tb = File::Spec->catfile($d, '.svn',
1647 'text-base',"$f.svn-base");
1650 unlink $x or croak $!;
1652 chmod(($mode &~ umask), $x) or croak $!;
1656 close $ui or croak $?;
1660 return if $_use_lib;
1662 if (!-f "$GIT_SVN_DIR/info/exclude") {
1663 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1664 print $fd '.svn',"\n";
1665 close $fd or croak $!;
1667 my $no_text_base = shift;
1668 do_update_index([qw/git-diff-files --name-only -z/],
1671 do_update_index([qw/git-ls-files -z --others/,
1672 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1678 my ($str, $file, $mode) = @_;
1679 open my $fd,'>',$file or croak $!;
1680 print $fd $str,"\n" or croak $!;
1681 close $fd or croak $!;
1682 chmod ($mode &~ umask, $file) if (defined $mode);
1687 open my $fd,'<',$file or croak "$!: file: $file\n";
1690 close $fd or croak $!;
1695 sub assert_revision_unknown {
1697 if (my $c = revdb_get($REVDB, $r)) {
1698 croak "$r = $c already exists! Why are we refetching it?";
1704 my @x = safe_qx('git-cat-file','commit',$x);
1705 my @y = safe_qx('git-cat-file','commit',$y);
1706 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1707 || $y[0] !~ /^tree $sha1\n$/) {
1708 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1715 my ($log_msg, @parents) = @_;
1716 assert_revision_unknown($log_msg->{revision});
1717 map_tree_joins() if (@_branch_from && !%tree_map);
1719 my (@tmp_parents, @exec_parents, %seen_parent);
1720 if (my $lparents = $log_msg->{parents}) {
1721 @tmp_parents = @$lparents
1723 # commit parents can be conditionally bound to a particular
1724 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1725 foreach my $p (@parents) {
1726 next unless defined $p;
1727 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1728 if ($1 == $log_msg->{revision}) {
1729 push @tmp_parents, $2;
1732 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1735 my $tree = $log_msg->{tree};
1736 if (!defined $tree) {
1737 my $index = set_index($GIT_SVN_INDEX);
1739 chomp($tree = `git-write-tree`);
1741 restore_index($index);
1743 if (exists $tree_map{$tree}) {
1744 push @tmp_parents, @{$tree_map{$tree}};
1746 foreach (@tmp_parents) {
1747 next if $seen_parent{$_};
1748 $seen_parent{$_} = 1;
1749 push @exec_parents, $_;
1750 # MAXPARENT is defined to 16 in commit-tree.c:
1751 last if @exec_parents > 16;
1754 defined(my $pid = open my $out_fh, '-|') or croak $!;
1756 my $msg_fh = IO::File->new_tmpfile or croak $!;
1757 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1758 "$SVN_URL\@$log_msg->{revision}",
1759 " $SVN_UUID\n" or croak $!;
1760 $msg_fh->flush == 0 or croak $!;
1761 seek $msg_fh, 0, 0 or croak $!;
1762 set_commit_env($log_msg);
1763 my @exec = ('git-commit-tree',$tree);
1764 push @exec, '-p', $_ foreach @exec_parents;
1765 open STDIN, '<&', $msg_fh or croak $!;
1766 exec @exec or croak $!;
1768 chomp(my $commit = do { local $/; <$out_fh> });
1769 close $out_fh or croak $?;
1770 if ($commit !~ /^$sha1$/o) {
1771 croak "Failed to commit, invalid sha1: $commit\n";
1773 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1774 if (my $primary_parent = shift @exec_parents) {
1775 quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1776 push @update_ref, $primary_parent unless $?;
1779 revdb_set($REVDB, $log_msg->{revision}, $commit);
1781 # this output is read via pipe, do not change:
1782 print "r$log_msg->{revision} = $commit\n";
1788 if ($_repack && (--$_repack_nr == 0)) {
1789 $_repack_nr = $_repack;
1790 sys("git repack $_repack_flags");
1794 sub set_commit_env {
1796 my $author = $log_msg->{author};
1797 if (!defined $author || length $author == 0) {
1798 $author = '(no author)';
1800 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1801 : ($author,"$author\@$SVN_UUID");
1802 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1803 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1804 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1807 sub apply_mod_line_blob {
1809 if ($m->{mode_b} =~ /^120/) {
1810 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1812 blob_to_file($m->{sha1_b}, $m->{file_b});
1816 sub blob_to_symlink {
1817 my ($blob, $link) = @_;
1818 defined $link or croak "\$link not defined!\n";
1819 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1820 if (-l $link || -f _) {
1821 unlink $link or croak $!;
1824 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1825 symlink $dest, $link or croak $!;
1829 my ($blob, $file) = @_;
1830 defined $file or croak "\$file not defined!\n";
1831 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1832 if (-l $file || -f _) {
1833 unlink $file or croak $!;
1836 open my $blob_fh, '>', $file or croak "$!: $file\n";
1838 defined $pid or croak $!;
1841 open STDOUT, '>&', $blob_fh or croak $!;
1842 exec('git-cat-file','blob',$blob) or croak $!;
1847 close $blob_fh or croak $!;
1851 my $pid = open my $child, '-|';
1852 defined $pid or croak $!;
1854 exec(@_) or croak $!;
1856 my @ret = (<$child>);
1857 close $child or croak $?;
1858 die $? if $?; # just in case close didn't error out
1859 return wantarray ? @ret : join('',@ret);
1862 sub svn_compat_check {
1863 my @co_help = safe_qx(qw(svn co -h));
1864 unless (grep /ignore-externals/,@co_help) {
1865 print STDERR "W: Installed svn version does not support ",
1866 "--ignore-externals\n";
1867 $_no_ignore_ext = 1;
1869 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1870 $_svn_co_url_revs = 1;
1872 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1873 $_svn_pg_peg_revs = 1;
1876 # I really, really hope nobody hits this...
1877 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1879 W: The installed svn version does not support the --stop-on-copy flag in
1881 Lets hope the directory you're tracking is not a branch or tag
1882 and was never moved within the repository...
1888 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1889 # (and they won't honor URL@<rev> without -r<rev>, too!)
1890 sub svn_cmd_checkout {
1891 my ($url, $rev, $dir) = @_;
1892 my @cmd = ('svn','co', "-r$rev");
1893 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1894 $url .= "\@$rev" if $_svn_co_url_revs;
1895 sys(@cmd, $url, $dir);
1898 sub check_upgrade_needed {
1900 open my $fh, '>>',$REVDB or croak $!;
1904 my $pid = open my $child, '-|';
1905 defined $pid or croak $!;
1908 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1910 my @ret = (<$child>);
1911 close $child or croak $?;
1912 die $? if $?; # just in case close didn't error out
1913 return wantarray ? @ret : join('',@ret);
1916 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1918 print STDERR "Please run: $0 rebuild --upgrade\n";
1923 # fills %tree_map with a reverse mapping of trees to commits. Useful
1924 # for finding parents to commit on.
1925 sub map_tree_joins {
1927 foreach my $br (@_branch_from) {
1928 my $pid = open my $pipe, '-|';
1929 defined $pid or croak $!;
1931 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1935 if (/^commit ($sha1)$/o) {
1938 # if we've seen a commit,
1939 # we've seen its parents
1940 last if $seen{$commit};
1941 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1942 unless (defined $tree) {
1943 die "Failed to parse commit $commit\n";
1945 push @{$tree_map{$tree}}, $commit;
1949 close $pipe; # we could be breaking the pipe early
1954 if (@_branch_from) {
1955 print STDERR '--branch|-b parameters are ignored when ',
1956 "--branch-all-refs|-B is passed\n";
1959 # don't worry about rev-list on non-commit objects/tags,
1960 # it shouldn't blow up if a ref is a blob or tree...
1961 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1964 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1966 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1967 while (<$authors>) {
1969 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1970 my ($user, $name, $email) = ($1, $2, $3);
1971 $users{$user} = [$name, $email];
1973 close $authors or croak $!;
1977 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1978 while (<$authors>) {
1980 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1981 my ($user, $name, $email) = ($1, $2, $3);
1982 $rusers{"$name <$email>"} = $user;
1984 close $authors or croak $!;
1987 sub svn_propget_base {
1989 $f .= '@BASE' if $_svn_pg_peg_revs;
1990 return safe_qx(qw/svn propget/, $p, $f);
1995 foreach (`git-rev-parse --symbolic --all`) {
1996 next unless s#^refs/remotes/##;
1998 next unless -f "$GIT_DIR/svn/$_/info/url";
2006 defined(my $pid = fork) or croak $!;
2008 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2010 exit 0 if -r $REVDB;
2011 print "Upgrading svn => git mapping...\n";
2012 open my $fh, '>>',$REVDB or croak $!;
2015 print "Done upgrading. You may now delete the ",
2016 "deprecated $GIT_SVN_DIR/revs directory\n";
2024 sub migration_check {
2025 migrate_revdb() unless (-e $REVDB);
2026 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2027 print "Upgrading repository...\n";
2028 unless (-d "$GIT_DIR/svn") {
2029 mkdir "$GIT_DIR/svn" or croak $!;
2031 print "Data from a previous version of git-svn exists, but\n\t",
2032 "$GIT_SVN_DIR\n\t(required for this version ",
2033 "($VERSION) of git-svn) does not.\n";
2035 foreach my $x (`git-rev-parse --symbolic --all`) {
2036 next unless $x =~ s#^refs/remotes/##;
2038 next unless -f "$GIT_DIR/$x/info/url";
2039 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2041 my $dn = dirname("$GIT_DIR/svn/$x");
2042 mkpath([$dn]) unless -d $dn;
2043 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2045 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2046 print "Done upgrading.\n";
2049 sub find_rev_before {
2050 my ($r, $id, $eq_ok) = @_;
2051 my $f = "$GIT_DIR/svn/$id/.rev_db";
2052 return (undef,undef) unless -r $f;
2055 if (my $c = revdb_get($f, $r)) {
2060 return (undef, undef);
2064 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2065 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2066 $REVDB = "$GIT_SVN_DIR/.rev_db";
2067 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2069 $SVN_WC = "$GIT_SVN_DIR/tree";
2072 # convert GetOpt::Long specs for use by git-repo-config
2073 sub read_repo_config {
2074 return unless -d $GIT_DIR;
2076 foreach my $o (keys %$opts) {
2077 my $v = $opts->{$o};
2078 my ($key) = ($o =~ /^([a-z\-]+)/);
2080 my $arg = 'git-repo-config';
2081 $arg .= ' --int' if ($o =~ /[:=]i$/);
2082 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2083 if (ref $v eq 'ARRAY') {
2084 chomp(my @tmp = `$arg --get-all svn.$key`);
2087 chomp(my $tmp = `$arg --get svn.$key`);
2088 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2095 sub set_default_vals {
2096 if (defined $_repack) {
2097 $_repack = 1000 if ($_repack <= 0);
2098 $_repack_nr = $_repack;
2099 $_repack_flags ||= '-d';
2104 my $gr_file = shift;
2105 my ($grafts, $comments) = ({}, {});
2106 if (open my $fh, '<', $gr_file) {
2109 if (/^($sha1)\s+/) {
2112 @{$comments->{$c}} = @tmp;
2115 foreach my $p (split /\s+/, $_) {
2116 $grafts->{$c}->{$p} = 1;
2122 close $fh or croak $!;
2123 @{$comments->{'END'}} = @tmp if @tmp;
2125 return ($grafts, $comments);
2129 my ($grafts, $comments, $gr_file) = @_;
2131 open my $fh, '>', $gr_file or croak $!;
2132 foreach my $c (sort keys %$grafts) {
2133 if ($comments->{$c}) {
2134 print $fh $_ foreach @{$comments->{$c}};
2136 my $p = $grafts->{$c};
2137 delete $p->{$c}; # commits are not self-reproducing...
2138 my $pid = open my $ch, '-|';
2139 defined $pid or croak $!;
2141 exec(qw/git-cat-file commit/, $c) or croak $!;
2144 if (/^parent ([a-f\d]{40})/) {
2150 close $ch; # breaking the pipe
2151 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2153 if ($comments->{'END'}) {
2154 print $fh $_ foreach @{$comments->{'END'}};
2156 close $fh or croak $!;
2159 sub read_url_paths {
2161 git_svn_each(sub { my $x = shift;
2162 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2163 my ($u, $p) = repo_path_split($url);
2164 $l_map->{$u}->{$p} = $x;
2169 sub extract_metadata {
2171 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2173 if (!$rev || !$uuid || !$url) {
2174 # some of the original repositories I made had
2175 # indentifiers like this:
2176 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2178 return ($url, $rev, $uuid);
2181 sub tz_to_s_offset {
2184 return ($1 * 60) + ($tz * 3600);
2187 sub setup_pager { # translated to Perl from pager.c
2188 return unless (-t *STDOUT);
2189 my $pager = $ENV{PAGER};
2190 if (!defined $pager) {
2192 } elsif (length $pager == 0 || $pager eq 'cat') {
2195 pipe my $rfd, my $wfd or return;
2196 defined(my $pid = fork) or croak $!;
2198 open STDOUT, '>&', $wfd or croak $!;
2201 open STDIN, '<&', $rfd or croak $!;
2202 $ENV{LESS} ||= '-S';
2203 exec $pager or croak "Can't run pager: $!\n";;
2206 sub get_author_info {
2207 my ($dest, $author, $t, $tz) = @_;
2208 $author =~ s/(?:^\s*|\s*$)//g;
2211 $_a = $rusers{$author} || undef;
2214 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2219 # Date::Parse isn't in the standard Perl distro :(
2220 if ($tz =~ s/^\+//) {
2221 $t += tz_to_s_offset($tz);
2222 } elsif ($tz =~ s/^\-//) {
2223 $t -= tz_to_s_offset($tz);
2225 $dest->{t_utc} = $t;
2228 sub process_commit {
2229 my ($c, $r_min, $r_max, $defer) = @_;
2230 if (defined $r_min && defined $r_max) {
2231 if ($r_min == $c->{r} && $r_min == $r_max) {
2235 return 1 if $r_min == $r_max;
2236 if ($r_min < $r_max) {
2237 # we need to reverse the print order
2238 return 0 if (defined $_limit && --$_limit < 0);
2242 if ($r_min != $r_max) {
2243 return 1 if ($r_min < $c->{r});
2244 return 1 if ($r_max > $c->{r});
2247 return 0 if (defined $_limit && --$_limit < 0);
2256 if (my $l = $c->{l}) {
2257 while ($l->[0] =~ /^\s*$/) { shift @$l }
2260 $_l_fmt ||= 'A' . length($c->{r});
2261 print 'r',pack($_l_fmt, $c->{r}),' | ';
2262 print "$c->{c} | " if $_show_commit;
2265 show_commit_normal($c);
2269 sub show_commit_normal {
2271 print '-' x72, "\nr$c->{r} | ";
2272 print "$c->{c} | " if $_show_commit;
2273 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2274 localtime($c->{t_utc})), ' | ';
2277 if (my $l = $c->{l}) {
2278 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2281 $nr_line = scalar @$l;
2283 print "1 line\n\n\n";
2285 if ($nr_line == 1) {
2286 $nr_line = '1 line';
2288 $nr_line .= ' lines';
2290 print $nr_line, "\n\n";
2291 print $_ foreach @$l;
2297 foreach my $x (qw/raw diff/) {
2300 print $_ foreach @{$c->{$x}}
2306 return unless $_use_lib;
2309 if ($SVN::Core::VERSION lt '1.2.1') {
2310 die "Need SVN::Core 1.2.1 or better ",
2311 "(got $SVN::Core::VERSION) ",
2312 "Falling back to command-line svn\n";
2316 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2317 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2318 $SVN::Node::dir.$SVN::Node::unknown.
2319 $SVN::Node::none.$SVN::Node::file.
2320 $SVN::Node::dir.$SVN::Node::unknown;
2325 sub libsvn_connect {
2327 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2328 SVN::Client::get_ssl_server_trust_file_provider(),
2329 SVN::Client::get_username_provider()]);
2330 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2334 sub libsvn_get_file {
2335 my ($gui, $f, $rev) = @_;
2337 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2339 my ($hash, $pid, $in, $out);
2340 my $pool = SVN::Pool->new;
2341 defined($pid = open3($in, $out, '>&STDERR',
2342 qw/git-hash-object -w --stdin/)) or croak $!;
2343 my ($r, $props) = $SVN->get_file($f, $rev, $in, $pool);
2344 $in->flush == 0 or croak $!;
2345 close $in or croak $!;
2347 chomp($hash = do { local $/; <$out> });
2348 close $out or croak $!;
2350 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2352 my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2353 if (exists $props->{'svn:special'}) {
2355 my $link = `git-cat-file blob $hash`;
2356 $link =~ s/^link // or die "svn:special file with contents: <",
2357 $link, "> is not understood\n";
2358 defined($pid = open3($in, $out, '>&STDERR',
2359 qw/git-hash-object -w --stdin/)) or croak $!;
2361 $in->flush == 0 or croak $!;
2362 close $in or croak $!;
2363 chomp($hash = do { local $/; <$out> });
2364 close $out or croak $!;
2366 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2368 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2371 sub libsvn_log_entry {
2372 my ($rev, $author, $date, $msg, $parents) = @_;
2373 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2374 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2375 or die "Unable to parse date: $date\n";
2376 if (defined $_authors && ! defined $users{$author}) {
2377 die "Author: $author not defined in $_authors file\n";
2379 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2380 author => $author, msg => $msg."\n", parents => $parents || [] }
2384 my ($gui, $last_commit, $f) = @_;
2385 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2386 # remove entire directories.
2387 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2388 defined(my $pid = open my $ls, '-|') or croak $!;
2390 exec(qw/git-ls-tree -r --name-only -z/,
2391 $last_commit,'--',$f) or croak $!;
2395 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2397 close $ls or croak $?;
2399 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2404 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2405 open my $gui, '| git-update-index -z --index-info' or croak $!;
2407 foreach my $f (keys %$paths) {
2408 my $m = $paths->{$f}->action();
2410 if ($m =~ /^[DR]$/) {
2411 process_rm($gui, $last_commit, $f);
2413 # 'R' can be file replacements, too, right?
2415 my $pool = SVN::Pool->new;
2416 my $t = $SVN->check_path($f, $rev, $pool);
2417 if ($t == $SVN::Node::file) {
2418 if ($m =~ /^[AMR]$/) {
2421 die "Unrecognized action: $m, ($f r$rev)\n";
2426 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2427 close $gui or croak $?;
2428 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2431 sub svn_grab_base_rev {
2432 defined(my $pid = open my $fh, '-|') or croak $!;
2434 open my $null, '>', '/dev/null' or croak $!;
2435 open STDERR, '>&', $null or croak $!;
2436 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2439 chomp(my $c = do { local $/; <$fh> });
2441 if (defined $c && length $c) {
2442 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2443 safe_qx(qw/git-cat-file commit/, $c)))[0]);
2446 return (undef, undef);
2449 sub libsvn_parse_revision {
2451 my $head = $SVN->get_latest_revnum();
2452 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2453 return ($base + 1, $head) if (defined $base);
2456 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2457 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2458 if ($_revision =~ /^BASE:(\d+)$/) {
2459 return ($base + 1, $1) if (defined $base);
2462 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2463 die "revision argument: $_revision not understood by git-svn\n",
2464 "Try using the command-line svn client instead\n";
2467 sub libsvn_traverse {
2468 my ($gui, $pfx, $path, $rev) = @_;
2469 my $cwd = "$pfx/$path";
2470 my $pool = SVN::Pool->new;
2472 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2473 foreach my $d (keys %$dirent) {
2474 my $t = $dirent->{$d}->kind;
2475 if ($t == $SVN::Node::dir) {
2476 libsvn_traverse($gui, $cwd, $d, $rev);
2477 } elsif ($t == $SVN::Node::file) {
2478 libsvn_get_file($gui, "$cwd/$d", $rev);
2484 sub libsvn_traverse_ignore {
2485 my ($fh, $path, $r) = @_;
2487 my $pool = SVN::Pool->new;
2488 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2490 $p =~ s#^\Q$SVN_PATH\E/?##;
2491 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2492 if (my $s = $props->{'svn:ignore'}) {
2493 $s =~ s/[\r\n]+/\n/g;
2495 if (length $p == 0) {
2499 $s =~ s#\n#\n/$p/#g;
2500 print $fh "/$p/$s\n";
2503 foreach (sort keys %$dirent) {
2504 next if $dirent->{$_}->kind != $SVN::Node::dir;
2505 libsvn_traverse_ignore($fh, "$path/$_", $r);
2511 my ($path, $r0, $r1) = @_;
2512 return 1 if $r0 == $r1;
2515 # should be OK to use Pool here (r1 - r0) should be small
2516 my $pool = SVN::Pool->new;
2517 $SVN->get_log("/$path", $r0, $r1, 0, 1, 1, sub {$nr++},$pool);
2520 my ($url, undef) = repo_path_split($SVN_URL);
2521 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2522 while (next_log_entry($svn_log)) { $nr++ }
2523 close $svn_log->{fh};
2525 return 0 if ($nr > 1);
2529 sub libsvn_find_parent_branch {
2530 my ($paths, $rev, $author, $date, $msg) = @_;
2531 my $svn_path = '/'.$SVN_PATH;
2533 # look for a parent from another branch:
2534 my $i = $paths->{$svn_path} or return;
2535 my $branch_from = $i->copyfrom_path or return;
2536 my $r = $i->copyfrom_rev;
2537 print STDERR "Found possible branch point: ",
2538 "$branch_from => $svn_path, $r\n";
2539 $branch_from =~ s#^/##;
2540 my $l_map = read_url_paths();
2541 my $url = $SVN->{url};
2542 defined $l_map->{$url} or return;
2543 my $id = $l_map->{$url}->{$branch_from} or return;
2544 my ($r0, $parent) = find_rev_before($r,$id,1);
2545 return unless (defined $r0 && defined $parent);
2546 if (revisions_eq($branch_from, $r0, $r)) {
2547 unlink $GIT_SVN_INDEX;
2548 print STDERR "Found branch parent: $parent\n";
2549 sys(qw/git-read-tree/, $parent);
2550 return libsvn_fetch($parent, $paths, $rev,
2551 $author, $date, $msg);
2553 print STDERR "Nope, branch point not imported or unknown\n";
2557 sub libsvn_new_tree {
2558 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2561 my ($paths, $rev, $author, $date, $msg) = @_;
2562 open my $gui, '| git-update-index -z --index-info' or croak $!;
2563 my $pool = SVN::Pool->new;
2564 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2566 close $gui or croak $?;
2567 return libsvn_log_entry($rev, $author, $date, $msg);
2570 sub find_graft_path_commit {
2571 my ($tree_paths, $p1, $r1) = @_;
2572 foreach my $x (keys %$tree_paths) {
2573 next unless ($p1 =~ /^\Q$x\E/);
2574 my $i = $tree_paths->{$x};
2575 my ($r0, $parent) = find_rev_before($r1,$i,1);
2576 return $parent if (defined $r0 && $r0 == $r1);
2577 print STDERR "r$r1 of $i not imported\n";
2583 sub find_graft_path_parents {
2584 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2585 foreach my $x (keys %$tree_paths) {
2586 next unless ($p0 =~ /^\Q$x\E/);
2587 my $i = $tree_paths->{$x};
2588 my ($r, $parent) = find_rev_before($r0, $i, 1);
2589 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2590 $grafts->{$c}->{$parent} = 1;
2595 sub libsvn_graft_file_copies {
2596 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2597 foreach (keys %$paths) {
2598 my $i = $paths->{$_};
2599 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2601 next unless (defined $p0 && defined $r0);
2606 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2608 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2613 my $old = $ENV{GIT_INDEX_FILE};
2614 $ENV{GIT_INDEX_FILE} = shift;
2621 $ENV{GIT_INDEX_FILE} = $old;
2623 delete $ENV{GIT_INDEX_FILE};
2627 sub libsvn_commit_cb {
2628 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2629 if ($_optimize_commits && $rev == ($r_last + 1)) {
2630 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2631 $log->{tree} = get_tree_from_treeish($c);
2632 my $cmt = git_commit($log, $cmt_last, $c);
2633 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2635 print STDERR "Trees differ: $cmt $c\n",
2636 join('',@diff),"\n";
2644 sub libsvn_ls_fullurl {
2645 my $fullurl = shift;
2646 my ($repo, $path) = repo_path_split($fullurl);
2647 $SVN ||= libsvn_connect($repo);
2649 my $pool = SVN::Pool->new;
2650 my ($dirent, undef, undef) = $SVN->get_dir($path,
2651 $SVN->get_latest_revnum, $pool);
2652 foreach my $d (keys %$dirent) {
2653 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2654 push @ret, "$d/"; # add '/' for compat with cli svn
2662 sub libsvn_skip_unknown_revs {
2664 my $errno = $err->apr_err();
2665 # Maybe the branch we're tracking didn't
2666 # exist when the repo started, so it's
2667 # not an error if it doesn't, just continue
2669 # Wonderfully consistent library, eh?
2670 # 160013 - svn:// and file://
2671 # 175002 - http(s)://
2672 # More codes may be discovered later...
2673 if ($errno == 175002 || $errno == 160013) {
2676 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2679 # Tie::File seems to be prone to offset errors if revisions get sparse,
2680 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2681 # one of my favorite modules is out :< Next up would be one of the DBM
2682 # modules, but I'm not sure which is most portable... So I'll just
2683 # go with something that's plain-text, but still capable of
2684 # being randomly accessed. So here's my ultra-simple fixed-width
2685 # database. All records are 40 characters + "\n", so it's easy to seek
2686 # to a revision: (41 * rev) is the byte offset.
2687 # A record of 40 0s denotes an empty revision.
2688 # And yes, it's still pretty fast (faster than Tie::File).
2690 my ($file, $rev, $commit) = @_;
2691 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2692 open my $fh, '+<', $file or croak $!;
2693 my $offset = $rev * 41;
2694 # assume that append is the common case:
2695 seek $fh, 0, 2 or croak $!;
2697 if ($pos < $offset) {
2698 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2700 seek $fh, $offset, 0 or croak $!;
2701 print $fh $commit,"\n";
2702 close $fh or croak $!;
2706 my ($file, $rev) = @_;
2708 my $offset = $rev * 41;
2709 open my $fh, '<', $file or croak $!;
2710 seek $fh, $offset, 0;
2711 if (tell $fh == $offset) {
2712 $ret = readline $fh;
2715 $ret = undef if ($ret =~ /^0{40}$/);
2718 close $fh or croak $!;
2722 package SVN::Git::Editor;
2731 my $git_svn = shift;
2732 my $self = SVN::Delta::Editor->new(@_);
2733 bless $self, $class;
2734 foreach (qw/svn_path c r ra /) {
2735 die "$_ required!\n" unless (defined $git_svn->{$_});
2736 $self->{$_} = $git_svn->{$_};
2738 $self->{pool} = SVN::Pool->new;
2739 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2741 require Digest::MD5;
2746 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2750 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2755 my ($self, $path) = @_;
2756 $self->{ra}->{url} . '/' . $self->repo_path($path);
2761 my $rm = $self->{rm};
2762 delete $rm->{''}; # we never delete the url we're tracking
2765 foreach (keys %$rm) {
2766 my @d = split m#/#, $_;
2770 $c .= '/' . shift @d;
2774 delete $rm->{$self->{svn_path}};
2775 delete $rm->{''}; # we never delete the url we're tracking
2778 defined(my $pid = open my $fh,'-|') or croak $!;
2780 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2785 $_ = $self->{svn_path} . '/' . $_;
2786 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2790 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2791 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2792 $self->close_directory($bat->{$d}, $p);
2793 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2794 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2799 sub open_or_add_dir {
2800 my ($self, $full_path, $baton) = @_;
2801 my $p = SVN::Pool->new;
2802 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2804 if ($t == $SVN::Node::none) {
2805 return $self->add_directory($full_path, $baton,
2806 undef, -1, $self->{pool});
2807 } elsif ($t == $SVN::Node::dir) {
2808 return $self->open_directory($full_path, $baton,
2809 $self->{r}, $self->{pool});
2811 print STDERR "$full_path already exists in repository at ",
2812 "r$self->{r} and it is not a directory (",
2813 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2818 my ($self, $path) = @_;
2819 my $bat = $self->{bat};
2820 $path = $self->repo_path($path);
2821 return $bat->{''} unless (length $path);
2822 my @p = split m#/+#, $path;
2824 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2827 $c .= '/' . shift @p;
2828 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2834 my ($self, $m) = @_;
2835 my ($dir, $file) = split_path($m->{file_b});
2836 my $pbat = $self->ensure_path($dir);
2837 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2839 $self->chg_file($fbat, $m);
2840 $self->close_file($fbat,undef,$self->{pool});
2844 my ($self, $m) = @_;
2845 my ($dir, $file) = split_path($m->{file_b});
2846 my $pbat = $self->ensure_path($dir);
2847 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2848 $self->url_path($m->{file_a}), $self->{r});
2849 $self->chg_file($fbat, $m);
2850 $self->close_file($fbat,undef,$self->{pool});
2854 my ($self, $path, $pbat) = @_;
2855 my $rpath = $self->repo_path($path);
2856 my ($dir, $file) = split_path($rpath);
2857 $self->{rm}->{$dir} = 1;
2858 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2862 my ($self, $m) = @_;
2863 my ($dir, $file) = split_path($m->{file_b});
2864 my $pbat = $self->ensure_path($dir);
2865 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2866 $self->url_path($m->{file_a}), $self->{r});
2867 $self->chg_file($fbat, $m);
2868 $self->close_file($fbat,undef,$self->{pool});
2870 ($dir, $file) = split_path($m->{file_a});
2871 $pbat = $self->ensure_path($dir);
2872 $self->delete_entry($m->{file_a}, $pbat);
2876 my ($self, $m) = @_;
2877 my ($dir, $file) = split_path($m->{file_b});
2878 my $pbat = $self->ensure_path($dir);
2879 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2880 $pbat,$self->{r},$self->{pool});
2881 $self->chg_file($fbat, $m);
2882 $self->close_file($fbat,undef,$self->{pool});
2885 sub T { shift->M(@_) }
2887 sub change_file_prop {
2888 my ($self, $fbat, $pname, $pval) = @_;
2889 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2893 my ($self, $fbat, $m) = @_;
2894 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2895 $self->change_file_prop($fbat,'svn:executable','*');
2896 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2897 $self->change_file_prop($fbat,'svn:executable',undef);
2899 my $fh = IO::File->new_tmpfile or croak $!;
2900 if ($m->{mode_b} =~ /^120/) {
2901 print $fh 'link ' or croak $!;
2902 $self->change_file_prop($fbat,'svn:special','*');
2903 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2904 $self->change_file_prop($fbat,'svn:special',undef);
2906 defined(my $pid = fork) or croak $!;
2908 open STDOUT, '>&', $fh or croak $!;
2909 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2913 $fh->flush == 0 or croak $!;
2914 seek $fh, 0, 0 or croak $!;
2916 my $md5 = Digest::MD5->new;
2917 $md5->addfile($fh) or croak $!;
2918 seek $fh, 0, 0 or croak $!;
2920 my $exp = $md5->hexdigest;
2921 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2922 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2923 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2925 close $fh or croak $!;
2929 my ($self, $m) = @_;
2930 my ($dir, $file) = split_path($m->{file_b});
2931 my $pbat = $self->ensure_path($dir);
2932 $self->delete_entry($m->{file_b}, $pbat);
2937 my ($p,$bat) = ($self->{pool}, $self->{bat});
2938 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2939 $self->close_directory($bat->{$_}, $p);
2941 $self->SUPER::close_edit($p);
2947 $self->SUPER::abort_edit($self->{pool});
2948 $self->{pool}->clear;
2955 $svn_log hashref (as returned by svn_log_raw)
2957 fh => file handle of the log file,
2958 state => state of the log file parser (sep/msg/rev/msg_start...)
2961 $log_msg hashref as returned by next_log_entry($svn_log)
2963 msg => 'whitespace-formatted log entry
2964 ', # trailing newline is preserved
2965 revision => '8', # integer
2966 date => '2004-02-24T17:01:44.108345Z', # commit date
2967 author => 'committer name'
2971 @mods = array of diff-index line hashes, each element represents one line
2972 of diff-index output
2974 diff-index line ($m hash)
2976 mode_a => first column of diff-index output, no leading ':',
2977 mode_b => second column of diff-index output,
2978 sha1_b => sha1sum of the final blob,
2979 chg => change type [MCRADT],
2980 file_a => original file name of a file (iff chg is 'C' or 'R')
2981 file_b => new/current file name of a file (any chg)
2986 I don't trust the each() function on unless I created %hash myself
2987 because the internal iterator may not have started at base.