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/;
35 memoize('revisions_eq');
37 my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
38 $_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
40 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
41 my $sha1 = qr/[a-f\d]{40}/;
42 my $sha1_short = qr/[a-f\d]{4,40}/;
43 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
44 $_find_copies_harder, $_l, $_cp_similarity,
45 $_repack, $_repack_nr, $_repack_flags,
46 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
47 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
48 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
49 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
50 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
51 my @repo_path_split_cache;
53 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
54 'branch|b=s' => \@_branch_from,
55 'branch-all-refs|B' => \$_branch_all_refs,
56 'authors-file|A=s' => \$_authors,
57 'repack:i' => \$_repack,
58 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
60 my ($_trunk, $_tags, $_branches);
61 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
62 'tags|t=s' => \$_tags,
63 'branches|b=s' => \$_branches );
64 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
66 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
67 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
70 fetch => [ \&fetch, "Download new revisions from SVN",
71 { 'revision|r=s' => \$_revision, %fc_opts } ],
72 init => [ \&init, "Initialize a repo for tracking" .
73 " (requires URL argument)",
75 commit => [ \&commit, "Commit git revisions to SVN",
76 { 'stdin|' => \$_stdin,
79 'find-copies-harder' => \$_find_copies_harder,
81 'copy-similarity|C=i'=> \$_cp_similarity,
84 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
85 { 'revision|r=i' => \$_revision } ],
86 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
87 { 'no-ignore-externals' => \$_no_ignore_ext,
88 'upgrade' => \$_upgrade } ],
89 'graft-branches' => [ \&graft_branches,
90 'Detect merges/branches from already imported history',
91 { 'merge-rx|m' => \@_opt_m,
92 'no-default-regex' => \$_no_default_regex,
93 'no-graft-copy' => \$_no_graft_copy } ],
94 'multi-init' => [ \&multi_init,
95 'Initialize multiple trees (like git-svnimport)',
96 { %multi_opts, %fc_opts } ],
97 'multi-fetch' => [ \&multi_fetch,
98 'Fetch multiple trees (like git-svnimport)',
100 'log' => [ \&show_log, 'Show commit logs',
101 { 'limit=i' => \$_limit,
102 'revision|r=s' => \$_revision,
103 'verbose|v' => \$_verbose,
104 'incremental' => \$_incremental,
105 'oneline' => \$_oneline,
106 'show-commit' => \$_show_commit,
107 'authors-file|A=s' => \$_authors,
112 for (my $i = 0; $i < @ARGV; $i++) {
113 if (defined $cmd{$ARGV[$i]}) {
120 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
122 read_repo_config(\%opts);
123 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
124 'version|V' => \$_version,
125 'id|i=s' => \$GIT_SVN);
126 exit 1 if (!$rv && $cmd ne 'log');
130 version() if $_version;
131 usage(1) unless defined $cmd;
133 load_authors() if $_authors;
134 load_all_refs() if $_branch_all_refs;
136 migration_check() unless $cmd =~ /^(?:init|multi-init)$/;
137 $cmd{$cmd}->[0]->(@ARGV);
140 ####################### primary functions ######################
142 my $exit = shift || 0;
143 my $fd = $exit ? \*STDERR : \*STDOUT;
145 git-svn - bidirectional operations between a single Subversion tree and git
146 Usage: $0 <command> [options] [arguments]\n
148 print $fd "Available commands:\n" unless $cmd;
150 foreach (sort keys %cmd) {
151 next if $cmd && $cmd ne $_;
152 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
153 foreach (keys %{$cmd{$_}->[2]}) {
154 # prints out arguments as they should be passed:
155 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
156 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
158 split /\|/,$_)," $x\n";
162 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
163 arbitrary identifier if you're tracking multiple SVN branches/repositories in
164 one git repository and want to keep them separate. See git-svn(1) for more
171 print "git-svn version $VERSION\n";
176 $SVN_URL = shift or undef;
179 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
181 check_upgrade_needed();
184 my $pid = open(my $rev_list,'-|');
185 defined $pid or croak $!;
187 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
190 while (<$rev_list>) {
193 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
194 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
195 next if (!@commit); # skip merges
196 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
197 if (!$rev || !$uuid) {
198 croak "Unable to extract revision or UUID from ",
199 "$c, $commit[$#commit]\n";
202 # if we merged or otherwise started elsewhere, this is
203 # how we break out of it
204 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
205 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
207 unless (defined $latest) {
208 if (!$SVN_URL && !$url) {
209 croak "SVN repository location required: $url\n";
216 revdb_set($REVDB, $rev, $c);
217 print "r$rev = $c\n";
218 $newest_rev = $rev if ($rev > $newest_rev);
220 close $rev_list or croak $?;
222 goto out if $_use_lib;
223 if (!chdir $SVN_WC) {
224 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
225 chdir $SVN_WC or croak $!;
229 defined $pid or croak $!;
231 my @svn_up = qw(svn up);
232 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
233 sys(@svn_up,"-r$newest_rev");
234 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
236 exec('git-write-tree') or croak $!;
243 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
244 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
250 $SVN_URL = shift or die "SVN repository location required " .
251 "as a command-line argument\n";
252 $SVN_URL =~ s!/+$!!; # strip trailing slash
253 unless (-d $GIT_DIR) {
254 my @init_db = ('git-init-db');
255 push @init_db, "--template=$_template" if defined $_template;
256 push @init_db, "--shared" if defined $_shared;
263 check_upgrade_needed();
264 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
265 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
266 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
267 refs/heads/master^0))) {
268 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
275 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
276 unless ($_revision) {
277 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
279 push @log_args, "-r$_revision";
280 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
282 my $svn_log = svn_log_raw(@log_args);
284 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
285 # don't need last_revision from grab_base_rev() because
286 # user could've specified a different revision to skip (they
287 # didn't want to import certain revisions into git for whatever
288 # reason, so trust $base->{revision} instead.
289 my (undef, $last_commit) = svn_grab_base_rev();
290 unless (-d $SVN_WC) {
291 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
292 chdir $SVN_WC or croak $!;
294 $last_commit = git_commit($base, @parents);
295 assert_tree($last_commit);
297 chdir $SVN_WC or croak $!;
299 # looks like a user manually cp'd and svn switch'ed
300 unless ($last_commit) {
301 sys(qw/svn revert -R ./);
302 assert_svn_wc_clean($base->{revision});
303 $last_commit = git_commit($base, @parents);
304 assert_tree($last_commit);
307 my @svn_up = qw(svn up);
308 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
310 while (my $log_msg = next_log_entry($svn_log)) {
311 if ($last->{revision} >= $log_msg->{revision}) {
312 croak "Out of order: last >= current: ",
313 "$last->{revision} >= $log_msg->{revision}\n";
315 # Revert is needed for cases like:
316 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
317 # I can't seem to reproduce something like that on a test...
318 sys(qw/svn revert -R ./);
319 assert_svn_wc_clean($last->{revision});
320 sys(@svn_up,"-r$log_msg->{revision}");
321 $last_commit = git_commit($log_msg, $last_commit, @parents);
324 close $svn_log->{fh};
325 $last->{commit} = $last_commit;
331 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
333 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
334 $SVN_LOG ||= libsvn_connect($repo);
335 $SVN ||= libsvn_connect($repo);
336 my ($last_rev, $last_commit) = svn_grab_base_rev();
337 my ($base, $head) = libsvn_parse_revision($last_rev);
339 return { revision => $last_rev, commit => $last_commit }
341 my $index = set_index($GIT_SVN_INDEX);
343 # limit ourselves and also fork() since get_log won't release memory
344 # after processing a revision and SVN stuff seems to leak
346 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
348 if (defined $last_commit) {
349 unless (-e $GIT_SVN_INDEX) {
350 sys(qw/git-read-tree/, $last_commit);
352 chomp (my $x = `git-write-tree`);
353 my ($y) = (`git-cat-file commit $last_commit`
354 =~ /^tree ($sha1)/m);
356 unlink $GIT_SVN_INDEX or croak $!;
357 sys(qw/git-read-tree/, $last_commit);
359 chomp ($x = `git-write-tree`);
361 print STDERR "trees ($last_commit) $y != $x\n",
362 "Something is seriously wrong...\n";
366 # fork, because using SVN::Pool with get_log() still doesn't
367 # seem to help enough to keep memory usage down.
368 defined(my $pid = fork) or croak $!;
370 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
372 # Yes I'm perfectly aware that the fourth argument
373 # below is the limit revisions number. Unfortunately
374 # performance sucks with it enabled, so it's much
375 # faster to fetch revision ranges instead of relying
377 $SVN_LOG->get_log( '/'.$SVN_PATH, $min, $max, 0, 1, 1,
381 $log_msg = libsvn_fetch(
383 $last_commit = git_commit(
388 $log_msg = libsvn_new_tree(@_);
389 $last_commit = git_commit(
397 ($last_rev, $last_commit) = svn_grab_base_rev();
398 last if ($max >= $head);
401 $max = $head if ($max > $head);
403 restore_index($index);
404 return { revision => $last_rev, commit => $last_commit };
409 check_upgrade_needed();
410 if ($_stdin || !@commits) {
411 print "Reading from stdin...\n";
414 if (/\b($sha1_short)\b/o) {
415 unshift @commits, $1;
420 foreach my $c (@commits) {
421 chomp(my @tmp = safe_qx('git-rev-parse',$c));
422 if (scalar @tmp == 1) {
424 } elsif (scalar @tmp > 1) {
425 push @revs, reverse (safe_qx('git-rev-list',@tmp));
427 die "Failed to rev-parse $c\n";
431 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
432 print "Done committing ",scalar @revs," revisions to SVN\n";
438 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
439 my $info = svn_info('.');
440 my $fetched = fetch();
441 if ($info->{Revision} != $fetched->{revision}) {
442 print STDERR "There are new revisions that were fetched ",
443 "and need to be merged (or acknowledged) ",
444 "before committing.\n";
447 $info = svn_info('.');
450 foreach my $c (@revs) {
451 my $mods = svn_checkout_tree($last, $c);
452 if (scalar @$mods == 0) {
453 print "Skipping, no changes detected\n";
456 $last = svn_commit_tree($last, $c);
462 my ($r_last, $cmt_last) = svn_grab_base_rev();
463 defined $r_last or die "Must have an existing revision to commit\n";
464 my $fetched = fetch();
465 if ($r_last != $fetched->{revision}) {
466 print STDERR "There are new revisions that were fetched ",
467 "and need to be merged (or acknowledged) ",
468 "before committing.\n",
469 "last rev: $r_last\n",
470 " current: $fetched->{revision}\n";
474 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
475 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
477 foreach my $c (@revs) {
478 # fork for each commit because there's a memory leak I
479 # can't track down... (it's probably in the SVN code)
480 defined(my $pid = open my $fh, '-|') or croak $!;
482 if (defined $LC_ALL) {
483 $ENV{LC_ALL} = $LC_ALL;
487 my $log_msg = get_commit_message($c, $commit_msg);
488 my $ed = SVN::Git::Editor->new(
492 svn_path => $SVN_PATH
494 $SVN->get_commit_editor(
505 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
507 print "No changes\nr$r_last = $cmt_last\n";
514 my ($r_new, $cmt_new, $no);
518 if (/^r(\d+) = ($sha1)$/o) {
519 ($r_new, $cmt_new) = ($1, $2);
520 } elsif ($_ eq 'No changes') {
524 close $fh or croak $?;
525 if (! defined $r_new && ! defined $cmt_new) {
527 die "Failed to parse revision information\n";
530 ($r_last, $cmt_last) = ($r_new, $cmt_new);
537 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
538 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
541 sub show_ignore_cmd {
542 require File::Find or die $!;
543 if (defined $_revision) {
544 die "-r/--revision option doesn't work unless the Perl SVN ",
545 "libraries are used\n";
547 chdir $SVN_WC or croak $!;
549 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
551 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
552 }}, no_chdir=>1},'.');
555 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
557 foreach my $i (sort keys %ign) {
558 print "\n# ",$i,"\n";
559 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
563 sub show_ignore_lib {
565 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
566 $SVN ||= libsvn_connect($repo);
567 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
568 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
572 my $gr_file = "$GIT_DIR/info/grafts";
573 my ($grafts, $comments) = read_grafts($gr_file);
577 # temporarily disable our grafts file to make this idempotent
578 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
579 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
582 my $l_map = read_url_paths();
583 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
584 unless ($_no_default_regex) {
585 push @re, ( qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
586 qr/\b(?:from|of)\s+(\S.+)/is );
588 foreach my $u (keys %$l_map) {
590 foreach my $p (keys %{$l_map->{$u}}) {
591 graft_merge_msg($grafts,$l_map,$u,$p);
594 unless ($_no_graft_copy) {
596 graft_file_copy_lib($grafts,$l_map,$u);
598 graft_file_copy_cmd($grafts,$l_map,$u);
603 write_grafts($grafts, $comments, $gr_file);
604 unlink "$gr_file~$gr_sha1" if $gr_sha1;
611 $url =~ s#/+$## if $url;
612 if ($_trunk !~ m#^[a-z\+]+://#) {
613 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
615 print STDERR "E: '$_trunk' is not a complete URL ",
616 "and a separate URL is not specified\n";
619 $_trunk = $url . $_trunk;
621 if ($GIT_SVN eq 'git-svn') {
622 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
623 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
627 complete_url_ls_init($url, $_branches, '--branches/-b', '');
628 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
632 # try to do trunk first, since branches/tags
633 # may be descended from it.
634 if (-e "$GIT_DIR/svn/trunk/info/url") {
635 fetch_child_id('trunk', @_);
637 rec_fetch('', "$GIT_DIR/svn", @_);
643 my $r_last = -1; # prevent dupes
644 rload_authors() if $_authors;
650 if (defined $_revision) {
651 if ($_revision =~ /^(\d+):(\d+)$/) {
652 ($r_min, $r_max) = ($1, $2);
653 } elsif ($_revision =~ /^\d+$/) {
654 $r_min = $r_max = $_revision;
656 print STDERR "-r$_revision is not supported, use ",
657 "standard \'git log\' arguments instead\n";
662 my $pid = open(my $log,'-|');
663 defined $pid or croak $!;
665 my @rl = (qw/git-log --abbrev-commit --pretty=raw
666 --default/, "remotes/$GIT_SVN");
667 push @rl, '--raw' if $_verbose;
668 exec(@rl, @args) or croak $!;
673 if (/^commit ($sha1_short)/o) {
675 if ($c && defined $c->{r} && $c->{r} != $r_last) {
677 process_commit($c, $r_min, $r_max, \@k) or
682 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
683 get_author_info($c, $1, $2, $3);
684 } elsif (/^(?:tree|parent|committer) /) {
686 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
687 push @{$c->{raw}}, $_;
690 push @{$c->{diff}}, $_;
692 push @{$c->{diff}}, $_;
693 } elsif (/^ (git-svn-id:.+)$/) {
694 my ($url, $rev, $uuid) = extract_metadata($1);
700 if ($c && defined $c->{r} && $c->{r} != $r_last) {
702 process_commit($c, $r_min, $r_max, \@k);
708 process_commit($_, $r_min, $r_max) foreach reverse @k;
712 print '-' x72,"\n" unless $_incremental || $_oneline;
715 ########################### utility functions #########################
719 print "Fetching $id\n";
720 my $ref = "$GIT_DIR/refs/remotes/$id";
721 my $ca = file_to_s($ref) if (-r $ref);
722 defined(my $pid = fork) or croak $!;
724 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
731 return unless $_repack || -r $ref;
733 my $cb = file_to_s($ref);
735 defined($pid = open my $fh, '-|') or croak $!;
736 my $url = file_to_s("$GIT_DIR/svn/$id/info/url");
739 exec qw/git-rev-list --pretty=raw/,
740 $ca ? "$ca..$cb" : $cb or croak $!;
743 if (/^ git-svn-id: $url\@\d+ [a-f0-9\-]+$/) {
745 } elsif (/^ git-svn-id: \S+\@\d+ [a-f0-9\-]+$/) {
753 my ($pfx, $p, @args) = @_;
755 foreach (sort <$p/*>) {
756 if (-r "$_/info/url") {
757 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
758 my $id = $pfx . basename $_;
759 next if $id eq 'trunk';
760 fetch_child_id($id, @args);
767 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
772 sub complete_url_ls_init {
773 my ($url, $var, $switch, $pfx) = @_;
775 print STDERR "W: $switch not specified\n";
779 if ($var !~ m#^[a-z\+]+://#) {
780 $var = '/' . $var if ($var !~ m#^/#);
782 print STDERR "E: '$var' is not a complete URL ",
783 "and a separate URL is not specified\n";
788 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
789 : safe_qx(qw/svn ls --non-interactive/, $var));
791 defined(my $pid = fork) or croak $!;
793 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
795 if ($u !~ m!\Q$var\E/(.+)$!) {
796 print STDERR "W: Unrecognized URL: $u\n";
797 die "This should never happen\n";
800 print "init $u => $id\n";
801 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
815 my @tmp = split m#/#, $_;
817 while (my $x = shift @tmp) {
823 foreach (sort {length $b <=> length $a} keys %common) {
824 if ($common{$_} == @$paths) {
831 # this isn't funky-filename safe, but good enough for now...
832 sub graft_file_copy_cmd {
833 my ($grafts, $l_map, $u) = @_;
834 my $paths = $l_map->{$u};
835 my $pfx = common_prefix([keys %$paths]);
836 $SVN_URL ||= $u.$pfx;
837 my $pid = open my $fh, '-|';
838 defined $pid or croak $!;
840 my @exec = qw/svn log -v/;
841 push @exec, "-r$_revision" if defined $_revision;
842 exec @exec, $u.$pfx or croak $!;
844 my ($r, $mp) = (undef, undef);
849 } elsif (/^r(\d+) \| /) {
850 $r = $1 unless defined $r;
851 } elsif (/^Changed paths:/) {
853 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
854 my ($p1, $p0, $r0) = ($1, $2, $3);
855 my $c = find_graft_path_commit($paths, $p1, $r);
857 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
862 sub graft_file_copy_lib {
863 my ($grafts, $l_map, $u) = @_;
864 my $tree_paths = $l_map->{$u};
865 my $pfx = common_prefix([keys %$tree_paths]);
866 my ($repo, $path) = repo_path_split($u.$pfx);
867 $SVN_LOG ||= libsvn_connect($repo);
868 $SVN ||= libsvn_connect($repo);
870 my ($base, $head) = libsvn_parse_revision();
872 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
873 my $eh = $SVN::Error::handler;
874 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
876 my $pool = SVN::Pool->new;
877 $SVN_LOG->get_log( "/$path", $min, $max, 0, 1, 1,
879 libsvn_graft_file_copies($grafts, $tree_paths,
883 last if ($max >= $head);
886 $max = $head if ($max > $head);
888 $SVN::Error::handler = $eh;
891 sub process_merge_msg_matches {
892 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
895 # merging with ourselves is not interesting
897 if ($l_map->{$u}->{$_}) {
903 foreach my $w (@weak) {
905 # no exact match, use branch name as regexp.
906 my $re = qr/\Q$w\E/i;
907 foreach (keys %{$l_map->{$u}}) {
916 foreach (keys %{$l_map->{$u}}) {
923 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
924 \s(?:[a-f\d\-]+)$/xsm);
925 unless (defined $rev) {
926 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
927 \@(?:[a-f\d\-]+)/xsm);
928 return unless defined $rev;
930 foreach my $m (@strong) {
931 my ($r0, $s0) = find_rev_before($rev, $m);
932 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
936 sub graft_merge_msg {
937 my ($grafts, $l_map, $u, $p, @re) = @_;
939 my $x = $l_map->{$u}->{$p};
940 my $rl = rev_list_raw($x);
941 while (my $c = next_rev_list_entry($rl)) {
942 foreach my $re (@re) {
943 my (@br) = ($c->{m} =~ /$re/g);
945 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
953 my $pool = SVN::Pool->new;
954 $SVN_UUID = $SVN->get_uuid($pool);
957 my $info = shift || svn_info('.');
958 $SVN_UUID = $info->{'Repository UUID'} or
959 croak "Repository UUID unreadable\n";
965 defined $pid or croak $!;
967 open my $null, '>', '/dev/null' or croak $!;
968 open STDERR, '>&', $null or croak $!;
969 open STDOUT, '>&', $null or croak $!;
976 sub repo_path_split {
977 my $full_url = shift;
978 $full_url =~ s#/+$##;
980 foreach (@repo_path_split_cache) {
981 if ($full_url =~ s#$_##) {
983 $full_url =~ s#^/+##;
984 return ($u, $full_url);
988 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
990 my @paths = split(m#/+#, $path);
994 $SVN = libsvn_connect($url);
995 last if (defined $SVN &&
996 defined eval { $SVN->get_latest_revnum });
997 my $n = shift @paths || last;
1001 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1002 my $n = shift @paths || last;
1006 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1007 $path = join('/',@paths);
1008 return ($url, $path);
1012 defined $SVN_URL or croak "SVN repository location required\n";
1013 unless (-d $GIT_DIR) {
1014 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1016 mkpath([$GIT_SVN_DIR]);
1017 mkpath(["$GIT_SVN_DIR/info"]);
1018 open my $fh, '>>',$REVDB or croak $!;
1020 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1024 sub assert_svn_wc_clean {
1025 return if $_use_lib;
1027 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1028 my $lcr = svn_info('.')->{'Last Changed Rev'};
1029 if ($svn_rev != $lcr) {
1030 print STDERR "Checking for copy-tree ... ";
1031 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1032 "-r$lcr:$svn_rev")));
1034 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1036 print STDERR "OK!\n";
1039 my @status = grep(!/^Performing status on external/,(`svn status`));
1040 @status = grep(!/^\s*$/,@status);
1041 if (scalar @status) {
1042 print STDERR "Tree ($SVN_WC) is not clean:\n";
1043 print STDERR $_ foreach @status;
1048 sub get_tree_from_treeish {
1050 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1051 chomp(my $type = `git-cat-file -t $treeish`);
1053 while ($type eq 'tag') {
1054 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1056 if ($type eq 'commit') {
1057 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1058 ($expected) = ($expected =~ /^tree ($sha1)$/);
1059 die "Unable to get tree from $treeish\n" unless $expected;
1060 } elsif ($type eq 'tree') {
1061 $expected = $treeish;
1063 die "$treeish is a $type, expected tree, tag or commit\n";
1069 return if $_use_lib;
1071 my $expected = get_tree_from_treeish($treeish);
1073 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1075 unlink $tmpindex or croak $!;
1077 my $old_index = set_index($tmpindex);
1079 chomp(my $tree = `git-write-tree`);
1080 restore_index($old_index);
1081 if ($tree ne $expected) {
1082 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1087 sub parse_diff_tree {
1088 my $diff_fh = shift;
1092 while (<$diff_fh>) {
1093 chomp $_; # this gets rid of the trailing "\0"
1094 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1095 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1096 push @mods, { mode_a => $1, mode_b => $2,
1097 sha1_b => $3, chg => $4 };
1098 if ($4 =~ /^(?:C|R)$/) {
1103 } elsif ($state eq 'file_a') {
1104 my $x = $mods[$#mods] or croak "Empty array\n";
1105 if ($x->{chg} !~ /^(?:C|R)$/) {
1106 croak "Error parsing $_, $x->{chg}\n";
1110 } elsif ($state eq 'file_b') {
1111 my $x = $mods[$#mods] or croak "Empty array\n";
1112 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1113 croak "Error parsing $_, $x->{chg}\n";
1115 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1116 croak "Error parsing $_, $x->{chg}\n";
1121 croak "Error parsing $_\n";
1124 close $diff_fh or croak $?;
1129 sub svn_check_prop_executable {
1131 return if -l $m->{file_b};
1132 if ($m->{mode_b} =~ /755$/) {
1133 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1134 if ($m->{mode_a} !~ /755$/) {
1135 sys(qw(svn propset svn:executable 1), $m->{file_b});
1137 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1138 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1139 sys(qw(svn propdel svn:executable), $m->{file_b});
1140 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1141 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1145 sub svn_ensure_parent_path {
1146 my $dir_b = dirname(shift);
1147 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1148 mkpath([$dir_b]) unless (-d $dir_b);
1149 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1152 sub precommit_check {
1154 my (%rm_file, %rmdir_check, %added_check);
1156 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1157 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1158 if ($m->{chg} eq 'R') {
1159 if (-d $m->{file_b}) {
1160 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1162 # dir/$file => dir/file/$file
1163 my $dirname = dirname($m->{file_b});
1164 while ($dirname ne File::Spec->curdir) {
1165 if ($dirname ne $m->{file_a}) {
1166 $dirname = dirname($dirname);
1169 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1171 # baz/zzz => baz (baz is a file)
1172 $dirname = dirname($m->{file_a});
1173 while ($dirname ne File::Spec->curdir) {
1174 if ($dirname ne $m->{file_b}) {
1175 $dirname = dirname($dirname);
1178 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1181 if ($m->{chg} =~ /^(D|R)$/) {
1182 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1183 $rm_file{ $m->{$t} } = 1;
1184 my $dirname = dirname( $m->{$t} );
1185 my $basename = basename( $m->{$t} );
1186 $rmdir_check{$dirname}->{$basename} = 1;
1187 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1188 if (-d $m->{file_b}) {
1189 err_dir_to_file($m->{file_b});
1191 my $dirname = dirname( $m->{file_b} );
1192 my $basename = basename( $m->{file_b} );
1193 $added_check{$dirname}->{$basename} = 1;
1194 while ($dirname ne File::Spec->curdir) {
1195 if ($rm_file{$dirname}) {
1196 err_file_to_dir($m->{file_b});
1198 $dirname = dirname $dirname;
1202 return (\%rmdir_check, \%added_check);
1204 sub err_dir_to_file {
1206 print STDERR "Node change from directory to file ",
1207 "is not supported by Subversion: ",$file,"\n";
1210 sub err_file_to_dir {
1212 print STDERR "Node change from file to directory ",
1213 "is not supported by Subversion: ",$file,"\n";
1220 my ($from, $treeish) = @_;
1222 print "diff-tree $from $treeish\n";
1223 my $pid = open my $diff_fh, '-|';
1224 defined $pid or croak $!;
1226 my @diff_tree = qw(git-diff-tree -z -r);
1227 if ($_cp_similarity) {
1228 push @diff_tree, "-C$_cp_similarity";
1230 push @diff_tree, '-C';
1232 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1233 push @diff_tree, "-l$_l" if defined $_l;
1234 exec(@diff_tree, $from, $treeish) or croak $!;
1236 return parse_diff_tree($diff_fh);
1239 sub svn_checkout_tree {
1240 my ($from, $treeish) = @_;
1241 my $mods = get_diff($from->{commit}, $treeish);
1242 return $mods unless (scalar @$mods);
1243 my ($rm, $add) = precommit_check($mods);
1245 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1246 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1247 if ($m->{chg} eq 'C') {
1248 svn_ensure_parent_path( $m->{file_b} );
1249 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1250 apply_mod_line_blob($m);
1251 svn_check_prop_executable($m);
1252 } elsif ($m->{chg} eq 'D') {
1253 sys(qw(svn rm --force), $m->{file_b});
1254 } elsif ($m->{chg} eq 'R') {
1255 svn_ensure_parent_path( $m->{file_b} );
1256 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1257 apply_mod_line_blob($m);
1258 svn_check_prop_executable($m);
1259 } elsif ($m->{chg} eq 'M') {
1260 apply_mod_line_blob($m);
1261 svn_check_prop_executable($m);
1262 } elsif ($m->{chg} eq 'T') {
1263 sys(qw(svn rm --force),$m->{file_b});
1264 apply_mod_line_blob($m);
1265 sys(qw(svn add --force), $m->{file_b});
1266 svn_check_prop_executable($m);
1267 } elsif ($m->{chg} eq 'A') {
1268 svn_ensure_parent_path( $m->{file_b} );
1269 apply_mod_line_blob($m);
1270 sys(qw(svn add --force), $m->{file_b});
1271 svn_check_prop_executable($m);
1273 croak "Invalid chg: $m->{chg}\n";
1277 assert_tree($treeish);
1278 if ($_rmdir) { # remove empty directories
1279 handle_rmdir($rm, $add);
1281 assert_tree($treeish);
1285 sub libsvn_checkout_tree {
1286 my ($from, $treeish, $ed) = @_;
1287 my $mods = get_diff($from, $treeish);
1288 return $mods unless (scalar @$mods);
1289 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1290 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1292 if (defined $o{$f}) {
1295 croak "Invalid change type: $f\n";
1298 $ed->rmdirs if $_rmdir;
1302 # svn ls doesn't work with respect to the current working tree, but what's
1303 # in the repository. There's not even an option for it... *sigh*
1304 # (added files don't show up and removed files remain in the ls listing)
1305 sub svn_ls_current {
1306 my ($dir, $rm, $add) = @_;
1307 chomp(my @ls = safe_qx('svn','ls',$dir));
1310 s#/$##; # trailing slashes are evil
1311 push @ret, $_ unless $rm->{$dir}->{$_};
1313 if (exists $add->{$dir}) {
1314 push @ret, keys %{$add->{$dir}};
1320 my ($rm, $add) = @_;
1322 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1323 my $ls = svn_ls_current($dir, $rm, $add);
1324 next if (scalar @$ls);
1325 sys(qw(svn rm --force),$dir);
1327 my $dn = dirname $dir;
1328 $rm->{ $dn }->{ basename $dir } = 1;
1329 $ls = svn_ls_current($dn, $rm, $add);
1330 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1331 sys(qw(svn rm --force),$dn);
1332 $dir = basename $dn;
1334 $rm->{ $dn }->{ $dir } = 1;
1335 $ls = svn_ls_current($dn, $rm, $add);
1340 sub get_commit_message {
1341 my ($commit, $commit_msg) = (@_);
1342 my %log_msg = ( msg => '' );
1343 open my $msg, '>', $commit_msg or croak $!;
1345 print "commit: $commit\n";
1346 chomp(my $type = `git-cat-file -t $commit`);
1347 if ($type eq 'commit') {
1348 my $pid = open my $msg_fh, '-|';
1349 defined $pid or croak $!;
1352 exec(qw(git-cat-file commit), $commit) or croak $!;
1357 $in_msg = 1 if (/^\s*$/);
1358 } elsif (/^git-svn-id: /) {
1359 # skip this, we regenerate the correct one
1360 # on re-fetch anyways
1362 print $msg $_ or croak $!;
1365 close $msg_fh or croak $?;
1367 close $msg or croak $!;
1369 if ($_edit || ($type eq 'tree')) {
1370 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1371 system($editor, $commit_msg);
1374 # file_to_s removes all trailing newlines, so just use chomp() here:
1375 open $msg, '<', $commit_msg or croak $!;
1376 { local $/; chomp($log_msg{msg} = <$msg>); }
1377 close $msg or croak $!;
1382 sub svn_commit_tree {
1383 my ($last, $commit) = @_;
1384 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1385 my $log_msg = get_commit_message($commit, $commit_msg);
1386 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1387 print "Committing $commit: $oneline\n";
1389 if (defined $LC_ALL) {
1390 $ENV{LC_ALL} = $LC_ALL;
1392 delete $ENV{LC_ALL};
1394 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1397 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1398 if (!defined $committed) {
1399 my $out = join("\n",@ci_output);
1400 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1401 $out, "\n\nAssuming English locale...";
1402 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1403 defined $committed or die " FAILED!\n",
1404 "Commit output failed to parse committed revision!\n",
1405 print STDERR " OK\n";
1408 my @svn_up = qw(svn up);
1409 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1410 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1411 push @svn_up, "-r$committed";
1413 my $info = svn_info('.');
1414 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1415 if ($info->{'Last Changed Rev'} != $committed) {
1416 croak "$info->{'Last Changed Rev'} != $committed\n"
1418 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1419 /(\d{4})\-(\d\d)\-(\d\d)\s
1420 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1421 or croak "Failed to parse date: $date\n";
1422 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1423 $log_msg->{author} = $info->{'Last Changed Author'};
1424 $log_msg->{revision} = $committed;
1425 $log_msg->{msg} .= "\n";
1426 $log_msg->{parents} = [ $last->{commit} ];
1427 $log_msg->{commit} = git_commit($log_msg, $commit);
1430 # resync immediately
1431 push @svn_up, "-r$last->{revision}";
1433 return fetch("$committed=$commit");
1438 my $pid = open my $fh, '-|';
1439 defined $pid or croak $!;
1441 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1443 return { fh => $fh, t => { } };
1446 sub next_rev_list_entry {
1451 if (/^commit ($sha1)$/o) {
1453 $rl->{t} = { c => $1 };
1458 } elsif (/^parent ($sha1)$/o) {
1465 return ($x != $rl->{t}) ? $x : undef;
1468 # read the entire log into a temporary file (which is removed ASAP)
1469 # and store the file handle + parser state
1471 my (@log_args) = @_;
1472 my $log_fh = IO::File->new_tmpfile or croak $!;
1474 defined $pid or croak $!;
1476 open STDOUT, '>&', $log_fh or croak $!;
1477 exec (qw(svn log), @log_args) or croak $!
1481 seek $log_fh, 0, 0 or croak $!;
1482 return { state => 'sep', fh => $log_fh };
1485 sub next_log_entry {
1486 my $log = shift; # retval of svn_log_raw()
1488 my $fh = $log->{fh};
1493 if ($log->{state} eq 'msg') {
1494 if ($ret->{lines}) {
1495 $ret->{msg} .= $_."\n";
1496 unless(--$ret->{lines}) {
1497 $log->{state} = 'sep';
1500 croak "Log parse error at: $_\n",
1506 if ($log->{state} ne 'sep') {
1507 croak "Log parse error at: $_\n",
1508 "state: $log->{state}\n",
1512 $log->{state} = 'rev';
1514 # if we have an empty log message, put something there:
1516 $ret->{msg} ||= "\n";
1517 delete $ret->{lines};
1522 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1524 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1525 ($lines) = ($lines =~ /(\d+)/);
1526 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1527 /(\d{4})\-(\d\d)\-(\d\d)\s
1528 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1529 or croak "Failed to parse date: $date\n";
1530 $ret = { revision => $rev,
1531 date => "$tz $Y-$m-$d $H:$M:$S",
1535 if (defined $_authors && ! defined $users{$author}) {
1536 die "Author: $author not defined in ",
1539 $log->{state} = 'msg_start';
1542 # skip the first blank line of the message:
1543 if ($log->{state} eq 'msg_start' && /^$/) {
1544 $log->{state} = 'msg';
1545 } elsif ($log->{state} eq 'msg') {
1546 if ($ret->{lines}) {
1547 $ret->{msg} .= $_."\n";
1548 unless (--$ret->{lines}) {
1549 $log->{state} = 'sep';
1552 croak "Log parse error at: $_\n",
1553 $ret->{revision},"\n";
1561 my $url = shift || $SVN_URL;
1563 my $pid = open my $info_fh, '-|';
1564 defined $pid or croak $!;
1567 exec(qw(svn info),$url) or croak $!;
1571 # only single-lines seem to exist in svn info output
1572 while (<$info_fh>) {
1574 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1576 push @{$ret->{-order}}, $1;
1579 close $info_fh or croak $?;
1583 sub sys { system(@_) == 0 or croak $? }
1586 my ($from, $to) = @_;
1587 my $es = svn_propget_base('svn:eol-style', $to);
1588 open my $rfd, '<', $from or croak $!;
1589 binmode $rfd or croak $!;
1590 open my $wfd, '>', $to or croak $!;
1591 binmode $wfd or croak $!;
1592 eol_cp_fd($rfd, $wfd, $es);
1593 close $rfd or croak $!;
1594 close $wfd or croak $!;
1598 my ($rfd, $wfd, $es) = @_;
1599 my $eol = defined $es ? $EOL{$es} : undef;
1604 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1607 if ($buf =~ /\015$/) {
1609 defined($r = sysread($rfd,$c,1)) or croak $!;
1610 $buf .= $c if $r > 0;
1612 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1615 for ($w = 0; $w < $r; $w += $t) {
1616 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1622 sub do_update_index {
1623 my ($z_cmd, $cmd, $no_text_base) = @_;
1625 my $z = open my $p, '-|';
1626 defined $z or croak $!;
1627 unless ($z) { exec @$z_cmd or croak $! }
1629 my $pid = open my $ui, '|-';
1630 defined $pid or croak $!;
1632 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1635 while (my $x = <$p>) {
1637 if (!$no_text_base && lstat $x && ! -l _ &&
1638 svn_propget_base('svn:keywords', $x)) {
1639 my $mode = -x _ ? 0755 : 0644;
1640 my ($v,$d,$f) = File::Spec->splitpath($x);
1641 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1642 'text-base',"$f.svn-base");
1645 $tb = File::Spec->catfile($d, '.svn',
1646 'text-base',"$f.svn-base");
1649 unlink $x or croak $!;
1651 chmod(($mode &~ umask), $x) or croak $!;
1655 close $ui or croak $?;
1659 return if $_use_lib;
1661 if (!-f "$GIT_SVN_DIR/info/exclude") {
1662 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1663 print $fd '.svn',"\n";
1664 close $fd or croak $!;
1666 my $no_text_base = shift;
1667 do_update_index([qw/git-diff-files --name-only -z/],
1670 do_update_index([qw/git-ls-files -z --others/,
1671 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1677 my ($str, $file, $mode) = @_;
1678 open my $fd,'>',$file or croak $!;
1679 print $fd $str,"\n" or croak $!;
1680 close $fd or croak $!;
1681 chmod ($mode &~ umask, $file) if (defined $mode);
1686 open my $fd,'<',$file or croak "$!: file: $file\n";
1689 close $fd or croak $!;
1694 sub assert_revision_unknown {
1696 if (my $c = revdb_get($REVDB, $r)) {
1697 croak "$r = $c already exists! Why are we refetching it?";
1703 my @x = safe_qx('git-cat-file','commit',$x);
1704 my @y = safe_qx('git-cat-file','commit',$y);
1705 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1706 || $y[0] !~ /^tree $sha1\n$/) {
1707 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1714 my ($log_msg, @parents) = @_;
1715 assert_revision_unknown($log_msg->{revision});
1716 map_tree_joins() if (@_branch_from && !%tree_map);
1718 my (@tmp_parents, @exec_parents, %seen_parent);
1719 if (my $lparents = $log_msg->{parents}) {
1720 @tmp_parents = @$lparents
1722 # commit parents can be conditionally bound to a particular
1723 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1724 foreach my $p (@parents) {
1725 next unless defined $p;
1726 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1727 if ($1 == $log_msg->{revision}) {
1728 push @tmp_parents, $2;
1731 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1734 my $tree = $log_msg->{tree};
1735 if (!defined $tree) {
1736 my $index = set_index($GIT_SVN_INDEX);
1738 chomp($tree = `git-write-tree`);
1740 restore_index($index);
1742 if (exists $tree_map{$tree}) {
1743 push @tmp_parents, @{$tree_map{$tree}};
1745 foreach (@tmp_parents) {
1746 next if $seen_parent{$_};
1747 $seen_parent{$_} = 1;
1748 push @exec_parents, $_;
1749 # MAXPARENT is defined to 16 in commit-tree.c:
1750 last if @exec_parents > 16;
1753 defined(my $pid = open my $out_fh, '-|') or croak $!;
1755 my $msg_fh = IO::File->new_tmpfile or croak $!;
1756 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1757 "$SVN_URL\@$log_msg->{revision}",
1758 " $SVN_UUID\n" or croak $!;
1759 $msg_fh->flush == 0 or croak $!;
1760 seek $msg_fh, 0, 0 or croak $!;
1761 set_commit_env($log_msg);
1762 my @exec = ('git-commit-tree',$tree);
1763 push @exec, '-p', $_ foreach @exec_parents;
1764 open STDIN, '<&', $msg_fh or croak $!;
1765 exec @exec or croak $!;
1767 chomp(my $commit = do { local $/; <$out_fh> });
1768 close $out_fh or croak $?;
1769 if ($commit !~ /^$sha1$/o) {
1770 croak "Failed to commit, invalid sha1: $commit\n";
1772 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1773 if (my $primary_parent = shift @exec_parents) {
1774 quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1775 push @update_ref, $primary_parent unless $?;
1778 revdb_set($REVDB, $log_msg->{revision}, $commit);
1780 # this output is read via pipe, do not change:
1781 print "r$log_msg->{revision} = $commit\n";
1787 if ($_repack && (--$_repack_nr == 0)) {
1788 $_repack_nr = $_repack;
1789 sys("git repack $_repack_flags");
1793 sub set_commit_env {
1795 my $author = $log_msg->{author};
1796 if (!defined $author || length $author == 0) {
1797 $author = '(no author)';
1799 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1800 : ($author,"$author\@$SVN_UUID");
1801 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1802 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1803 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1806 sub apply_mod_line_blob {
1808 if ($m->{mode_b} =~ /^120/) {
1809 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1811 blob_to_file($m->{sha1_b}, $m->{file_b});
1815 sub blob_to_symlink {
1816 my ($blob, $link) = @_;
1817 defined $link or croak "\$link not defined!\n";
1818 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1819 if (-l $link || -f _) {
1820 unlink $link or croak $!;
1823 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1824 symlink $dest, $link or croak $!;
1828 my ($blob, $file) = @_;
1829 defined $file or croak "\$file not defined!\n";
1830 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1831 if (-l $file || -f _) {
1832 unlink $file or croak $!;
1835 open my $blob_fh, '>', $file or croak "$!: $file\n";
1837 defined $pid or croak $!;
1840 open STDOUT, '>&', $blob_fh or croak $!;
1841 exec('git-cat-file','blob',$blob) or croak $!;
1846 close $blob_fh or croak $!;
1850 my $pid = open my $child, '-|';
1851 defined $pid or croak $!;
1853 exec(@_) or croak $!;
1855 my @ret = (<$child>);
1856 close $child or croak $?;
1857 die $? if $?; # just in case close didn't error out
1858 return wantarray ? @ret : join('',@ret);
1861 sub svn_compat_check {
1862 my @co_help = safe_qx(qw(svn co -h));
1863 unless (grep /ignore-externals/,@co_help) {
1864 print STDERR "W: Installed svn version does not support ",
1865 "--ignore-externals\n";
1866 $_no_ignore_ext = 1;
1868 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1869 $_svn_co_url_revs = 1;
1871 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1872 $_svn_pg_peg_revs = 1;
1875 # I really, really hope nobody hits this...
1876 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1878 W: The installed svn version does not support the --stop-on-copy flag in
1880 Lets hope the directory you're tracking is not a branch or tag
1881 and was never moved within the repository...
1887 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1888 # (and they won't honor URL@<rev> without -r<rev>, too!)
1889 sub svn_cmd_checkout {
1890 my ($url, $rev, $dir) = @_;
1891 my @cmd = ('svn','co', "-r$rev");
1892 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1893 $url .= "\@$rev" if $_svn_co_url_revs;
1894 sys(@cmd, $url, $dir);
1897 sub check_upgrade_needed {
1899 open my $fh, '>>',$REVDB or croak $!;
1903 my $pid = open my $child, '-|';
1904 defined $pid or croak $!;
1907 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1909 my @ret = (<$child>);
1910 close $child or croak $?;
1911 die $? if $?; # just in case close didn't error out
1912 return wantarray ? @ret : join('',@ret);
1915 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1917 print STDERR "Please run: $0 rebuild --upgrade\n";
1922 # fills %tree_map with a reverse mapping of trees to commits. Useful
1923 # for finding parents to commit on.
1924 sub map_tree_joins {
1926 foreach my $br (@_branch_from) {
1927 my $pid = open my $pipe, '-|';
1928 defined $pid or croak $!;
1930 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1934 if (/^commit ($sha1)$/o) {
1937 # if we've seen a commit,
1938 # we've seen its parents
1939 last if $seen{$commit};
1940 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1941 unless (defined $tree) {
1942 die "Failed to parse commit $commit\n";
1944 push @{$tree_map{$tree}}, $commit;
1948 close $pipe; # we could be breaking the pipe early
1953 if (@_branch_from) {
1954 print STDERR '--branch|-b parameters are ignored when ',
1955 "--branch-all-refs|-B is passed\n";
1958 # don't worry about rev-list on non-commit objects/tags,
1959 # it shouldn't blow up if a ref is a blob or tree...
1960 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1963 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1965 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1966 while (<$authors>) {
1968 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1969 my ($user, $name, $email) = ($1, $2, $3);
1970 $users{$user} = [$name, $email];
1972 close $authors or croak $!;
1976 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1977 while (<$authors>) {
1979 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1980 my ($user, $name, $email) = ($1, $2, $3);
1981 $rusers{"$name <$email>"} = $user;
1983 close $authors or croak $!;
1986 sub svn_propget_base {
1988 $f .= '@BASE' if $_svn_pg_peg_revs;
1989 return safe_qx(qw/svn propget/, $p, $f);
1994 foreach (`git-rev-parse --symbolic --all`) {
1995 next unless s#^refs/remotes/##;
1997 next unless -f "$GIT_DIR/svn/$_/info/url";
2005 defined(my $pid = fork) or croak $!;
2007 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2009 exit 0 if -r $REVDB;
2010 print "Upgrading svn => git mapping...\n";
2011 open my $fh, '>>',$REVDB or croak $!;
2014 print "Done upgrading. You may now delete the ",
2015 "deprecated $GIT_SVN_DIR/revs directory\n";
2023 sub migration_check {
2024 migrate_revdb() unless (-e $REVDB);
2025 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2026 print "Upgrading repository...\n";
2027 unless (-d "$GIT_DIR/svn") {
2028 mkdir "$GIT_DIR/svn" or croak $!;
2030 print "Data from a previous version of git-svn exists, but\n\t",
2031 "$GIT_SVN_DIR\n\t(required for this version ",
2032 "($VERSION) of git-svn) does not.\n";
2034 foreach my $x (`git-rev-parse --symbolic --all`) {
2035 next unless $x =~ s#^refs/remotes/##;
2037 next unless -f "$GIT_DIR/$x/info/url";
2038 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2040 my $dn = dirname("$GIT_DIR/svn/$x");
2041 mkpath([$dn]) unless -d $dn;
2042 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2044 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2045 print "Done upgrading.\n";
2048 sub find_rev_before {
2049 my ($r, $id, $eq_ok) = @_;
2050 my $f = "$GIT_DIR/svn/$id/.rev_db";
2051 return (undef,undef) unless -r $f;
2054 if (my $c = revdb_get($f, $r)) {
2059 return (undef, undef);
2063 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2064 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2065 $REVDB = "$GIT_SVN_DIR/.rev_db";
2066 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2068 $SVN_WC = "$GIT_SVN_DIR/tree";
2071 # convert GetOpt::Long specs for use by git-repo-config
2072 sub read_repo_config {
2073 return unless -d $GIT_DIR;
2075 foreach my $o (keys %$opts) {
2076 my $v = $opts->{$o};
2077 my ($key) = ($o =~ /^([a-z\-]+)/);
2079 my $arg = 'git-repo-config';
2080 $arg .= ' --int' if ($o =~ /[:=]i$/);
2081 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2082 if (ref $v eq 'ARRAY') {
2083 chomp(my @tmp = `$arg --get-all svn.$key`);
2086 chomp(my $tmp = `$arg --get svn.$key`);
2087 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2094 sub set_default_vals {
2095 if (defined $_repack) {
2096 $_repack = 1000 if ($_repack <= 0);
2097 $_repack_nr = $_repack;
2098 $_repack_flags ||= '-d';
2103 my $gr_file = shift;
2104 my ($grafts, $comments) = ({}, {});
2105 if (open my $fh, '<', $gr_file) {
2108 if (/^($sha1)\s+/) {
2111 @{$comments->{$c}} = @tmp;
2114 foreach my $p (split /\s+/, $_) {
2115 $grafts->{$c}->{$p} = 1;
2121 close $fh or croak $!;
2122 @{$comments->{'END'}} = @tmp if @tmp;
2124 return ($grafts, $comments);
2128 my ($grafts, $comments, $gr_file) = @_;
2130 open my $fh, '>', $gr_file or croak $!;
2131 foreach my $c (sort keys %$grafts) {
2132 if ($comments->{$c}) {
2133 print $fh $_ foreach @{$comments->{$c}};
2135 my $p = $grafts->{$c};
2136 delete $p->{$c}; # commits are not self-reproducing...
2137 my $pid = open my $ch, '-|';
2138 defined $pid or croak $!;
2140 exec(qw/git-cat-file commit/, $c) or croak $!;
2143 if (/^parent ([a-f\d]{40})/) {
2149 close $ch; # breaking the pipe
2150 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2152 if ($comments->{'END'}) {
2153 print $fh $_ foreach @{$comments->{'END'}};
2155 close $fh or croak $!;
2158 sub read_url_paths {
2160 git_svn_each(sub { my $x = shift;
2161 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2162 my ($u, $p) = repo_path_split($url);
2163 $l_map->{$u}->{$p} = $x;
2168 sub extract_metadata {
2170 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2172 if (!$rev || !$uuid || !$url) {
2173 # some of the original repositories I made had
2174 # indentifiers like this:
2175 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2177 return ($url, $rev, $uuid);
2180 sub tz_to_s_offset {
2183 return ($1 * 60) + ($tz * 3600);
2186 sub setup_pager { # translated to Perl from pager.c
2187 return unless (-t *STDOUT);
2188 my $pager = $ENV{PAGER};
2189 if (!defined $pager) {
2191 } elsif (length $pager == 0 || $pager eq 'cat') {
2194 pipe my $rfd, my $wfd or return;
2195 defined(my $pid = fork) or croak $!;
2197 open STDOUT, '>&', $wfd or croak $!;
2200 open STDIN, '<&', $rfd or croak $!;
2201 $ENV{LESS} ||= '-S';
2202 exec $pager or croak "Can't run pager: $!\n";;
2205 sub get_author_info {
2206 my ($dest, $author, $t, $tz) = @_;
2207 $author =~ s/(?:^\s*|\s*$)//g;
2210 $_a = $rusers{$author} || undef;
2213 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2218 # Date::Parse isn't in the standard Perl distro :(
2219 if ($tz =~ s/^\+//) {
2220 $t += tz_to_s_offset($tz);
2221 } elsif ($tz =~ s/^\-//) {
2222 $t -= tz_to_s_offset($tz);
2224 $dest->{t_utc} = $t;
2227 sub process_commit {
2228 my ($c, $r_min, $r_max, $defer) = @_;
2229 if (defined $r_min && defined $r_max) {
2230 if ($r_min == $c->{r} && $r_min == $r_max) {
2234 return 1 if $r_min == $r_max;
2235 if ($r_min < $r_max) {
2236 # we need to reverse the print order
2237 return 0 if (defined $_limit && --$_limit < 0);
2241 if ($r_min != $r_max) {
2242 return 1 if ($r_min < $c->{r});
2243 return 1 if ($r_max > $c->{r});
2246 return 0 if (defined $_limit && --$_limit < 0);
2255 if (my $l = $c->{l}) {
2256 while ($l->[0] =~ /^\s*$/) { shift @$l }
2259 $_l_fmt ||= 'A' . length($c->{r});
2260 print 'r',pack($_l_fmt, $c->{r}),' | ';
2261 print "$c->{c} | " if $_show_commit;
2264 show_commit_normal($c);
2268 sub show_commit_normal {
2270 print '-' x72, "\nr$c->{r} | ";
2271 print "$c->{c} | " if $_show_commit;
2272 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2273 localtime($c->{t_utc})), ' | ';
2276 if (my $l = $c->{l}) {
2277 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2280 $nr_line = scalar @$l;
2282 print "1 line\n\n\n";
2284 if ($nr_line == 1) {
2285 $nr_line = '1 line';
2287 $nr_line .= ' lines';
2289 print $nr_line, "\n\n";
2290 print $_ foreach @$l;
2296 foreach my $x (qw/raw diff/) {
2299 print $_ foreach @{$c->{$x}}
2305 return unless $_use_lib;
2308 if ($SVN::Core::VERSION lt '1.2.1') {
2309 die "Need SVN::Core 1.2.1 or better ",
2310 "(got $SVN::Core::VERSION) ",
2311 "Falling back to command-line svn\n";
2315 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2316 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2317 $SVN::Node::dir.$SVN::Node::unknown.
2318 $SVN::Node::none.$SVN::Node::file.
2319 $SVN::Node::dir.$SVN::Node::unknown;
2324 sub libsvn_connect {
2326 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2327 SVN::Client::get_ssl_server_trust_file_provider(),
2328 SVN::Client::get_username_provider()]);
2329 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2333 sub libsvn_get_file {
2334 my ($gui, $f, $rev) = @_;
2336 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2338 my $fd = IO::File->new_tmpfile or croak $!;
2339 my $pool = SVN::Pool->new;
2340 my ($r, $props) = $SVN->get_file($f, $rev, $fd, $pool);
2342 $fd->flush == 0 or croak $!;
2343 seek $fd, 0, 0 or croak $!;
2344 if (my $es = $props->{'svn:eol-style'}) {
2345 my $new_fd = IO::File->new_tmpfile or croak $!;
2346 eol_cp_fd($fd, $new_fd, $es);
2347 close $fd or croak $!;
2349 seek $fd, 0, 0 or croak $!;
2350 $fd->flush == 0 or croak $!;
2352 my $mode = '100644';
2353 if (exists $props->{'svn:executable'}) {
2356 if (exists $props->{'svn:special'}) {
2360 $link =~ s/^link // or die "svn:special file with contents: <",
2361 $link, "> is not understood\n";
2362 seek $fd, 0, 0 or croak $!;
2363 truncate $fd, 0 or croak $!;
2364 print $fd $link or croak $!;
2365 seek $fd, 0, 0 or croak $!;
2366 $fd->flush == 0 or croak $!;
2368 my $pid = open my $ho, '-|';
2369 defined $pid or croak $!;
2371 open STDIN, '<&', $fd or croak $!;
2372 exec qw/git-hash-object -w --stdin/ or croak $!;
2374 chomp(my $hash = do { local $/; <$ho> });
2375 close $ho or croak $?;
2376 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2377 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2378 close $fd or croak $?;
2381 sub libsvn_log_entry {
2382 my ($rev, $author, $date, $msg, $parents) = @_;
2383 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2384 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2385 or die "Unable to parse date: $date\n";
2386 if (defined $_authors && ! defined $users{$author}) {
2387 die "Author: $author not defined in $_authors file\n";
2389 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2390 author => $author, msg => $msg."\n", parents => $parents || [] }
2394 my ($gui, $last_commit, $f) = @_;
2395 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2396 # remove entire directories.
2397 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2398 defined(my $pid = open my $ls, '-|') or croak $!;
2400 exec(qw/git-ls-tree -r --name-only -z/,
2401 $last_commit,'--',$f) or croak $!;
2405 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2407 close $ls or croak $?;
2409 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2414 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2415 open my $gui, '| git-update-index -z --index-info' or croak $!;
2417 foreach my $f (keys %$paths) {
2418 my $m = $paths->{$f}->action();
2420 if ($m =~ /^[DR]$/) {
2421 process_rm($gui, $last_commit, $f);
2423 # 'R' can be file replacements, too, right?
2425 my $pool = SVN::Pool->new;
2426 my $t = $SVN->check_path($f, $rev, $pool);
2427 if ($t == $SVN::Node::file) {
2428 if ($m =~ /^[AMR]$/) {
2431 die "Unrecognized action: $m, ($f r$rev)\n";
2436 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2437 close $gui or croak $?;
2438 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2441 sub svn_grab_base_rev {
2442 defined(my $pid = open my $fh, '-|') or croak $!;
2444 open my $null, '>', '/dev/null' or croak $!;
2445 open STDERR, '>&', $null or croak $!;
2446 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2449 chomp(my $c = do { local $/; <$fh> });
2451 if (defined $c && length $c) {
2452 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2453 safe_qx(qw/git-cat-file commit/, $c)))[0]);
2456 return (undef, undef);
2459 sub libsvn_parse_revision {
2461 my $head = $SVN->get_latest_revnum();
2462 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2463 return ($base + 1, $head) if (defined $base);
2466 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2467 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2468 if ($_revision =~ /^BASE:(\d+)$/) {
2469 return ($base + 1, $1) if (defined $base);
2472 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2473 die "revision argument: $_revision not understood by git-svn\n",
2474 "Try using the command-line svn client instead\n";
2477 sub libsvn_traverse {
2478 my ($gui, $pfx, $path, $rev) = @_;
2479 my $cwd = "$pfx/$path";
2480 my $pool = SVN::Pool->new;
2482 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2483 foreach my $d (keys %$dirent) {
2484 my $t = $dirent->{$d}->kind;
2485 if ($t == $SVN::Node::dir) {
2486 libsvn_traverse($gui, $cwd, $d, $rev);
2487 } elsif ($t == $SVN::Node::file) {
2488 libsvn_get_file($gui, "$cwd/$d", $rev);
2494 sub libsvn_traverse_ignore {
2495 my ($fh, $path, $r) = @_;
2497 my $pool = SVN::Pool->new;
2498 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2500 $p =~ s#^\Q$SVN_PATH\E/?##;
2501 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2502 if (my $s = $props->{'svn:ignore'}) {
2503 $s =~ s/[\r\n]+/\n/g;
2505 if (length $p == 0) {
2509 $s =~ s#\n#\n/$p/#g;
2510 print $fh "/$p/$s\n";
2513 foreach (sort keys %$dirent) {
2514 next if $dirent->{$_}->kind != $SVN::Node::dir;
2515 libsvn_traverse_ignore($fh, "$path/$_", $r);
2521 my ($path, $r0, $r1) = @_;
2522 return 1 if $r0 == $r1;
2525 # should be OK to use Pool here (r1 - r0) should be small
2526 my $pool = SVN::Pool->new;
2527 $SVN->get_log("/$path", $r0, $r1, 0, 1, 1, sub {$nr++},$pool);
2530 my ($url, undef) = repo_path_split($SVN_URL);
2531 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2532 while (next_log_entry($svn_log)) { $nr++ }
2533 close $svn_log->{fh};
2535 return 0 if ($nr > 1);
2539 sub libsvn_find_parent_branch {
2540 my ($paths, $rev, $author, $date, $msg) = @_;
2541 my $svn_path = '/'.$SVN_PATH;
2543 # look for a parent from another branch:
2544 my $i = $paths->{$svn_path} or return;
2545 my $branch_from = $i->copyfrom_path or return;
2546 my $r = $i->copyfrom_rev;
2547 print STDERR "Found possible branch point: ",
2548 "$branch_from => $svn_path, $r\n";
2549 $branch_from =~ s#^/##;
2550 my $l_map = read_url_paths();
2551 my $url = $SVN->{url};
2552 defined $l_map->{$url} or return;
2553 my $id = $l_map->{$url}->{$branch_from} or return;
2554 my ($r0, $parent) = find_rev_before($r,$id,1);
2555 return unless (defined $r0 && defined $parent);
2556 if (revisions_eq($branch_from, $r0, $r)) {
2557 unlink $GIT_SVN_INDEX;
2558 print STDERR "Found branch parent: $parent\n";
2559 sys(qw/git-read-tree/, $parent);
2560 return libsvn_fetch($parent, $paths, $rev,
2561 $author, $date, $msg);
2563 print STDERR "Nope, branch point not imported or unknown\n";
2567 sub libsvn_new_tree {
2568 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2571 my ($paths, $rev, $author, $date, $msg) = @_;
2572 open my $gui, '| git-update-index -z --index-info' or croak $!;
2573 my $pool = SVN::Pool->new;
2574 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2576 close $gui or croak $?;
2577 return libsvn_log_entry($rev, $author, $date, $msg);
2580 sub find_graft_path_commit {
2581 my ($tree_paths, $p1, $r1) = @_;
2582 foreach my $x (keys %$tree_paths) {
2583 next unless ($p1 =~ /^\Q$x\E/);
2584 my $i = $tree_paths->{$x};
2585 my ($r0, $parent) = find_rev_before($r1,$i,1);
2586 return $parent if (defined $r0 && $r0 == $r1);
2587 print STDERR "r$r1 of $i not imported\n";
2593 sub find_graft_path_parents {
2594 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2595 foreach my $x (keys %$tree_paths) {
2596 next unless ($p0 =~ /^\Q$x\E/);
2597 my $i = $tree_paths->{$x};
2598 my ($r, $parent) = find_rev_before($r0, $i, 1);
2599 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2600 $grafts->{$c}->{$parent} = 1;
2605 sub libsvn_graft_file_copies {
2606 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2607 foreach (keys %$paths) {
2608 my $i = $paths->{$_};
2609 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2611 next unless (defined $p0 && defined $r0);
2616 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2618 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2623 my $old = $ENV{GIT_INDEX_FILE};
2624 $ENV{GIT_INDEX_FILE} = shift;
2631 $ENV{GIT_INDEX_FILE} = $old;
2633 delete $ENV{GIT_INDEX_FILE};
2637 sub libsvn_commit_cb {
2638 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2639 if ($_optimize_commits && $rev == ($r_last + 1)) {
2640 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2641 $log->{tree} = get_tree_from_treeish($c);
2642 my $cmt = git_commit($log, $cmt_last, $c);
2643 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2645 print STDERR "Trees differ: $cmt $c\n",
2646 join('',@diff),"\n";
2654 sub libsvn_ls_fullurl {
2655 my $fullurl = shift;
2656 my ($repo, $path) = repo_path_split($fullurl);
2657 $SVN ||= libsvn_connect($repo);
2659 my $pool = SVN::Pool->new;
2660 my ($dirent, undef, undef) = $SVN->get_dir($path,
2661 $SVN->get_latest_revnum, $pool);
2662 foreach my $d (keys %$dirent) {
2663 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2664 push @ret, "$d/"; # add '/' for compat with cli svn
2672 sub libsvn_skip_unknown_revs {
2674 my $errno = $err->apr_err();
2675 # Maybe the branch we're tracking didn't
2676 # exist when the repo started, so it's
2677 # not an error if it doesn't, just continue
2679 # Wonderfully consistent library, eh?
2680 # 160013 - svn:// and file://
2681 # 175002 - http(s)://
2682 # More codes may be discovered later...
2683 if ($errno == 175002 || $errno == 160013) {
2686 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2689 # Tie::File seems to be prone to offset errors if revisions get sparse,
2690 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2691 # one of my favorite modules is out :< Next up would be one of the DBM
2692 # modules, but I'm not sure which is most portable... So I'll just
2693 # go with something that's plain-text, but still capable of
2694 # being randomly accessed. So here's my ultra-simple fixed-width
2695 # database. All records are 40 characters + "\n", so it's easy to seek
2696 # to a revision: (41 * rev) is the byte offset.
2697 # A record of 40 0s denotes an empty revision.
2698 # And yes, it's still pretty fast (faster than Tie::File).
2700 my ($file, $rev, $commit) = @_;
2701 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2702 open my $fh, '+<', $file or croak $!;
2703 my $offset = $rev * 41;
2704 # assume that append is the common case:
2705 seek $fh, 0, 2 or croak $!;
2707 if ($pos < $offset) {
2708 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2710 seek $fh, $offset, 0 or croak $!;
2711 print $fh $commit,"\n";
2712 close $fh or croak $!;
2716 my ($file, $rev) = @_;
2718 my $offset = $rev * 41;
2719 open my $fh, '<', $file or croak $!;
2720 seek $fh, $offset, 0;
2721 if (tell $fh == $offset) {
2722 $ret = readline $fh;
2725 $ret = undef if ($ret =~ /^0{40}$/);
2728 close $fh or croak $!;
2732 package SVN::Git::Editor;
2741 my $git_svn = shift;
2742 my $self = SVN::Delta::Editor->new(@_);
2743 bless $self, $class;
2744 foreach (qw/svn_path c r ra /) {
2745 die "$_ required!\n" unless (defined $git_svn->{$_});
2746 $self->{$_} = $git_svn->{$_};
2748 $self->{pool} = SVN::Pool->new;
2749 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2751 require Digest::MD5;
2756 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2760 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2765 my ($self, $path) = @_;
2766 $self->{ra}->{url} . '/' . $self->repo_path($path);
2771 my $rm = $self->{rm};
2772 delete $rm->{''}; # we never delete the url we're tracking
2775 foreach (keys %$rm) {
2776 my @d = split m#/#, $_;
2780 $c .= '/' . shift @d;
2784 delete $rm->{$self->{svn_path}};
2785 delete $rm->{''}; # we never delete the url we're tracking
2788 defined(my $pid = open my $fh,'-|') or croak $!;
2790 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2795 $_ = $self->{svn_path} . '/' . $_;
2796 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2800 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2801 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2802 $self->close_directory($bat->{$d}, $p);
2803 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2804 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2809 sub open_or_add_dir {
2810 my ($self, $full_path, $baton) = @_;
2811 my $p = SVN::Pool->new;
2812 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2814 if ($t == $SVN::Node::none) {
2815 return $self->add_directory($full_path, $baton,
2816 undef, -1, $self->{pool});
2817 } elsif ($t == $SVN::Node::dir) {
2818 return $self->open_directory($full_path, $baton,
2819 $self->{r}, $self->{pool});
2821 print STDERR "$full_path already exists in repository at ",
2822 "r$self->{r} and it is not a directory (",
2823 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2828 my ($self, $path) = @_;
2829 my $bat = $self->{bat};
2830 $path = $self->repo_path($path);
2831 return $bat->{''} unless (length $path);
2832 my @p = split m#/+#, $path;
2834 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2837 $c .= '/' . shift @p;
2838 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
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,
2849 $self->chg_file($fbat, $m);
2850 $self->close_file($fbat,undef,$self->{pool});
2854 my ($self, $m) = @_;
2855 my ($dir, $file) = split_path($m->{file_b});
2856 my $pbat = $self->ensure_path($dir);
2857 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2858 $self->url_path($m->{file_a}), $self->{r});
2859 $self->chg_file($fbat, $m);
2860 $self->close_file($fbat,undef,$self->{pool});
2864 my ($self, $path, $pbat) = @_;
2865 my $rpath = $self->repo_path($path);
2866 my ($dir, $file) = split_path($rpath);
2867 $self->{rm}->{$dir} = 1;
2868 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2872 my ($self, $m) = @_;
2873 my ($dir, $file) = split_path($m->{file_b});
2874 my $pbat = $self->ensure_path($dir);
2875 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2876 $self->url_path($m->{file_a}), $self->{r});
2877 $self->chg_file($fbat, $m);
2878 $self->close_file($fbat,undef,$self->{pool});
2880 ($dir, $file) = split_path($m->{file_a});
2881 $pbat = $self->ensure_path($dir);
2882 $self->delete_entry($m->{file_a}, $pbat);
2886 my ($self, $m) = @_;
2887 my ($dir, $file) = split_path($m->{file_b});
2888 my $pbat = $self->ensure_path($dir);
2889 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2890 $pbat,$self->{r},$self->{pool});
2891 $self->chg_file($fbat, $m);
2892 $self->close_file($fbat,undef,$self->{pool});
2895 sub T { shift->M(@_) }
2897 sub change_file_prop {
2898 my ($self, $fbat, $pname, $pval) = @_;
2899 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2903 my ($self, $fbat, $m) = @_;
2904 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2905 $self->change_file_prop($fbat,'svn:executable','*');
2906 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2907 $self->change_file_prop($fbat,'svn:executable',undef);
2909 my $fh = IO::File->new_tmpfile or croak $!;
2910 if ($m->{mode_b} =~ /^120/) {
2911 print $fh 'link ' or croak $!;
2912 $self->change_file_prop($fbat,'svn:special','*');
2913 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2914 $self->change_file_prop($fbat,'svn:special',undef);
2916 defined(my $pid = fork) or croak $!;
2918 open STDOUT, '>&', $fh or croak $!;
2919 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2923 $fh->flush == 0 or croak $!;
2924 seek $fh, 0, 0 or croak $!;
2926 my $md5 = Digest::MD5->new;
2927 $md5->addfile($fh) or croak $!;
2928 seek $fh, 0, 0 or croak $!;
2930 my $exp = $md5->hexdigest;
2931 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2932 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2933 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2935 close $fh or croak $!;
2939 my ($self, $m) = @_;
2940 my ($dir, $file) = split_path($m->{file_b});
2941 my $pbat = $self->ensure_path($dir);
2942 $self->delete_entry($m->{file_b}, $pbat);
2947 my ($p,$bat) = ($self->{pool}, $self->{bat});
2948 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2949 $self->close_directory($bat->{$_}, $p);
2951 $self->SUPER::close_edit($p);
2957 $self->SUPER::abort_edit($self->{pool});
2958 $self->{pool}->clear;
2965 $svn_log hashref (as returned by svn_log_raw)
2967 fh => file handle of the log file,
2968 state => state of the log file parser (sep/msg/rev/msg_start...)
2971 $log_msg hashref as returned by next_log_entry($svn_log)
2973 msg => 'whitespace-formatted log entry
2974 ', # trailing newline is preserved
2975 revision => '8', # integer
2976 date => '2004-02-24T17:01:44.108345Z', # commit date
2977 author => 'committer name'
2981 @mods = array of diff-index line hashes, each element represents one line
2982 of diff-index output
2984 diff-index line ($m hash)
2986 mode_a => first column of diff-index output, no leading ':',
2987 mode_b => second column of diff-index output,
2988 sha1_b => sha1sum of the final blob,
2989 chg => change type [MCRADT],
2990 file_a => original file name of a file (iff chg is 'C' or 'R')
2991 file_b => new/current file name of a file (any chg)
2996 I don't trust the each() function on unless I created %hash myself
2997 because the internal iterator may not have started at base.