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;
371 print "Fetching revisions $min .. $max\n";
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(
394 $SVN::Error::handler = sub { 'quiet warnings' };
399 ($last_rev, $last_commit) = svn_grab_base_rev();
400 last if ($max >= $head);
403 $max = $head if ($max > $head);
405 restore_index($index);
406 return { revision => $last_rev, commit => $last_commit };
411 check_upgrade_needed();
412 if ($_stdin || !@commits) {
413 print "Reading from stdin...\n";
416 if (/\b($sha1_short)\b/o) {
417 unshift @commits, $1;
422 foreach my $c (@commits) {
423 chomp(my @tmp = safe_qx('git-rev-parse',$c));
424 if (scalar @tmp == 1) {
426 } elsif (scalar @tmp > 1) {
427 push @revs, reverse (safe_qx('git-rev-list',@tmp));
429 die "Failed to rev-parse $c\n";
433 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
434 print "Done committing ",scalar @revs," revisions to SVN\n";
440 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
441 my $info = svn_info('.');
442 my $fetched = fetch();
443 if ($info->{Revision} != $fetched->{revision}) {
444 print STDERR "There are new revisions that were fetched ",
445 "and need to be merged (or acknowledged) ",
446 "before committing.\n";
449 $info = svn_info('.');
452 foreach my $c (@revs) {
453 my $mods = svn_checkout_tree($last, $c);
454 if (scalar @$mods == 0) {
455 print "Skipping, no changes detected\n";
458 $last = svn_commit_tree($last, $c);
464 my ($r_last, $cmt_last) = svn_grab_base_rev();
465 defined $r_last or die "Must have an existing revision to commit\n";
466 my $fetched = fetch_lib();
467 if ($r_last != $fetched->{revision}) {
468 print STDERR "There are new revisions that were fetched ",
469 "and need to be merged (or acknowledged) ",
470 "before committing.\n",
471 "last rev: $r_last\n",
472 " current: $fetched->{revision}\n";
476 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
477 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
479 foreach my $c (@revs) {
480 # fork for each commit because there's a memory leak I
481 # can't track down... (it's probably in the SVN code)
482 defined(my $pid = open my $fh, '-|') or croak $!;
484 if (defined $LC_ALL) {
485 $ENV{LC_ALL} = $LC_ALL;
489 my $log_msg = get_commit_message($c, $commit_msg);
490 my $ed = SVN::Git::Editor->new(
494 svn_path => $SVN_PATH
496 $SVN->get_commit_editor(
507 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
509 print "No changes\nr$r_last = $cmt_last\n";
516 my ($r_new, $cmt_new, $no);
520 if (/^r(\d+) = ($sha1)$/o) {
521 ($r_new, $cmt_new) = ($1, $2);
522 } elsif ($_ eq 'No changes') {
526 close $fh or croak $!;
527 if (! defined $r_new && ! defined $cmt_new) {
529 die "Failed to parse revision information\n";
532 ($r_last, $cmt_last) = ($r_new, $cmt_new);
539 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
540 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
543 sub show_ignore_cmd {
544 require File::Find or die $!;
545 if (defined $_revision) {
546 die "-r/--revision option doesn't work unless the Perl SVN ",
547 "libraries are used\n";
549 chdir $SVN_WC or croak $!;
551 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
553 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
554 }}, no_chdir=>1},'.');
557 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
559 foreach my $i (sort keys %ign) {
560 print "\n# ",$i,"\n";
561 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
565 sub show_ignore_lib {
567 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
568 $SVN ||= libsvn_connect($repo);
569 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
570 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
574 my $gr_file = "$GIT_DIR/info/grafts";
575 my ($grafts, $comments) = read_grafts($gr_file);
579 # temporarily disable our grafts file to make this idempotent
580 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
581 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
584 my $l_map = read_url_paths();
585 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
586 unless ($_no_default_regex) {
587 push @re, ( qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
588 qr/\b(?:from|of)\s+(\S.+)/is );
590 foreach my $u (keys %$l_map) {
592 foreach my $p (keys %{$l_map->{$u}}) {
593 graft_merge_msg($grafts,$l_map,$u,$p);
596 unless ($_no_graft_copy) {
598 graft_file_copy_lib($grafts,$l_map,$u);
600 graft_file_copy_cmd($grafts,$l_map,$u);
605 write_grafts($grafts, $comments, $gr_file);
606 unlink "$gr_file~$gr_sha1" if $gr_sha1;
613 $url =~ s#/+$## if $url;
614 if ($_trunk !~ m#^[a-z\+]+://#) {
615 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
617 print STDERR "E: '$_trunk' is not a complete URL ",
618 "and a separate URL is not specified\n";
621 $_trunk = $url . $_trunk;
623 if ($GIT_SVN eq 'git-svn') {
624 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
625 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
629 complete_url_ls_init($url, $_branches, '--branches/-b', '');
630 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
634 # try to do trunk first, since branches/tags
635 # may be descended from it.
636 if (-d "$GIT_DIR/svn/trunk") {
637 print "Fetching trunk\n";
638 defined(my $pid = fork) or croak $!;
640 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
648 rec_fetch('', "$GIT_DIR/svn", @_);
654 my $r_last = -1; # prevent dupes
655 rload_authors() if $_authors;
661 if (defined $_revision) {
662 if ($_revision =~ /^(\d+):(\d+)$/) {
663 ($r_min, $r_max) = ($1, $2);
664 } elsif ($_revision =~ /^\d+$/) {
665 $r_min = $r_max = $_revision;
667 print STDERR "-r$_revision is not supported, use ",
668 "standard \'git log\' arguments instead\n";
673 my $pid = open(my $log,'-|');
674 defined $pid or croak $!;
676 my @rl = (qw/git-log --abbrev-commit --pretty=raw
677 --default/, "remotes/$GIT_SVN");
678 push @rl, '--raw' if $_verbose;
679 exec(@rl, @args) or croak $!;
684 if (/^commit ($sha1_short)/o) {
686 if ($c && defined $c->{r} && $c->{r} != $r_last) {
688 process_commit($c, $r_min, $r_max, \@k) or
693 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
694 get_author_info($c, $1, $2, $3);
695 } elsif (/^(?:tree|parent|committer) /) {
697 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
698 push @{$c->{raw}}, $_;
701 push @{$c->{diff}}, $_;
703 push @{$c->{diff}}, $_;
704 } elsif (/^ (git-svn-id:.+)$/) {
705 my ($url, $rev, $uuid) = extract_metadata($1);
711 if ($c && defined $c->{r} && $c->{r} != $r_last) {
713 process_commit($c, $r_min, $r_max, \@k);
719 process_commit($_, $r_min, $r_max) foreach reverse @k;
723 print '-' x72,"\n" unless $_incremental || $_oneline;
726 ########################### utility functions #########################
729 my ($pfx, $p, @args) = @_;
731 foreach (sort <$p/*>) {
732 if (-r "$_/info/url") {
733 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
734 my $id = $pfx . basename $_;
735 next if $id eq 'trunk';
736 print "Fetching $id\n";
737 defined(my $pid = fork) or croak $!;
739 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
752 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
757 sub complete_url_ls_init {
758 my ($url, $var, $switch, $pfx) = @_;
760 print STDERR "W: $switch not specified\n";
764 if ($var !~ m#^[a-z\+]+://#) {
765 $var = '/' . $var if ($var !~ m#^/#);
767 print STDERR "E: '$var' is not a complete URL ",
768 "and a separate URL is not specified\n";
773 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
774 : safe_qx(qw/svn ls --non-interactive/, $var));
776 defined(my $pid = fork) or croak $!;
778 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
780 if ($u !~ m!\Q$var\E/(.+)$!) {
781 print STDERR "W: Unrecognized URL: $u\n";
782 die "This should never happen\n";
785 print "init $u => $id\n";
786 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
800 my @tmp = split m#/#, $_;
802 while (my $x = shift @tmp) {
808 foreach (sort {length $b <=> length $a} keys %common) {
809 if ($common{$_} == @$paths) {
816 # this isn't funky-filename safe, but good enough for now...
817 sub graft_file_copy_cmd {
818 my ($grafts, $l_map, $u) = @_;
819 my $paths = $l_map->{$u};
820 my $pfx = common_prefix([keys %$paths]);
821 $SVN_URL ||= $u.$pfx;
822 my $pid = open my $fh, '-|';
823 defined $pid or croak $!;
825 my @exec = qw/svn log -v/;
826 push @exec, "-r$_revision" if defined $_revision;
827 exec @exec, $u.$pfx or croak $!;
829 my ($r, $mp) = (undef, undef);
834 } elsif (/^r(\d+) \| /) {
835 $r = $1 unless defined $r;
836 } elsif (/^Changed paths:/) {
838 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
839 my ($p1, $p0, $r0) = ($1, $2, $3);
840 my $c = find_graft_path_commit($paths, $p1, $r);
842 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
847 sub graft_file_copy_lib {
848 my ($grafts, $l_map, $u) = @_;
849 my $tree_paths = $l_map->{$u};
850 my $pfx = common_prefix([keys %$tree_paths]);
851 my ($repo, $path) = repo_path_split($u.$pfx);
852 $SVN_LOG ||= libsvn_connect($repo);
853 $SVN ||= libsvn_connect($repo);
855 my ($base, $head) = libsvn_parse_revision();
857 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
858 my $eh = $SVN::Error::handler;
859 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
861 my $pool = SVN::Pool->new;
862 $SVN_LOG->get_log( "/$path", $min, $max, 0, 1, 1,
864 libsvn_graft_file_copies($grafts, $tree_paths,
868 last if ($max >= $head);
871 $max = $head if ($max > $head);
873 $SVN::Error::handler = $eh;
876 sub process_merge_msg_matches {
877 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
880 # merging with ourselves is not interesting
882 if ($l_map->{$u}->{$_}) {
888 foreach my $w (@weak) {
890 # no exact match, use branch name as regexp.
891 my $re = qr/\Q$w\E/i;
892 foreach (keys %{$l_map->{$u}}) {
901 foreach (keys %{$l_map->{$u}}) {
908 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
909 \s(?:[a-f\d\-]+)$/xsm);
910 unless (defined $rev) {
911 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
912 \@(?:[a-f\d\-]+)/xsm);
913 return unless defined $rev;
915 foreach my $m (@strong) {
916 my ($r0, $s0) = find_rev_before($rev, $m);
917 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
921 sub graft_merge_msg {
922 my ($grafts, $l_map, $u, $p, @re) = @_;
924 my $x = $l_map->{$u}->{$p};
925 my $rl = rev_list_raw($x);
926 while (my $c = next_rev_list_entry($rl)) {
927 foreach my $re (@re) {
928 my (@br) = ($c->{m} =~ /$re/g);
930 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
938 my $pool = SVN::Pool->new;
939 $SVN_UUID = $SVN->get_uuid($pool);
942 my $info = shift || svn_info('.');
943 $SVN_UUID = $info->{'Repository UUID'} or
944 croak "Repository UUID unreadable\n";
946 s_to_file($SVN_UUID,"$GIT_SVN_DIR/info/uuid");
951 defined $pid or croak $!;
953 open my $null, '>', '/dev/null' or croak $!;
954 open STDERR, '>&', $null or croak $!;
955 open STDOUT, '>&', $null or croak $!;
962 sub repo_path_split {
963 my $full_url = shift;
964 $full_url =~ s#/+$##;
966 foreach (@repo_path_split_cache) {
967 if ($full_url =~ s#$_##) {
969 $full_url =~ s#^/+##;
970 return ($u, $full_url);
974 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
976 my @paths = split(m#/+#, $path);
980 $SVN = libsvn_connect($url);
981 last if (defined $SVN &&
982 defined eval { $SVN->get_latest_revnum });
983 my $n = shift @paths || last;
987 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
988 my $n = shift @paths || last;
992 push @repo_path_split_cache, qr/^(\Q$url\E)/;
993 $path = join('/',@paths);
994 return ($url, $path);
998 defined $SVN_URL or croak "SVN repository location required\n";
999 unless (-d $GIT_DIR) {
1000 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1002 mkpath([$GIT_SVN_DIR]);
1003 mkpath(["$GIT_SVN_DIR/info"]);
1004 open my $fh, '>>',$REVDB or croak $!;
1006 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1010 sub assert_svn_wc_clean {
1011 return if $_use_lib;
1013 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1014 my $lcr = svn_info('.')->{'Last Changed Rev'};
1015 if ($svn_rev != $lcr) {
1016 print STDERR "Checking for copy-tree ... ";
1017 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1018 "-r$lcr:$svn_rev")));
1020 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1022 print STDERR "OK!\n";
1025 my @status = grep(!/^Performing status on external/,(`svn status`));
1026 @status = grep(!/^\s*$/,@status);
1027 if (scalar @status) {
1028 print STDERR "Tree ($SVN_WC) is not clean:\n";
1029 print STDERR $_ foreach @status;
1034 sub get_tree_from_treeish {
1036 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1037 chomp(my $type = `git-cat-file -t $treeish`);
1039 while ($type eq 'tag') {
1040 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1042 if ($type eq 'commit') {
1043 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1044 ($expected) = ($expected =~ /^tree ($sha1)$/);
1045 die "Unable to get tree from $treeish\n" unless $expected;
1046 } elsif ($type eq 'tree') {
1047 $expected = $treeish;
1049 die "$treeish is a $type, expected tree, tag or commit\n";
1055 return if $_use_lib;
1057 my $expected = get_tree_from_treeish($treeish);
1059 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1061 unlink $tmpindex or croak $!;
1063 my $old_index = set_index($tmpindex);
1065 chomp(my $tree = `git-write-tree`);
1066 restore_index($old_index);
1067 if ($tree ne $expected) {
1068 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1073 sub parse_diff_tree {
1074 my $diff_fh = shift;
1078 while (<$diff_fh>) {
1079 chomp $_; # this gets rid of the trailing "\0"
1080 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1081 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1082 push @mods, { mode_a => $1, mode_b => $2,
1083 sha1_b => $3, chg => $4 };
1084 if ($4 =~ /^(?:C|R)$/) {
1089 } elsif ($state eq 'file_a') {
1090 my $x = $mods[$#mods] or croak "Empty array\n";
1091 if ($x->{chg} !~ /^(?:C|R)$/) {
1092 croak "Error parsing $_, $x->{chg}\n";
1096 } elsif ($state eq 'file_b') {
1097 my $x = $mods[$#mods] or croak "Empty array\n";
1098 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1099 croak "Error parsing $_, $x->{chg}\n";
1101 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1102 croak "Error parsing $_, $x->{chg}\n";
1107 croak "Error parsing $_\n";
1110 close $diff_fh or croak $!;
1115 sub svn_check_prop_executable {
1117 return if -l $m->{file_b};
1118 if ($m->{mode_b} =~ /755$/) {
1119 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1120 if ($m->{mode_a} !~ /755$/) {
1121 sys(qw(svn propset svn:executable 1), $m->{file_b});
1123 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1124 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1125 sys(qw(svn propdel svn:executable), $m->{file_b});
1126 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1127 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1131 sub svn_ensure_parent_path {
1132 my $dir_b = dirname(shift);
1133 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1134 mkpath([$dir_b]) unless (-d $dir_b);
1135 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1138 sub precommit_check {
1140 my (%rm_file, %rmdir_check, %added_check);
1142 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1143 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1144 if ($m->{chg} eq 'R') {
1145 if (-d $m->{file_b}) {
1146 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1148 # dir/$file => dir/file/$file
1149 my $dirname = dirname($m->{file_b});
1150 while ($dirname ne File::Spec->curdir) {
1151 if ($dirname ne $m->{file_a}) {
1152 $dirname = dirname($dirname);
1155 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1157 # baz/zzz => baz (baz is a file)
1158 $dirname = dirname($m->{file_a});
1159 while ($dirname ne File::Spec->curdir) {
1160 if ($dirname ne $m->{file_b}) {
1161 $dirname = dirname($dirname);
1164 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1167 if ($m->{chg} =~ /^(D|R)$/) {
1168 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1169 $rm_file{ $m->{$t} } = 1;
1170 my $dirname = dirname( $m->{$t} );
1171 my $basename = basename( $m->{$t} );
1172 $rmdir_check{$dirname}->{$basename} = 1;
1173 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1174 if (-d $m->{file_b}) {
1175 err_dir_to_file($m->{file_b});
1177 my $dirname = dirname( $m->{file_b} );
1178 my $basename = basename( $m->{file_b} );
1179 $added_check{$dirname}->{$basename} = 1;
1180 while ($dirname ne File::Spec->curdir) {
1181 if ($rm_file{$dirname}) {
1182 err_file_to_dir($m->{file_b});
1184 $dirname = dirname $dirname;
1188 return (\%rmdir_check, \%added_check);
1190 sub err_dir_to_file {
1192 print STDERR "Node change from directory to file ",
1193 "is not supported by Subversion: ",$file,"\n";
1196 sub err_file_to_dir {
1198 print STDERR "Node change from file to directory ",
1199 "is not supported by Subversion: ",$file,"\n";
1206 my ($from, $treeish) = @_;
1208 print "diff-tree $from $treeish\n";
1209 my $pid = open my $diff_fh, '-|';
1210 defined $pid or croak $!;
1212 my @diff_tree = qw(git-diff-tree -z -r);
1213 if ($_cp_similarity) {
1214 push @diff_tree, "-C$_cp_similarity";
1216 push @diff_tree, '-C';
1218 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1219 push @diff_tree, "-l$_l" if defined $_l;
1220 exec(@diff_tree, $from, $treeish) or croak $!;
1222 return parse_diff_tree($diff_fh);
1225 sub svn_checkout_tree {
1226 my ($from, $treeish) = @_;
1227 my $mods = get_diff($from->{commit}, $treeish);
1228 return $mods unless (scalar @$mods);
1229 my ($rm, $add) = precommit_check($mods);
1231 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1232 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1233 if ($m->{chg} eq 'C') {
1234 svn_ensure_parent_path( $m->{file_b} );
1235 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1236 apply_mod_line_blob($m);
1237 svn_check_prop_executable($m);
1238 } elsif ($m->{chg} eq 'D') {
1239 sys(qw(svn rm --force), $m->{file_b});
1240 } elsif ($m->{chg} eq 'R') {
1241 svn_ensure_parent_path( $m->{file_b} );
1242 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1243 apply_mod_line_blob($m);
1244 svn_check_prop_executable($m);
1245 } elsif ($m->{chg} eq 'M') {
1246 apply_mod_line_blob($m);
1247 svn_check_prop_executable($m);
1248 } elsif ($m->{chg} eq 'T') {
1249 sys(qw(svn rm --force),$m->{file_b});
1250 apply_mod_line_blob($m);
1251 sys(qw(svn add --force), $m->{file_b});
1252 svn_check_prop_executable($m);
1253 } elsif ($m->{chg} eq 'A') {
1254 svn_ensure_parent_path( $m->{file_b} );
1255 apply_mod_line_blob($m);
1256 sys(qw(svn add --force), $m->{file_b});
1257 svn_check_prop_executable($m);
1259 croak "Invalid chg: $m->{chg}\n";
1263 assert_tree($treeish);
1264 if ($_rmdir) { # remove empty directories
1265 handle_rmdir($rm, $add);
1267 assert_tree($treeish);
1271 sub libsvn_checkout_tree {
1272 my ($from, $treeish, $ed) = @_;
1273 my $mods = get_diff($from, $treeish);
1274 return $mods unless (scalar @$mods);
1275 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1276 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1278 if (defined $o{$f}) {
1281 croak "Invalid change type: $f\n";
1284 $ed->rmdirs if $_rmdir;
1288 # svn ls doesn't work with respect to the current working tree, but what's
1289 # in the repository. There's not even an option for it... *sigh*
1290 # (added files don't show up and removed files remain in the ls listing)
1291 sub svn_ls_current {
1292 my ($dir, $rm, $add) = @_;
1293 chomp(my @ls = safe_qx('svn','ls',$dir));
1296 s#/$##; # trailing slashes are evil
1297 push @ret, $_ unless $rm->{$dir}->{$_};
1299 if (exists $add->{$dir}) {
1300 push @ret, keys %{$add->{$dir}};
1306 my ($rm, $add) = @_;
1308 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1309 my $ls = svn_ls_current($dir, $rm, $add);
1310 next if (scalar @$ls);
1311 sys(qw(svn rm --force),$dir);
1313 my $dn = dirname $dir;
1314 $rm->{ $dn }->{ basename $dir } = 1;
1315 $ls = svn_ls_current($dn, $rm, $add);
1316 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1317 sys(qw(svn rm --force),$dn);
1318 $dir = basename $dn;
1320 $rm->{ $dn }->{ $dir } = 1;
1321 $ls = svn_ls_current($dn, $rm, $add);
1326 sub get_commit_message {
1327 my ($commit, $commit_msg) = (@_);
1328 my %log_msg = ( msg => '' );
1329 open my $msg, '>', $commit_msg or croak $!;
1331 print "commit: $commit\n";
1332 chomp(my $type = `git-cat-file -t $commit`);
1333 if ($type eq 'commit') {
1334 my $pid = open my $msg_fh, '-|';
1335 defined $pid or croak $!;
1338 exec(qw(git-cat-file commit), $commit) or croak $!;
1343 $in_msg = 1 if (/^\s*$/);
1344 } elsif (/^git-svn-id: /) {
1345 # skip this, we regenerate the correct one
1346 # on re-fetch anyways
1348 print $msg $_ or croak $!;
1351 close $msg_fh or croak $!;
1353 close $msg or croak $!;
1355 if ($_edit || ($type eq 'tree')) {
1356 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1357 system($editor, $commit_msg);
1360 # file_to_s removes all trailing newlines, so just use chomp() here:
1361 open $msg, '<', $commit_msg or croak $!;
1362 { local $/; chomp($log_msg{msg} = <$msg>); }
1363 close $msg or croak $!;
1368 sub svn_commit_tree {
1369 my ($last, $commit) = @_;
1370 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1371 my $log_msg = get_commit_message($commit, $commit_msg);
1372 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1373 print "Committing $commit: $oneline\n";
1375 if (defined $LC_ALL) {
1376 $ENV{LC_ALL} = $LC_ALL;
1378 delete $ENV{LC_ALL};
1380 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1383 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1384 if (!defined $committed) {
1385 my $out = join("\n",@ci_output);
1386 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1387 $out, "\n\nAssuming English locale...";
1388 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1389 defined $committed or die " FAILED!\n",
1390 "Commit output failed to parse committed revision!\n",
1391 print STDERR " OK\n";
1394 my @svn_up = qw(svn up);
1395 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1396 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1397 push @svn_up, "-r$committed";
1399 my $info = svn_info('.');
1400 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1401 if ($info->{'Last Changed Rev'} != $committed) {
1402 croak "$info->{'Last Changed Rev'} != $committed\n"
1404 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1405 /(\d{4})\-(\d\d)\-(\d\d)\s
1406 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1407 or croak "Failed to parse date: $date\n";
1408 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1409 $log_msg->{author} = $info->{'Last Changed Author'};
1410 $log_msg->{revision} = $committed;
1411 $log_msg->{msg} .= "\n";
1412 $log_msg->{parents} = [ $last->{commit} ];
1413 $log_msg->{commit} = git_commit($log_msg, $commit);
1416 # resync immediately
1417 push @svn_up, "-r$last->{revision}";
1419 return fetch("$committed=$commit");
1424 my $pid = open my $fh, '-|';
1425 defined $pid or croak $!;
1427 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1429 return { fh => $fh, t => { } };
1432 sub next_rev_list_entry {
1437 if (/^commit ($sha1)$/o) {
1439 $rl->{t} = { c => $1 };
1444 } elsif (/^parent ($sha1)$/o) {
1451 return ($x != $rl->{t}) ? $x : undef;
1454 # read the entire log into a temporary file (which is removed ASAP)
1455 # and store the file handle + parser state
1457 my (@log_args) = @_;
1458 my $log_fh = IO::File->new_tmpfile or croak $!;
1460 defined $pid or croak $!;
1462 open STDOUT, '>&', $log_fh or croak $!;
1463 exec (qw(svn log), @log_args) or croak $!
1467 seek $log_fh, 0, 0 or croak $!;
1468 return { state => 'sep', fh => $log_fh };
1471 sub next_log_entry {
1472 my $log = shift; # retval of svn_log_raw()
1474 my $fh = $log->{fh};
1479 if ($log->{state} eq 'msg') {
1480 if ($ret->{lines}) {
1481 $ret->{msg} .= $_."\n";
1482 unless(--$ret->{lines}) {
1483 $log->{state} = 'sep';
1486 croak "Log parse error at: $_\n",
1492 if ($log->{state} ne 'sep') {
1493 croak "Log parse error at: $_\n",
1494 "state: $log->{state}\n",
1498 $log->{state} = 'rev';
1500 # if we have an empty log message, put something there:
1502 $ret->{msg} ||= "\n";
1503 delete $ret->{lines};
1508 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1510 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1511 ($lines) = ($lines =~ /(\d+)/);
1512 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1513 /(\d{4})\-(\d\d)\-(\d\d)\s
1514 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1515 or croak "Failed to parse date: $date\n";
1516 $ret = { revision => $rev,
1517 date => "$tz $Y-$m-$d $H:$M:$S",
1521 if (defined $_authors && ! defined $users{$author}) {
1522 die "Author: $author not defined in ",
1525 $log->{state} = 'msg_start';
1528 # skip the first blank line of the message:
1529 if ($log->{state} eq 'msg_start' && /^$/) {
1530 $log->{state} = 'msg';
1531 } elsif ($log->{state} eq 'msg') {
1532 if ($ret->{lines}) {
1533 $ret->{msg} .= $_."\n";
1534 unless (--$ret->{lines}) {
1535 $log->{state} = 'sep';
1538 croak "Log parse error at: $_\n",
1539 $ret->{revision},"\n";
1547 my $url = shift || $SVN_URL;
1549 my $pid = open my $info_fh, '-|';
1550 defined $pid or croak $!;
1553 exec(qw(svn info),$url) or croak $!;
1557 # only single-lines seem to exist in svn info output
1558 while (<$info_fh>) {
1560 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1562 push @{$ret->{-order}}, $1;
1565 close $info_fh or croak $!;
1569 sub sys { system(@_) == 0 or croak $? }
1572 my ($from, $to) = @_;
1573 my $es = svn_propget_base('svn:eol-style', $to);
1574 open my $rfd, '<', $from or croak $!;
1575 binmode $rfd or croak $!;
1576 open my $wfd, '>', $to or croak $!;
1577 binmode $wfd or croak $!;
1578 eol_cp_fd($rfd, $wfd, $es);
1579 close $rfd or croak $!;
1580 close $wfd or croak $!;
1584 my ($rfd, $wfd, $es) = @_;
1585 my $eol = defined $es ? $EOL{$es} : undef;
1590 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1593 if ($buf =~ /\015$/) {
1595 defined($r = sysread($rfd,$c,1)) or croak $!;
1596 $buf .= $c if $r > 0;
1598 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1601 for ($w = 0; $w < $r; $w += $t) {
1602 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1608 sub do_update_index {
1609 my ($z_cmd, $cmd, $no_text_base) = @_;
1611 my $z = open my $p, '-|';
1612 defined $z or croak $!;
1613 unless ($z) { exec @$z_cmd or croak $! }
1615 my $pid = open my $ui, '|-';
1616 defined $pid or croak $!;
1618 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1621 while (my $x = <$p>) {
1623 if (!$no_text_base && lstat $x && ! -l _ &&
1624 svn_propget_base('svn:keywords', $x)) {
1625 my $mode = -x _ ? 0755 : 0644;
1626 my ($v,$d,$f) = File::Spec->splitpath($x);
1627 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1628 'text-base',"$f.svn-base");
1631 $tb = File::Spec->catfile($d, '.svn',
1632 'text-base',"$f.svn-base");
1635 unlink $x or croak $!;
1637 chmod(($mode &~ umask), $x) or croak $!;
1641 close $ui or croak $!;
1645 return if $_use_lib;
1647 if (!-f "$GIT_SVN_DIR/info/exclude") {
1648 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1649 print $fd '.svn',"\n";
1650 close $fd or croak $!;
1652 my $no_text_base = shift;
1653 do_update_index([qw/git-diff-files --name-only -z/],
1656 do_update_index([qw/git-ls-files -z --others/,
1657 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1663 my ($str, $file, $mode) = @_;
1664 open my $fd,'>',$file or croak $!;
1665 print $fd $str,"\n" or croak $!;
1666 close $fd or croak $!;
1667 chmod ($mode &~ umask, $file) if (defined $mode);
1672 open my $fd,'<',$file or croak "$!: file: $file\n";
1675 close $fd or croak $!;
1680 sub assert_revision_unknown {
1682 if (my $c = revdb_get($REVDB, $r)) {
1683 croak "$r = $c already exists! Why are we refetching it?";
1689 my @x = safe_qx('git-cat-file','commit',$x);
1690 my @y = safe_qx('git-cat-file','commit',$y);
1691 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1692 || $y[0] !~ /^tree $sha1\n$/) {
1693 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1700 my ($log_msg, @parents) = @_;
1701 assert_revision_unknown($log_msg->{revision});
1702 map_tree_joins() if (@_branch_from && !%tree_map);
1704 my (@tmp_parents, @exec_parents, %seen_parent);
1705 if (my $lparents = $log_msg->{parents}) {
1706 @tmp_parents = @$lparents
1708 # commit parents can be conditionally bound to a particular
1709 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1710 foreach my $p (@parents) {
1711 next unless defined $p;
1712 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1713 if ($1 == $log_msg->{revision}) {
1714 push @tmp_parents, $2;
1717 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1720 my $tree = $log_msg->{tree};
1721 if (!defined $tree) {
1722 my $index = set_index($GIT_SVN_INDEX);
1724 chomp($tree = `git-write-tree`);
1726 restore_index($index);
1728 if (exists $tree_map{$tree}) {
1729 push @tmp_parents, @{$tree_map{$tree}};
1731 foreach (@tmp_parents) {
1732 next if $seen_parent{$_};
1733 $seen_parent{$_} = 1;
1734 push @exec_parents, $_;
1735 # MAXPARENT is defined to 16 in commit-tree.c:
1736 last if @exec_parents > 16;
1739 defined(my $pid = open my $out_fh, '-|') or croak $!;
1741 my $msg_fh = IO::File->new_tmpfile or croak $!;
1742 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1743 "$SVN_URL\@$log_msg->{revision}",
1744 " $SVN_UUID\n" or croak $!;
1745 $msg_fh->flush == 0 or croak $!;
1746 seek $msg_fh, 0, 0 or croak $!;
1747 set_commit_env($log_msg);
1748 my @exec = ('git-commit-tree',$tree);
1749 push @exec, '-p', $_ foreach @exec_parents;
1750 open STDIN, '<&', $msg_fh or croak $!;
1751 exec @exec or croak $!;
1753 chomp(my $commit = do { local $/; <$out_fh> });
1754 close $out_fh or croak $?;
1755 if ($commit !~ /^$sha1$/o) {
1756 croak "Failed to commit, invalid sha1: $commit\n";
1758 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1759 if (my $primary_parent = shift @exec_parents) {
1760 quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1761 push @update_ref, $primary_parent unless $?;
1764 revdb_set($REVDB, $log_msg->{revision}, $commit);
1766 # this output is read via pipe, do not change:
1767 print "r$log_msg->{revision} = $commit\n";
1768 if ($_repack && (--$_repack_nr == 0)) {
1769 $_repack_nr = $_repack;
1770 sys("git repack $_repack_flags");
1775 sub set_commit_env {
1777 my $author = $log_msg->{author};
1778 if (!defined $author || length $author == 0) {
1779 $author = '(no author)';
1781 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1782 : ($author,"$author\@$SVN_UUID");
1783 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1784 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1785 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1788 sub apply_mod_line_blob {
1790 if ($m->{mode_b} =~ /^120/) {
1791 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1793 blob_to_file($m->{sha1_b}, $m->{file_b});
1797 sub blob_to_symlink {
1798 my ($blob, $link) = @_;
1799 defined $link or croak "\$link not defined!\n";
1800 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1801 if (-l $link || -f _) {
1802 unlink $link or croak $!;
1805 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1806 symlink $dest, $link or croak $!;
1810 my ($blob, $file) = @_;
1811 defined $file or croak "\$file not defined!\n";
1812 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1813 if (-l $file || -f _) {
1814 unlink $file or croak $!;
1817 open my $blob_fh, '>', $file or croak "$!: $file\n";
1819 defined $pid or croak $!;
1822 open STDOUT, '>&', $blob_fh or croak $!;
1823 exec('git-cat-file','blob',$blob) or croak $!;
1828 close $blob_fh or croak $!;
1832 my $pid = open my $child, '-|';
1833 defined $pid or croak $!;
1835 exec(@_) or croak $!;
1837 my @ret = (<$child>);
1838 close $child or croak $?;
1839 die $? if $?; # just in case close didn't error out
1840 return wantarray ? @ret : join('',@ret);
1843 sub svn_compat_check {
1844 my @co_help = safe_qx(qw(svn co -h));
1845 unless (grep /ignore-externals/,@co_help) {
1846 print STDERR "W: Installed svn version does not support ",
1847 "--ignore-externals\n";
1848 $_no_ignore_ext = 1;
1850 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1851 $_svn_co_url_revs = 1;
1853 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1854 $_svn_pg_peg_revs = 1;
1857 # I really, really hope nobody hits this...
1858 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1860 W: The installed svn version does not support the --stop-on-copy flag in
1862 Lets hope the directory you're tracking is not a branch or tag
1863 and was never moved within the repository...
1869 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1870 # (and they won't honor URL@<rev> without -r<rev>, too!)
1871 sub svn_cmd_checkout {
1872 my ($url, $rev, $dir) = @_;
1873 my @cmd = ('svn','co', "-r$rev");
1874 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1875 $url .= "\@$rev" if $_svn_co_url_revs;
1876 sys(@cmd, $url, $dir);
1879 sub check_upgrade_needed {
1881 my $pid = open my $child, '-|';
1882 defined $pid or croak $!;
1885 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1887 my @ret = (<$child>);
1888 close $child or croak $?;
1889 die $? if $?; # just in case close didn't error out
1890 return wantarray ? @ret : join('',@ret);
1893 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1895 print STDERR "Please run: $0 rebuild --upgrade\n";
1900 # fills %tree_map with a reverse mapping of trees to commits. Useful
1901 # for finding parents to commit on.
1902 sub map_tree_joins {
1904 foreach my $br (@_branch_from) {
1905 my $pid = open my $pipe, '-|';
1906 defined $pid or croak $!;
1908 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1912 if (/^commit ($sha1)$/o) {
1915 # if we've seen a commit,
1916 # we've seen its parents
1917 last if $seen{$commit};
1918 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1919 unless (defined $tree) {
1920 die "Failed to parse commit $commit\n";
1922 push @{$tree_map{$tree}}, $commit;
1926 close $pipe; # we could be breaking the pipe early
1931 if (@_branch_from) {
1932 print STDERR '--branch|-b parameters are ignored when ',
1933 "--branch-all-refs|-B is passed\n";
1936 # don't worry about rev-list on non-commit objects/tags,
1937 # it shouldn't blow up if a ref is a blob or tree...
1938 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
1941 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1943 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1944 while (<$authors>) {
1946 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1947 my ($user, $name, $email) = ($1, $2, $3);
1948 $users{$user} = [$name, $email];
1950 close $authors or croak $!;
1954 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1955 while (<$authors>) {
1957 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
1958 my ($user, $name, $email) = ($1, $2, $3);
1959 $rusers{"$name <$email>"} = $user;
1961 close $authors or croak $!;
1964 sub svn_propget_base {
1966 $f .= '@BASE' if $_svn_pg_peg_revs;
1967 return safe_qx(qw/svn propget/, $p, $f);
1972 foreach (`git-rev-parse --symbolic --all`) {
1973 next unless s#^refs/remotes/##;
1975 next unless -f "$GIT_DIR/svn/$_/info/url";
1983 defined(my $pid = fork) or croak $!;
1985 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1987 exit 0 if -r $REVDB;
1988 print "Upgrading svn => git mapping...\n";
1989 open my $fh, '>>',$REVDB or croak $!;
1992 print "Done upgrading. You may now delete the ",
1993 "deprecated $GIT_SVN_DIR/revs directory\n";
2001 sub migration_check {
2002 migrate_revdb() unless (-e $REVDB);
2003 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2004 print "Upgrading repository...\n";
2005 unless (-d "$GIT_DIR/svn") {
2006 mkdir "$GIT_DIR/svn" or croak $!;
2008 print "Data from a previous version of git-svn exists, but\n\t",
2009 "$GIT_SVN_DIR\n\t(required for this version ",
2010 "($VERSION) of git-svn) does not.\n";
2012 foreach my $x (`git-rev-parse --symbolic --all`) {
2013 next unless $x =~ s#^refs/remotes/##;
2015 next unless -f "$GIT_DIR/$x/info/url";
2016 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2018 my $dn = dirname("$GIT_DIR/svn/$x");
2019 mkpath([$dn]) unless -d $dn;
2020 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2022 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2023 print "Done upgrading.\n";
2026 sub find_rev_before {
2027 my ($r, $id, $eq_ok) = @_;
2028 my $f = "$GIT_DIR/svn/$id/.rev_db";
2029 # --$r unless $eq_ok;
2031 if (my $c = revdb_get($f, $r)) {
2036 return (undef, undef);
2040 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2041 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2042 $REVDB = "$GIT_SVN_DIR/.rev_db";
2043 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2045 $SVN_WC = "$GIT_SVN_DIR/tree";
2048 # convert GetOpt::Long specs for use by git-repo-config
2049 sub read_repo_config {
2050 return unless -d $GIT_DIR;
2052 foreach my $o (keys %$opts) {
2053 my $v = $opts->{$o};
2054 my ($key) = ($o =~ /^([a-z\-]+)/);
2056 my $arg = 'git-repo-config';
2057 $arg .= ' --int' if ($o =~ /[:=]i$/);
2058 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2059 if (ref $v eq 'ARRAY') {
2060 chomp(my @tmp = `$arg --get-all svn.$key`);
2063 chomp(my $tmp = `$arg --get svn.$key`);
2064 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2071 sub set_default_vals {
2072 if (defined $_repack) {
2073 $_repack = 1000 if ($_repack <= 0);
2074 $_repack_nr = $_repack;
2075 $_repack_flags ||= '';
2080 my $gr_file = shift;
2081 my ($grafts, $comments) = ({}, {});
2082 if (open my $fh, '<', $gr_file) {
2085 if (/^($sha1)\s+/) {
2088 @{$comments->{$c}} = @tmp;
2091 foreach my $p (split /\s+/, $_) {
2092 $grafts->{$c}->{$p} = 1;
2098 close $fh or croak $!;
2099 @{$comments->{'END'}} = @tmp if @tmp;
2101 return ($grafts, $comments);
2105 my ($grafts, $comments, $gr_file) = @_;
2107 open my $fh, '>', $gr_file or croak $!;
2108 foreach my $c (sort keys %$grafts) {
2109 if ($comments->{$c}) {
2110 print $fh $_ foreach @{$comments->{$c}};
2112 my $p = $grafts->{$c};
2113 delete $p->{$c}; # commits are not self-reproducing...
2114 my $pid = open my $ch, '-|';
2115 defined $pid or croak $!;
2117 exec(qw/git-cat-file commit/, $c) or croak $!;
2120 if (/^parent ([a-f\d]{40})/) {
2126 close $ch; # breaking the pipe
2127 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2129 if ($comments->{'END'}) {
2130 print $fh $_ foreach @{$comments->{'END'}};
2132 close $fh or croak $!;
2135 sub read_url_paths {
2137 git_svn_each(sub { my $x = shift;
2138 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2139 my ($u, $p) = repo_path_split($url);
2140 $l_map->{$u}->{$p} = $x;
2145 sub extract_metadata {
2147 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2149 if (!$rev || !$uuid || !$url) {
2150 # some of the original repositories I made had
2151 # indentifiers like this:
2152 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2154 return ($url, $rev, $uuid);
2157 sub tz_to_s_offset {
2160 return ($1 * 60) + ($tz * 3600);
2163 sub setup_pager { # translated to Perl from pager.c
2164 return unless (-t *STDOUT);
2165 my $pager = $ENV{PAGER};
2166 if (!defined $pager) {
2168 } elsif (length $pager == 0 || $pager eq 'cat') {
2171 pipe my $rfd, my $wfd or return;
2172 defined(my $pid = fork) or croak $!;
2174 open STDOUT, '>&', $wfd or croak $!;
2177 open STDIN, '<&', $rfd or croak $!;
2178 $ENV{LESS} ||= '-S';
2179 exec $pager or croak "Can't run pager: $!\n";;
2182 sub get_author_info {
2183 my ($dest, $author, $t, $tz) = @_;
2184 $author =~ s/(?:^\s*|\s*$)//g;
2187 $_a = $rusers{$author} || undef;
2190 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2195 # Date::Parse isn't in the standard Perl distro :(
2196 if ($tz =~ s/^\+//) {
2197 $t += tz_to_s_offset($tz);
2198 } elsif ($tz =~ s/^\-//) {
2199 $t -= tz_to_s_offset($tz);
2201 $dest->{t_utc} = $t;
2204 sub process_commit {
2205 my ($c, $r_min, $r_max, $defer) = @_;
2206 if (defined $r_min && defined $r_max) {
2207 if ($r_min == $c->{r} && $r_min == $r_max) {
2211 return 1 if $r_min == $r_max;
2212 if ($r_min < $r_max) {
2213 # we need to reverse the print order
2214 return 0 if (defined $_limit && --$_limit < 0);
2218 if ($r_min != $r_max) {
2219 return 1 if ($r_min < $c->{r});
2220 return 1 if ($r_max > $c->{r});
2223 return 0 if (defined $_limit && --$_limit < 0);
2232 if (my $l = $c->{l}) {
2233 while ($l->[0] =~ /^\s*$/) { shift @$l }
2236 $_l_fmt ||= 'A' . length($c->{r});
2237 print 'r',pack($_l_fmt, $c->{r}),' | ';
2238 print "$c->{c} | " if $_show_commit;
2241 show_commit_normal($c);
2245 sub show_commit_normal {
2247 print '-' x72, "\nr$c->{r} | ";
2248 print "$c->{c} | " if $_show_commit;
2249 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2250 localtime($c->{t_utc})), ' | ';
2253 if (my $l = $c->{l}) {
2254 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2257 $nr_line = scalar @$l;
2259 print "1 line\n\n\n";
2261 if ($nr_line == 1) {
2262 $nr_line = '1 line';
2264 $nr_line .= ' lines';
2266 print $nr_line, "\n\n";
2267 print $_ foreach @$l;
2273 foreach my $x (qw/raw diff/) {
2276 print $_ foreach @{$c->{$x}}
2282 return unless $_use_lib;
2285 if ($SVN::Core::VERSION lt '1.2.1') {
2286 die "Need SVN::Core 1.2.1 or better ",
2287 "(got $SVN::Core::VERSION) ",
2288 "Falling back to command-line svn\n";
2292 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2293 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2294 $SVN::Node::dir.$SVN::Node::unknown.
2295 $SVN::Node::none.$SVN::Node::file.
2296 $SVN::Node::dir.$SVN::Node::unknown;
2301 sub libsvn_connect {
2303 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2304 SVN::Client::get_ssl_server_trust_file_provider(),
2305 SVN::Client::get_username_provider()]);
2306 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2310 sub libsvn_get_file {
2311 my ($gui, $f, $rev) = @_;
2313 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2315 my $fd = IO::File->new_tmpfile or croak $!;
2316 my $pool = SVN::Pool->new;
2317 my ($r, $props) = $SVN->get_file($f, $rev, $fd, $pool);
2319 $fd->flush == 0 or croak $!;
2320 seek $fd, 0, 0 or croak $!;
2321 if (my $es = $props->{'svn:eol-style'}) {
2322 my $new_fd = IO::File->new_tmpfile or croak $!;
2323 eol_cp_fd($fd, $new_fd, $es);
2324 close $fd or croak $!;
2326 seek $fd, 0, 0 or croak $!;
2327 $fd->flush == 0 or croak $!;
2329 my $mode = '100644';
2330 if (exists $props->{'svn:executable'}) {
2333 if (exists $props->{'svn:special'}) {
2337 $link =~ s/^link // or die "svn:special file with contents: <",
2338 $link, "> is not understood\n";
2339 seek $fd, 0, 0 or croak $!;
2340 truncate $fd, 0 or croak $!;
2341 print $fd $link or croak $!;
2342 seek $fd, 0, 0 or croak $!;
2343 $fd->flush == 0 or croak $!;
2345 my $pid = open my $ho, '-|';
2346 defined $pid or croak $!;
2348 open STDIN, '<&', $fd or croak $!;
2349 exec qw/git-hash-object -w --stdin/ or croak $!;
2351 chomp(my $hash = do { local $/; <$ho> });
2352 close $ho or croak $?;
2353 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2354 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2355 close $fd or croak $!;
2358 sub libsvn_log_entry {
2359 my ($rev, $author, $date, $msg, $parents) = @_;
2360 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2361 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2362 or die "Unable to parse date: $date\n";
2363 if (defined $_authors && ! defined $users{$author}) {
2364 die "Author: $author not defined in $_authors file\n";
2366 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2367 author => $author, msg => $msg."\n", parents => $parents || [] }
2371 my ($gui, $last_commit, $f) = @_;
2372 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2373 # remove entire directories.
2374 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2375 defined(my $pid = open my $ls, '-|') or croak $!;
2377 exec(qw/git-ls-tree -r --name-only -z/,
2378 $last_commit,'--',$f) or croak $!;
2382 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2384 close $ls or croak $!;
2386 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2391 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2392 open my $gui, '| git-update-index -z --index-info' or croak $!;
2394 foreach my $f (keys %$paths) {
2395 my $m = $paths->{$f}->action();
2397 if ($m =~ /^[DR]$/) {
2398 process_rm($gui, $last_commit, $f);
2400 # 'R' can be file replacements, too, right?
2402 my $pool = SVN::Pool->new;
2403 my $t = $SVN->check_path($f, $rev, $pool);
2404 if ($t == $SVN::Node::file) {
2405 if ($m =~ /^[AMR]$/) {
2408 die "Unrecognized action: $m, ($f r$rev)\n";
2413 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2414 close $gui or croak $!;
2415 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2418 sub svn_grab_base_rev {
2419 defined(my $pid = open my $fh, '-|') or croak $!;
2421 open my $null, '>', '/dev/null' or croak $!;
2422 open STDERR, '>&', $null or croak $!;
2423 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2426 chomp(my $c = do { local $/; <$fh> });
2428 if (defined $c && length $c) {
2429 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2430 safe_qx(qw/git-cat-file commit/, $c)))[0]);
2433 return (undef, undef);
2436 sub libsvn_parse_revision {
2438 my $head = $SVN->get_latest_revnum();
2439 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2440 return ($base + 1, $head) if (defined $base);
2443 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2444 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2445 if ($_revision =~ /^BASE:(\d+)$/) {
2446 return ($base + 1, $1) if (defined $base);
2449 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2450 die "revision argument: $_revision not understood by git-svn\n",
2451 "Try using the command-line svn client instead\n";
2454 sub libsvn_traverse {
2455 my ($gui, $pfx, $path, $rev) = @_;
2456 my $cwd = "$pfx/$path";
2457 my $pool = SVN::Pool->new;
2459 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2460 foreach my $d (keys %$dirent) {
2461 my $t = $dirent->{$d}->kind;
2462 if ($t == $SVN::Node::dir) {
2463 libsvn_traverse($gui, $cwd, $d, $rev);
2464 } elsif ($t == $SVN::Node::file) {
2465 libsvn_get_file($gui, "$cwd/$d", $rev);
2471 sub libsvn_traverse_ignore {
2472 my ($fh, $path, $r) = @_;
2474 my $pool = SVN::Pool->new;
2475 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2477 $p =~ s#^\Q$SVN_PATH\E/?##;
2478 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2479 if (my $s = $props->{'svn:ignore'}) {
2480 $s =~ s/[\r\n]+/\n/g;
2482 if (length $p == 0) {
2486 $s =~ s#\n#\n/$p/#g;
2487 print $fh "/$p/$s\n";
2490 foreach (sort keys %$dirent) {
2491 next if $dirent->{$_}->kind != $SVN::Node::dir;
2492 libsvn_traverse_ignore($fh, "$path/$_", $r);
2498 my ($path, $r0, $r1) = @_;
2499 return 1 if $r0 == $r1;
2502 # should be OK to use Pool here (r1 - r0) should be small
2503 my $pool = SVN::Pool->new;
2504 $SVN->get_log("/$path", $r0, $r1, 0, 1, 1, sub {$nr++},$pool);
2507 my ($url, undef) = repo_path_split($SVN_URL);
2508 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2509 while (next_log_entry($svn_log)) { $nr++ }
2510 close $svn_log->{fh};
2512 return 0 if ($nr > 1);
2516 sub libsvn_find_parent_branch {
2517 return undef; # XXX this function is disabled atm (not tested enough)
2518 my ($paths, $rev, $author, $date, $msg) = @_;
2519 my $svn_path = '/'.$SVN_PATH;
2521 # look for a parent from another branch:
2522 foreach (keys %$paths) {
2523 next if ($_ ne $svn_path);
2524 my $i = $paths->{$_};
2525 my $branch_from = $i->copyfrom_path or next;
2526 my $r = $i->copyfrom_rev;
2527 print STDERR "Found possible branch point: ",
2528 "$branch_from => $svn_path, $r\n";
2529 $branch_from =~ s#^/##;
2530 my $l_map = read_url_paths();
2531 my $url = $SVN->{url};
2532 defined $l_map->{$url} or next;
2533 my $id = $l_map->{$url}->{$branch_from} or next;
2534 my ($r0, $parent) = find_rev_before($r,$id,1);
2535 if (defined $r0 && defined $parent &&
2536 revisions_eq($branch_from, $r0, $r)) {
2537 unlink $GIT_SVN_INDEX;
2538 print STDERR "Found branch parent: $parent\n";
2539 sys(qw/git-read-tree/, $parent);
2540 return libsvn_fetch($parent, $paths, $rev,
2541 $author, $date, $msg);
2544 "Nope, branch point not imported or unknown\n";
2550 sub libsvn_new_tree {
2551 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2554 my ($paths, $rev, $author, $date, $msg) = @_;
2555 open my $gui, '| git-update-index -z --index-info' or croak $!;
2556 my $pool = SVN::Pool->new;
2557 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2559 close $gui or croak $!;
2560 return libsvn_log_entry($rev, $author, $date, $msg);
2563 sub find_graft_path_commit {
2564 my ($tree_paths, $p1, $r1) = @_;
2565 foreach my $x (keys %$tree_paths) {
2566 next unless ($p1 =~ /^\Q$x\E/);
2567 my $i = $tree_paths->{$x};
2568 my ($r0, $parent) = find_rev_before($r1,$i,1);
2569 return $parent if (defined $r0 && $r0 == $r1);
2570 print STDERR "r$r1 of $i not imported\n";
2576 sub find_graft_path_parents {
2577 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2578 foreach my $x (keys %$tree_paths) {
2579 next unless ($p0 =~ /^\Q$x\E/);
2580 my $i = $tree_paths->{$x};
2581 my ($r, $parent) = find_rev_before($r0, $i, 1);
2582 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2583 $grafts->{$c}->{$parent} = 1;
2588 sub libsvn_graft_file_copies {
2589 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2590 foreach (keys %$paths) {
2591 my $i = $paths->{$_};
2592 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2594 next unless (defined $p0 && defined $r0);
2599 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2601 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2606 my $old = $ENV{GIT_INDEX_FILE};
2607 $ENV{GIT_INDEX_FILE} = shift;
2614 $ENV{GIT_INDEX_FILE} = $old;
2616 delete $ENV{GIT_INDEX_FILE};
2620 sub libsvn_commit_cb {
2621 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2622 if ($_optimize_commits && $rev == ($r_last + 1)) {
2623 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2624 $log->{tree} = get_tree_from_treeish($c);
2625 my $cmt = git_commit($log, $cmt_last, $c);
2626 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2628 print STDERR "Trees differ: $cmt $c\n",
2629 join('',@diff),"\n";
2633 fetch_lib("$rev=$c");
2637 sub libsvn_ls_fullurl {
2638 my $fullurl = shift;
2639 my ($repo, $path) = repo_path_split($fullurl);
2640 $SVN ||= libsvn_connect($repo);
2642 my $pool = SVN::Pool->new;
2643 my ($dirent, undef, undef) = $SVN->get_dir($path,
2644 $SVN->get_latest_revnum, $pool);
2645 foreach my $d (keys %$dirent) {
2646 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2647 push @ret, "$d/"; # add '/' for compat with cli svn
2655 sub libsvn_skip_unknown_revs {
2657 my $errno = $err->apr_err();
2658 # Maybe the branch we're tracking didn't
2659 # exist when the repo started, so it's
2660 # not an error if it doesn't, just continue
2662 # Wonderfully consistent library, eh?
2663 # 160013 - svn:// and file://
2664 # 175002 - http(s)://
2665 # More codes may be discovered later...
2666 if ($errno == 175002 || $errno == 160013) {
2667 print STDERR "directory non-existent\n";
2670 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2673 # Tie::File seems to be prone to offset errors if revisions get sparse,
2674 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2675 # one of my favorite modules is out :< Next up would be one of the DBM
2676 # modules, but I'm not sure which is most portable... So I'll just
2677 # go with something that's plain-text, but still capable of
2678 # being randomly accessed. So here's my ultra-simple fixed-width
2679 # database. All records are 40 characters + "\n", so it's easy to seek
2680 # to a revision: (41 * rev) is the byte offset.
2681 # A record of 40 0s denotes an empty revision.
2682 # And yes, it's still pretty fast (faster than Tie::File).
2684 my ($file, $rev, $commit) = @_;
2685 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2686 open my $fh, '+<', $file or croak $!;
2687 my $offset = $rev * 41;
2688 # assume that append is the common case:
2689 seek $fh, 0, 2 or croak $!;
2691 if ($pos < $offset) {
2692 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2694 seek $fh, $offset, 0 or croak $!;
2695 print $fh $commit,"\n";
2696 close $fh or croak $!;
2700 my ($file, $rev) = @_;
2702 my $offset = $rev * 41;
2703 open my $fh, '<', $file or croak $!;
2704 seek $fh, $offset, 0;
2705 if (tell $fh == $offset) {
2706 $ret = readline $fh;
2709 $ret = undef if ($ret =~ /^0{40}$/);
2712 close $fh or croak $!;
2716 package SVN::Git::Editor;
2725 my $git_svn = shift;
2726 my $self = SVN::Delta::Editor->new(@_);
2727 bless $self, $class;
2728 foreach (qw/svn_path c r ra /) {
2729 die "$_ required!\n" unless (defined $git_svn->{$_});
2730 $self->{$_} = $git_svn->{$_};
2732 $self->{pool} = SVN::Pool->new;
2733 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2735 require Digest::MD5;
2740 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2744 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2749 my ($self, $path) = @_;
2750 $self->{ra}->{url} . '/' . $self->repo_path($path);
2755 my $rm = $self->{rm};
2756 delete $rm->{''}; # we never delete the url we're tracking
2759 foreach (keys %$rm) {
2760 my @d = split m#/#, $_;
2764 $c .= '/' . shift @d;
2768 delete $rm->{$self->{svn_path}};
2769 delete $rm->{''}; # we never delete the url we're tracking
2772 defined(my $pid = open my $fh,'-|') or croak $!;
2774 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2779 $_ = $self->{svn_path} . '/' . $_;
2780 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2784 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2785 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2786 $self->close_directory($bat->{$d}, $p);
2787 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2788 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2793 sub open_or_add_dir {
2794 my ($self, $full_path, $baton) = @_;
2795 my $p = SVN::Pool->new;
2796 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2798 if ($t == $SVN::Node::none) {
2799 return $self->add_directory($full_path, $baton,
2800 undef, -1, $self->{pool});
2801 } elsif ($t == $SVN::Node::dir) {
2802 return $self->open_directory($full_path, $baton,
2803 $self->{r}, $self->{pool});
2805 print STDERR "$full_path already exists in repository at ",
2806 "r$self->{r} and it is not a directory (",
2807 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2812 my ($self, $path) = @_;
2813 my $bat = $self->{bat};
2814 $path = $self->repo_path($path);
2815 return $bat->{''} unless (length $path);
2816 my @p = split m#/+#, $path;
2818 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2821 $c .= '/' . shift @p;
2822 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2828 my ($self, $m) = @_;
2829 my ($dir, $file) = split_path($m->{file_b});
2830 my $pbat = $self->ensure_path($dir);
2831 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2833 $self->chg_file($fbat, $m);
2834 $self->close_file($fbat,undef,$self->{pool});
2838 my ($self, $m) = @_;
2839 my ($dir, $file) = split_path($m->{file_b});
2840 my $pbat = $self->ensure_path($dir);
2841 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2842 $self->url_path($m->{file_a}), $self->{r});
2843 $self->chg_file($fbat, $m);
2844 $self->close_file($fbat,undef,$self->{pool});
2848 my ($self, $path, $pbat) = @_;
2849 my $rpath = $self->repo_path($path);
2850 my ($dir, $file) = split_path($rpath);
2851 $self->{rm}->{$dir} = 1;
2852 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2856 my ($self, $m) = @_;
2857 my ($dir, $file) = split_path($m->{file_b});
2858 my $pbat = $self->ensure_path($dir);
2859 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2860 $self->url_path($m->{file_a}), $self->{r});
2861 $self->chg_file($fbat, $m);
2862 $self->close_file($fbat,undef,$self->{pool});
2864 ($dir, $file) = split_path($m->{file_a});
2865 $pbat = $self->ensure_path($dir);
2866 $self->delete_entry($m->{file_a}, $pbat);
2870 my ($self, $m) = @_;
2871 my ($dir, $file) = split_path($m->{file_b});
2872 my $pbat = $self->ensure_path($dir);
2873 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2874 $pbat,$self->{r},$self->{pool});
2875 $self->chg_file($fbat, $m);
2876 $self->close_file($fbat,undef,$self->{pool});
2879 sub T { shift->M(@_) }
2881 sub change_file_prop {
2882 my ($self, $fbat, $pname, $pval) = @_;
2883 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2887 my ($self, $fbat, $m) = @_;
2888 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2889 $self->change_file_prop($fbat,'svn:executable','*');
2890 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2891 $self->change_file_prop($fbat,'svn:executable',undef);
2893 my $fh = IO::File->new_tmpfile or croak $!;
2894 if ($m->{mode_b} =~ /^120/) {
2895 print $fh 'link ' or croak $!;
2896 $self->change_file_prop($fbat,'svn:special','*');
2897 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2898 $self->change_file_prop($fbat,'svn:special',undef);
2900 defined(my $pid = fork) or croak $!;
2902 open STDOUT, '>&', $fh or croak $!;
2903 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2907 $fh->flush == 0 or croak $!;
2908 seek $fh, 0, 0 or croak $!;
2910 my $md5 = Digest::MD5->new;
2911 $md5->addfile($fh) or croak $!;
2912 seek $fh, 0, 0 or croak $!;
2914 my $exp = $md5->hexdigest;
2915 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2916 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2917 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2919 close $fh or croak $!;
2923 my ($self, $m) = @_;
2924 my ($dir, $file) = split_path($m->{file_b});
2925 my $pbat = $self->ensure_path($dir);
2926 $self->delete_entry($m->{file_b}, $pbat);
2931 my ($p,$bat) = ($self->{pool}, $self->{bat});
2932 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2933 $self->close_directory($bat->{$_}, $p);
2935 $self->SUPER::close_edit($p);
2941 $self->SUPER::abort_edit($self->{pool});
2942 $self->{pool}->clear;
2949 $svn_log hashref (as returned by svn_log_raw)
2951 fh => file handle of the log file,
2952 state => state of the log file parser (sep/msg/rev/msg_start...)
2955 $log_msg hashref as returned by next_log_entry($svn_log)
2957 msg => 'whitespace-formatted log entry
2958 ', # trailing newline is preserved
2959 revision => '8', # integer
2960 date => '2004-02-24T17:01:44.108345Z', # commit date
2961 author => 'committer name'
2965 @mods = array of diff-index line hashes, each element represents one line
2966 of diff-index output
2968 diff-index line ($m hash)
2970 mode_a => first column of diff-index output, no leading ':',
2971 mode_b => second column of diff-index output,
2972 sha1_b => sha1sum of the final blob,
2973 chg => change type [MCRADT],
2974 file_a => original file name of a file (iff chg is 'C' or 'R')
2975 file_b => new/current file name of a file (any chg)
2980 I don't trust the each() function on unless I created %hash myself
2981 because the internal iterator may not have started at base.