2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $SVN_URL $SVN_INFO $SVN_WC $SVN_UUID
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '1.1.1-broken';
14 $GIT_DIR = abs_path($ENV{GIT_DIR} || '.git');
15 $ENV{GIT_DIR} = $GIT_DIR;
17 my $LC_ALL = $ENV{LC_ALL};
19 # make sure the svn binary gives consistent output between locales and TZs:
23 # If SVN:: library support is added, please make the dependencies
24 # optional and preserve the capability to use the command-line client.
25 # use eval { require SVN::... } to make it lazy load
26 # We don't use any modules not in the standard Perl distribution:
29 use File::Basename qw/dirname basename/;
30 use File::Path qw/mkpath/;
31 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
33 use POSIX qw/strftime/;
36 memoize('revisions_eq');
38 my ($SVN_PATH, $SVN, $SVN_LOG, $_use_lib);
39 $_use_lib = 1 unless $ENV{GIT_SVN_NO_LIB};
41 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
42 my $sha1 = qr/[a-f\d]{40}/;
43 my $sha1_short = qr/[a-f\d]{4,40}/;
44 my ($_revision,$_stdin,$_no_ignore_ext,$_no_stop_copy,$_help,$_rmdir,$_edit,
45 $_find_copies_harder, $_l, $_cp_similarity, $_cp_remote,
46 $_repack, $_repack_nr, $_repack_flags,
47 $_template, $_shared, $_no_default_regex, $_no_graft_copy,
48 $_limit, $_verbose, $_incremental, $_oneline, $_l_fmt, $_show_commit,
49 $_version, $_upgrade, $_authors, $_branch_all_refs, @_opt_m);
50 my (@_branch_from, %tree_map, %users, %rusers, %equiv);
51 my ($_svn_co_url_revs, $_svn_pg_peg_revs);
52 my @repo_path_split_cache;
54 my %fc_opts = ( 'no-ignore-externals' => \$_no_ignore_ext,
55 'branch|b=s' => \@_branch_from,
56 'branch-all-refs|B' => \$_branch_all_refs,
57 'authors-file|A=s' => \$_authors,
58 'repack:i' => \$_repack,
59 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags);
61 my ($_trunk, $_tags, $_branches);
62 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
63 'tags|t=s' => \$_tags,
64 'branches|b=s' => \$_branches );
65 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
67 # yes, 'native' sets "\n". Patches to fix this for non-*nix systems welcome:
68 my %EOL = ( CR => "\015", LF => "\012", CRLF => "\015\012", native => "\012" );
71 fetch => [ \&fetch, "Download new revisions from SVN",
72 { 'revision|r=s' => \$_revision, %fc_opts } ],
73 init => [ \&init, "Initialize a repo for tracking" .
74 " (requires URL argument)",
76 commit => [ \&commit, "Commit git revisions to SVN",
77 { 'stdin|' => \$_stdin,
80 'find-copies-harder' => \$_find_copies_harder,
82 'copy-similarity|C=i'=> \$_cp_similarity,
85 'show-ignore' => [ \&show_ignore, "Show svn:ignore listings",
86 { 'revision|r=i' => \$_revision } ],
87 rebuild => [ \&rebuild, "Rebuild git-svn metadata (after git clone)",
88 { 'no-ignore-externals' => \$_no_ignore_ext,
89 'copy-remote|remote=s' => \$_cp_remote,
90 'upgrade' => \$_upgrade } ],
91 'graft-branches' => [ \&graft_branches,
92 'Detect merges/branches from already imported history',
93 { 'merge-rx|m' => \@_opt_m,
94 'no-default-regex' => \$_no_default_regex,
95 'no-graft-copy' => \$_no_graft_copy } ],
96 'multi-init' => [ \&multi_init,
97 'Initialize multiple trees (like git-svnimport)',
98 { %multi_opts, %fc_opts } ],
99 'multi-fetch' => [ \&multi_fetch,
100 'Fetch multiple trees (like git-svnimport)',
102 'log' => [ \&show_log, 'Show commit logs',
103 { 'limit=i' => \$_limit,
104 'revision|r=s' => \$_revision,
105 'verbose|v' => \$_verbose,
106 'incremental' => \$_incremental,
107 'oneline' => \$_oneline,
108 'show-commit' => \$_show_commit,
109 'authors-file|A=s' => \$_authors,
114 for (my $i = 0; $i < @ARGV; $i++) {
115 if (defined $cmd{$ARGV[$i]}) {
122 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
124 read_repo_config(\%opts);
125 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
126 'version|V' => \$_version,
127 'id|i=s' => \$GIT_SVN);
128 exit 1 if (!$rv && $cmd ne 'log');
132 version() if $_version;
133 usage(1) unless defined $cmd;
135 load_authors() if $_authors;
136 load_all_refs() if $_branch_all_refs;
138 migration_check() unless $cmd =~ /^(?:init|rebuild|multi-init)$/;
139 $cmd{$cmd}->[0]->(@ARGV);
142 ####################### primary functions ######################
144 my $exit = shift || 0;
145 my $fd = $exit ? \*STDERR : \*STDOUT;
147 git-svn - bidirectional operations between a single Subversion tree and git
148 Usage: $0 <command> [options] [arguments]\n
150 print $fd "Available commands:\n" unless $cmd;
152 foreach (sort keys %cmd) {
153 next if $cmd && $cmd ne $_;
154 print $fd ' ',pack('A13',$_),$cmd{$_}->[1],"\n";
155 foreach (keys %{$cmd{$_}->[2]}) {
156 # prints out arguments as they should be passed:
157 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
158 print $fd ' ' x 17, join(', ', map { length $_ > 1 ?
160 split /\|/,$_)," $x\n";
164 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
165 arbitrary identifier if you're tracking multiple SVN branches/repositories in
166 one git repository and want to keep them separate. See git-svn(1) for more
173 print "git-svn version $VERSION\n";
178 if (quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0")) {
181 $SVN_URL = shift or undef;
184 sys('git-update-ref',"refs/remotes/$GIT_SVN","$GIT_SVN-HEAD");
186 check_upgrade_needed();
189 my $pid = open(my $rev_list,'-|');
190 defined $pid or croak $!;
192 exec("git-rev-list","refs/remotes/$GIT_SVN") or croak $!;
195 while (<$rev_list>) {
198 croak "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
199 my @commit = grep(/^git-svn-id: /,`git-cat-file commit $c`);
200 next if (!@commit); # skip merges
201 my ($url, $rev, $uuid) = extract_metadata($commit[$#commit]);
202 if (!$rev || !$uuid) {
203 croak "Unable to extract revision or UUID from ",
204 "$c, $commit[$#commit]\n";
207 # if we merged or otherwise started elsewhere, this is
208 # how we break out of it
209 next if (defined $SVN_UUID && ($uuid ne $SVN_UUID));
210 next if (defined $SVN_URL && defined $url && ($url ne $SVN_URL));
212 unless (defined $latest) {
213 if (!$SVN_URL && !$url) {
214 croak "SVN repository location required: $url\n";
221 revdb_set($REVDB, $rev, $c);
222 print "r$rev = $c\n";
223 $newest_rev = $rev if ($rev > $newest_rev);
225 close $rev_list or croak $?;
227 goto out if $_use_lib;
228 if (!chdir $SVN_WC) {
229 svn_cmd_checkout($SVN_URL, $latest, $SVN_WC);
230 chdir $SVN_WC or croak $!;
234 defined $pid or croak $!;
236 my @svn_up = qw(svn up);
237 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
238 sys(@svn_up,"-r$newest_rev");
239 $ENV{GIT_INDEX_FILE} = $GIT_SVN_INDEX;
241 exec('git-write-tree') or croak $!;
248 Keeping deprecated refs/head/$GIT_SVN-HEAD for now. Please remove it
249 when you have upgraded your tools and habits to use refs/remotes/$GIT_SVN
255 $SVN_URL = shift or die "SVN repository location required " .
256 "as a command-line argument\n";
257 $SVN_URL =~ s!/+$!!; # strip trailing slash
258 unless (-d $GIT_DIR) {
259 my @init_db = ('git-init-db');
260 push @init_db, "--template=$_template" if defined $_template;
261 push @init_db, "--shared" if defined $_shared;
268 check_upgrade_needed();
269 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
270 my $ret = $_use_lib ? fetch_lib(@_) : fetch_cmd(@_);
271 if ($ret->{commit} && quiet_run(qw(git-rev-parse --verify
272 refs/heads/master^0))) {
273 sys(qw(git-update-ref refs/heads/master),$ret->{commit});
280 my @log_args = -d $SVN_WC ? ($SVN_WC) : ($SVN_URL);
281 unless ($_revision) {
282 $_revision = -d $SVN_WC ? 'BASE:HEAD' : '0:HEAD';
284 push @log_args, "-r$_revision";
285 push @log_args, '--stop-on-copy' unless $_no_stop_copy;
287 my $svn_log = svn_log_raw(@log_args);
289 my $base = next_log_entry($svn_log) or croak "No base revision!\n";
290 # don't need last_revision from grab_base_rev() because
291 # user could've specified a different revision to skip (they
292 # didn't want to import certain revisions into git for whatever
293 # reason, so trust $base->{revision} instead.
294 my (undef, $last_commit) = svn_grab_base_rev();
295 unless (-d $SVN_WC) {
296 svn_cmd_checkout($SVN_URL,$base->{revision},$SVN_WC);
297 chdir $SVN_WC or croak $!;
299 $last_commit = git_commit($base, @parents);
300 assert_tree($last_commit);
302 chdir $SVN_WC or croak $!;
304 # looks like a user manually cp'd and svn switch'ed
305 unless ($last_commit) {
306 sys(qw/svn revert -R ./);
307 assert_svn_wc_clean($base->{revision});
308 $last_commit = git_commit($base, @parents);
309 assert_tree($last_commit);
312 my @svn_up = qw(svn up);
313 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
315 while (my $log_msg = next_log_entry($svn_log)) {
316 if ($last->{revision} >= $log_msg->{revision}) {
317 croak "Out of order: last >= current: ",
318 "$last->{revision} >= $log_msg->{revision}\n";
320 # Revert is needed for cases like:
321 # https://svn.musicpd.org/Jamming/trunk (r166:167), but
322 # I can't seem to reproduce something like that on a test...
323 sys(qw/svn revert -R ./);
324 assert_svn_wc_clean($last->{revision});
325 sys(@svn_up,"-r$log_msg->{revision}");
326 $last_commit = git_commit($log_msg, $last_commit, @parents);
329 close $svn_log->{fh};
330 $last->{commit} = $last_commit;
336 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
338 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
339 $SVN_LOG ||= libsvn_connect($repo);
340 $SVN ||= libsvn_connect($repo);
341 my ($last_rev, $last_commit) = svn_grab_base_rev();
342 my ($base, $head) = libsvn_parse_revision($last_rev);
344 return { revision => $last_rev, commit => $last_commit }
346 my $index = set_index($GIT_SVN_INDEX);
348 # limit ourselves and also fork() since get_log won't release memory
349 # after processing a revision and SVN stuff seems to leak
351 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
353 if (defined $last_commit) {
354 unless (-e $GIT_SVN_INDEX) {
355 sys(qw/git-read-tree/, $last_commit);
357 chomp (my $x = `git-write-tree`);
358 my ($y) = (`git-cat-file commit $last_commit`
359 =~ /^tree ($sha1)/m);
361 unlink $GIT_SVN_INDEX or croak $!;
362 sys(qw/git-read-tree/, $last_commit);
364 chomp ($x = `git-write-tree`);
366 print STDERR "trees ($last_commit) $y != $x\n",
367 "Something is seriously wrong...\n";
371 # fork, because using SVN::Pool with get_log() still doesn't
372 # seem to help enough to keep memory usage down.
373 defined(my $pid = fork) or croak $!;
375 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
377 # Yes I'm perfectly aware that the fourth argument
378 # below is the limit revisions number. Unfortunately
379 # performance sucks with it enabled, so it's much
380 # faster to fetch revision ranges instead of relying
382 $SVN_LOG->get_log( '/'.$SVN_PATH, $min, $max, 0, 1, 1,
386 $log_msg = libsvn_fetch(
388 $last_commit = git_commit(
393 $log_msg = libsvn_new_tree(@_);
394 $last_commit = git_commit(
402 ($last_rev, $last_commit) = svn_grab_base_rev();
403 last if ($max >= $head);
406 $max = $head if ($max > $head);
408 restore_index($index);
409 return { revision => $last_rev, commit => $last_commit };
414 check_upgrade_needed();
415 if ($_stdin || !@commits) {
416 print "Reading from stdin...\n";
419 if (/\b($sha1_short)\b/o) {
420 unshift @commits, $1;
425 foreach my $c (@commits) {
426 chomp(my @tmp = safe_qx('git-rev-parse',$c));
427 if (scalar @tmp == 1) {
429 } elsif (scalar @tmp > 1) {
430 push @revs, reverse (safe_qx('git-rev-list',@tmp));
432 die "Failed to rev-parse $c\n";
436 $_use_lib ? commit_lib(@revs) : commit_cmd(@revs);
437 print "Done committing ",scalar @revs," revisions to SVN\n";
443 chdir $SVN_WC or croak "Unable to chdir $SVN_WC: $!\n";
444 my $info = svn_info('.');
445 my $fetched = fetch();
446 if ($info->{Revision} != $fetched->{revision}) {
447 print STDERR "There are new revisions that were fetched ",
448 "and need to be merged (or acknowledged) ",
449 "before committing.\n";
452 $info = svn_info('.');
455 foreach my $c (@revs) {
456 my $mods = svn_checkout_tree($last, $c);
457 if (scalar @$mods == 0) {
458 print "Skipping, no changes detected\n";
461 $last = svn_commit_tree($last, $c);
467 my ($r_last, $cmt_last) = svn_grab_base_rev();
468 defined $r_last or die "Must have an existing revision to commit\n";
469 my $fetched = fetch();
470 if ($r_last != $fetched->{revision}) {
471 print STDERR "There are new revisions that were fetched ",
472 "and need to be merged (or acknowledged) ",
473 "before committing.\n",
474 "last rev: $r_last\n",
475 " current: $fetched->{revision}\n";
479 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
480 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
482 foreach my $c (@revs) {
483 # fork for each commit because there's a memory leak I
484 # can't track down... (it's probably in the SVN code)
485 defined(my $pid = open my $fh, '-|') or croak $!;
487 if (defined $LC_ALL) {
488 $ENV{LC_ALL} = $LC_ALL;
492 my $log_msg = get_commit_message($c, $commit_msg);
493 my $ed = SVN::Git::Editor->new(
497 svn_path => $SVN_PATH
499 $SVN->get_commit_editor(
510 my $mods = libsvn_checkout_tree($cmt_last, $c, $ed);
512 print "No changes\nr$r_last = $cmt_last\n";
519 my ($r_new, $cmt_new, $no);
523 if (/^r(\d+) = ($sha1)$/o) {
524 ($r_new, $cmt_new) = ($1, $2);
525 } elsif ($_ eq 'No changes') {
529 close $fh or croak $?;
530 if (! defined $r_new && ! defined $cmt_new) {
532 die "Failed to parse revision information\n";
535 ($r_last, $cmt_last) = ($r_new, $cmt_new);
542 $SVN_URL ||= file_to_s("$GIT_SVN_DIR/info/url");
543 $_use_lib ? show_ignore_lib() : show_ignore_cmd();
546 sub show_ignore_cmd {
547 require File::Find or die $!;
548 if (defined $_revision) {
549 die "-r/--revision option doesn't work unless the Perl SVN ",
550 "libraries are used\n";
552 chdir $SVN_WC or croak $!;
554 File::Find::find({wanted=>sub{if(lstat $_ && -d _ && -d "$_/.svn"){
556 @{$ign{$_}} = svn_propget_base('svn:ignore', $_);
557 }}, no_chdir=>1},'.');
560 foreach (@{$ign{'.'}}) { print '/',$_ if /\S/ }
562 foreach my $i (sort keys %ign) {
563 print "\n# ",$i,"\n";
564 foreach (@{$ign{$i}}) { print '/',$i,'/',$_ if /\S/ }
568 sub show_ignore_lib {
570 ($repo, $SVN_PATH) = repo_path_split($SVN_URL);
571 $SVN ||= libsvn_connect($repo);
572 my $r = defined $_revision ? $_revision : $SVN->get_latest_revnum;
573 libsvn_traverse_ignore(\*STDOUT, $SVN_PATH, $r);
577 my $gr_file = "$GIT_DIR/info/grafts";
578 my ($grafts, $comments) = read_grafts($gr_file);
582 # temporarily disable our grafts file to make this idempotent
583 chomp($gr_sha1 = safe_qx(qw/git-hash-object -w/,$gr_file));
584 rename $gr_file, "$gr_file~$gr_sha1" or croak $!;
587 my $l_map = read_url_paths();
588 my @re = map { qr/$_/is } @_opt_m if @_opt_m;
589 unless ($_no_default_regex) {
590 push @re, ( qr/\b(?:merge|merging|merged)\s+(\S.+)/is,
591 qr/\b(?:from|of)\s+(\S.+)/is );
593 foreach my $u (keys %$l_map) {
595 foreach my $p (keys %{$l_map->{$u}}) {
596 graft_merge_msg($grafts,$l_map,$u,$p);
599 unless ($_no_graft_copy) {
601 graft_file_copy_lib($grafts,$l_map,$u);
603 graft_file_copy_cmd($grafts,$l_map,$u);
608 write_grafts($grafts, $comments, $gr_file);
609 unlink "$gr_file~$gr_sha1" if $gr_sha1;
616 $url =~ s#/+$## if $url;
617 if ($_trunk !~ m#^[a-z\+]+://#) {
618 $_trunk = '/' . $_trunk if ($_trunk !~ m#^/#);
620 print STDERR "E: '$_trunk' is not a complete URL ",
621 "and a separate URL is not specified\n";
624 $_trunk = $url . $_trunk;
626 if ($GIT_SVN eq 'git-svn') {
627 print "GIT_SVN_ID set to 'trunk' for $_trunk\n";
628 $GIT_SVN = $ENV{GIT_SVN_ID} = 'trunk';
632 complete_url_ls_init($url, $_branches, '--branches/-b', '');
633 complete_url_ls_init($url, $_tags, '--tags/-t', 'tags/');
637 # try to do trunk first, since branches/tags
638 # may be descended from it.
639 if (-e "$GIT_DIR/svn/trunk/info/url") {
640 fetch_child_id('trunk', @_);
642 rec_fetch('', "$GIT_DIR/svn", @_);
648 my $r_last = -1; # prevent dupes
649 rload_authors() if $_authors;
655 if (defined $_revision) {
656 if ($_revision =~ /^(\d+):(\d+)$/) {
657 ($r_min, $r_max) = ($1, $2);
658 } elsif ($_revision =~ /^\d+$/) {
659 $r_min = $r_max = $_revision;
661 print STDERR "-r$_revision is not supported, use ",
662 "standard \'git log\' arguments instead\n";
667 my $pid = open(my $log,'-|');
668 defined $pid or croak $!;
670 exec(git_svn_log_cmd($r_min,$r_max), @args) or croak $!;
676 if (/^commit ($sha1_short)/o) {
678 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
680 process_commit($c, $r_min, $r_max, \@k) or
685 } elsif (/^author (.+) (\d+) ([\-\+]?\d+)$/) {
686 get_author_info($c, $1, $2, $3);
687 } elsif (/^(?:tree|parent|committer) /) {
689 } elsif (/^:\d{6} \d{6} $sha1_short/o) {
690 push @{$c->{raw}}, $_;
693 push @{$c->{diff}}, $_;
695 push @{$c->{diff}}, $_;
696 } elsif (/^ (git-svn-id:.+)$/) {
697 (undef, $c->{r}, undef) = extract_metadata($1);
702 if ($c && defined $c->{r} && $c->{r} != $r_last) {
704 process_commit($c, $r_min, $r_max, \@k);
710 process_commit($_, $r_min, $r_max) foreach reverse @k;
714 print '-' x72,"\n" unless $_incremental || $_oneline;
717 ########################### utility functions #########################
721 return 1 if defined $c->{r};
722 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
723 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
724 my @msg = safe_qx(qw/git-cat-file commit/, $c->{c});
725 shift @msg while ($msg[0] ne "\n");
727 @{$c->{l}} = grep !/^git-svn-id: /, @msg;
729 (undef, $c->{r}, undef) = extract_metadata(
730 (grep(/^git-svn-id: /, @msg))[-1]);
732 return defined $c->{r};
735 sub git_svn_log_cmd {
736 my ($r_min, $r_max) = @_;
737 my @cmd = (qw/git-log --abbrev-commit --pretty=raw
738 --default/, "refs/remotes/$GIT_SVN");
739 push @cmd, '--summary' if $_verbose;
740 return @cmd unless defined $r_max;
741 if ($r_max == $r_min) {
742 push @cmd, '--max-count=1';
743 if (my $c = revdb_get($REVDB, $r_max)) {
748 $c_max = revdb_get($REVDB, $r_max);
749 $c_min = revdb_get($REVDB, $r_min);
750 if ($c_min && $c_max) {
751 if ($r_max > $r_max) {
752 push @cmd, "$c_min..$c_max";
754 push @cmd, "$c_max..$c_min";
756 } elsif ($r_max > $r_min) {
767 print "Fetching $id\n";
768 my $ref = "$GIT_DIR/refs/remotes/$id";
769 my $ca = file_to_s($ref) if (-r $ref);
770 defined(my $pid = fork) or croak $!;
772 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
779 return unless $_repack || -r $ref;
781 my $cb = file_to_s($ref);
783 defined($pid = open my $fh, '-|') or croak $!;
784 my $url = file_to_s("$GIT_DIR/svn/$id/info/url");
787 exec qw/git-rev-list --pretty=raw/,
788 $ca ? "$ca..$cb" : $cb or croak $!;
791 if (/^ git-svn-id: $url\@\d+ [a-f0-9\-]+$/) {
793 } elsif (/^ git-svn-id: \S+\@\d+ [a-f0-9\-]+$/) {
801 my ($pfx, $p, @args) = @_;
803 foreach (sort <$p/*>) {
804 if (-r "$_/info/url") {
805 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
806 my $id = $pfx . basename $_;
807 next if $id eq 'trunk';
808 fetch_child_id($id, @args);
815 $x =~ s!^\Q$GIT_DIR\E/svn/!!;
820 sub complete_url_ls_init {
821 my ($url, $var, $switch, $pfx) = @_;
823 print STDERR "W: $switch not specified\n";
827 if ($var !~ m#^[a-z\+]+://#) {
828 $var = '/' . $var if ($var !~ m#^/#);
830 print STDERR "E: '$var' is not a complete URL ",
831 "and a separate URL is not specified\n";
836 chomp(my @ls = $_use_lib ? libsvn_ls_fullurl($var)
837 : safe_qx(qw/svn ls --non-interactive/, $var));
839 defined(my $pid = fork) or croak $!;
841 foreach my $u (map { "$var/$_" } (grep m!/$!, @ls)) {
843 if ($u !~ m!\Q$var\E/(.+)$!) {
844 print STDERR "W: Unrecognized URL: $u\n";
845 die "This should never happen\n";
848 print "init $u => $id\n";
849 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
863 my @tmp = split m#/#, $_;
865 while (my $x = shift @tmp) {
871 foreach (sort {length $b <=> length $a} keys %common) {
872 if ($common{$_} == @$paths) {
879 # this isn't funky-filename safe, but good enough for now...
880 sub graft_file_copy_cmd {
881 my ($grafts, $l_map, $u) = @_;
882 my $paths = $l_map->{$u};
883 my $pfx = common_prefix([keys %$paths]);
884 $SVN_URL ||= $u.$pfx;
885 my $pid = open my $fh, '-|';
886 defined $pid or croak $!;
888 my @exec = qw/svn log -v/;
889 push @exec, "-r$_revision" if defined $_revision;
890 exec @exec, $u.$pfx or croak $!;
892 my ($r, $mp) = (undef, undef);
897 } elsif (/^r(\d+) \| /) {
898 $r = $1 unless defined $r;
899 } elsif (/^Changed paths:/) {
901 } elsif ($mp && m#^ [AR] /(\S.*?) \(from /(\S+?):(\d+)\)$#) {
902 my ($p1, $p0, $r0) = ($1, $2, $3);
903 my $c = find_graft_path_commit($paths, $p1, $r);
905 find_graft_path_parents($grafts, $paths, $c, $p0, $r0);
910 sub graft_file_copy_lib {
911 my ($grafts, $l_map, $u) = @_;
912 my $tree_paths = $l_map->{$u};
913 my $pfx = common_prefix([keys %$tree_paths]);
914 my ($repo, $path) = repo_path_split($u.$pfx);
915 $SVN_LOG ||= libsvn_connect($repo);
916 $SVN ||= libsvn_connect($repo);
918 my ($base, $head) = libsvn_parse_revision();
920 my ($min, $max) = ($base, $head < $base+$inc ? $head : $base+$inc);
921 my $eh = $SVN::Error::handler;
922 $SVN::Error::handler = \&libsvn_skip_unknown_revs;
924 my $pool = SVN::Pool->new;
925 $SVN_LOG->get_log( "/$path", $min, $max, 0, 1, 1,
927 libsvn_graft_file_copies($grafts, $tree_paths,
931 last if ($max >= $head);
934 $max = $head if ($max > $head);
936 $SVN::Error::handler = $eh;
939 sub process_merge_msg_matches {
940 my ($grafts, $l_map, $u, $p, $c, @matches) = @_;
943 # merging with ourselves is not interesting
945 if ($l_map->{$u}->{$_}) {
951 foreach my $w (@weak) {
953 # no exact match, use branch name as regexp.
954 my $re = qr/\Q$w\E/i;
955 foreach (keys %{$l_map->{$u}}) {
964 foreach (keys %{$l_map->{$u}}) {
971 my ($rev) = ($c->{m} =~ /^git-svn-id:\s(?:\S+?)\@(\d+)
972 \s(?:[a-f\d\-]+)$/xsm);
973 unless (defined $rev) {
974 ($rev) = ($c->{m} =~/^git-svn-id:\s(\d+)
975 \@(?:[a-f\d\-]+)/xsm);
976 return unless defined $rev;
978 foreach my $m (@strong) {
979 my ($r0, $s0) = find_rev_before($rev, $m);
980 $grafts->{$c->{c}}->{$s0} = 1 if defined $s0;
984 sub graft_merge_msg {
985 my ($grafts, $l_map, $u, $p, @re) = @_;
987 my $x = $l_map->{$u}->{$p};
988 my $rl = rev_list_raw($x);
989 while (my $c = next_rev_list_entry($rl)) {
990 foreach my $re (@re) {
991 my (@br) = ($c->{m} =~ /$re/g);
993 process_merge_msg_matches($grafts,$l_map,$u,$p,$c,@br);
1001 my $pool = SVN::Pool->new;
1002 $SVN_UUID = $SVN->get_uuid($pool);
1005 my $info = shift || svn_info('.');
1006 $SVN_UUID = $info->{'Repository UUID'} or
1007 croak "Repository UUID unreadable\n";
1013 defined $pid or croak $!;
1015 open my $null, '>', '/dev/null' or croak $!;
1016 open STDERR, '>&', $null or croak $!;
1017 open STDOUT, '>&', $null or croak $!;
1018 exec @_ or croak $!;
1024 sub repo_path_split {
1025 my $full_url = shift;
1026 $full_url =~ s#/+$##;
1028 foreach (@repo_path_split_cache) {
1029 if ($full_url =~ s#$_##) {
1031 $full_url =~ s#^/+##;
1032 return ($u, $full_url);
1036 my ($url, $path) = ($full_url =~ m!^([a-z\+]+://[^/]*)(.*)$!i);
1038 my @paths = split(m#/+#, $path);
1042 $SVN = libsvn_connect($url);
1043 last if (defined $SVN &&
1044 defined eval { $SVN->get_latest_revnum });
1045 my $n = shift @paths || last;
1049 while (quiet_run(qw/svn ls --non-interactive/, $url)) {
1050 my $n = shift @paths || last;
1054 push @repo_path_split_cache, qr/^(\Q$url\E)/;
1055 $path = join('/',@paths);
1056 return ($url, $path);
1060 defined $SVN_URL or croak "SVN repository location required\n";
1061 unless (-d $GIT_DIR) {
1062 croak "GIT_DIR=$GIT_DIR does not exist!\n";
1064 mkpath([$GIT_SVN_DIR]);
1065 mkpath(["$GIT_SVN_DIR/info"]);
1066 open my $fh, '>>',$REVDB or croak $!;
1068 s_to_file($SVN_URL,"$GIT_SVN_DIR/info/url");
1072 sub assert_svn_wc_clean {
1073 return if $_use_lib;
1075 croak "$svn_rev is not an integer!\n" unless ($svn_rev =~ /^\d+$/);
1076 my $lcr = svn_info('.')->{'Last Changed Rev'};
1077 if ($svn_rev != $lcr) {
1078 print STDERR "Checking for copy-tree ... ";
1079 my @diff = grep(/^Index: /,(safe_qx(qw(svn diff),
1080 "-r$lcr:$svn_rev")));
1082 croak "Nope! Expected r$svn_rev, got r$lcr\n";
1084 print STDERR "OK!\n";
1087 my @status = grep(!/^Performing status on external/,(`svn status`));
1088 @status = grep(!/^\s*$/,@status);
1089 if (scalar @status) {
1090 print STDERR "Tree ($SVN_WC) is not clean:\n";
1091 print STDERR $_ foreach @status;
1096 sub get_tree_from_treeish {
1098 croak "Not a sha1: $treeish\n" unless $treeish =~ /^$sha1$/o;
1099 chomp(my $type = `git-cat-file -t $treeish`);
1101 while ($type eq 'tag') {
1102 chomp(($treeish, $type) = `git-cat-file tag $treeish`);
1104 if ($type eq 'commit') {
1105 $expected = (grep /^tree /,`git-cat-file commit $treeish`)[0];
1106 ($expected) = ($expected =~ /^tree ($sha1)$/);
1107 die "Unable to get tree from $treeish\n" unless $expected;
1108 } elsif ($type eq 'tree') {
1109 $expected = $treeish;
1111 die "$treeish is a $type, expected tree, tag or commit\n";
1117 return if $_use_lib;
1119 my $expected = get_tree_from_treeish($treeish);
1121 my $tmpindex = $GIT_SVN_INDEX.'.assert-tmp';
1123 unlink $tmpindex or croak $!;
1125 my $old_index = set_index($tmpindex);
1127 chomp(my $tree = `git-write-tree`);
1128 restore_index($old_index);
1129 if ($tree ne $expected) {
1130 croak "Tree mismatch, Got: $tree, Expected: $expected\n";
1135 sub parse_diff_tree {
1136 my $diff_fh = shift;
1140 while (<$diff_fh>) {
1141 chomp $_; # this gets rid of the trailing "\0"
1142 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1143 $sha1\s($sha1)\s([MTCRAD])\d*$/xo) {
1144 push @mods, { mode_a => $1, mode_b => $2,
1145 sha1_b => $3, chg => $4 };
1146 if ($4 =~ /^(?:C|R)$/) {
1151 } elsif ($state eq 'file_a') {
1152 my $x = $mods[$#mods] or croak "Empty array\n";
1153 if ($x->{chg} !~ /^(?:C|R)$/) {
1154 croak "Error parsing $_, $x->{chg}\n";
1158 } elsif ($state eq 'file_b') {
1159 my $x = $mods[$#mods] or croak "Empty array\n";
1160 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1161 croak "Error parsing $_, $x->{chg}\n";
1163 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1164 croak "Error parsing $_, $x->{chg}\n";
1169 croak "Error parsing $_\n";
1172 close $diff_fh or croak $?;
1177 sub svn_check_prop_executable {
1179 return if -l $m->{file_b};
1180 if ($m->{mode_b} =~ /755$/) {
1181 chmod((0755 &~ umask),$m->{file_b}) or croak $!;
1182 if ($m->{mode_a} !~ /755$/) {
1183 sys(qw(svn propset svn:executable 1), $m->{file_b});
1185 -x $m->{file_b} or croak "$m->{file_b} is not executable!\n";
1186 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1187 sys(qw(svn propdel svn:executable), $m->{file_b});
1188 chmod((0644 &~ umask),$m->{file_b}) or croak $!;
1189 -x $m->{file_b} and croak "$m->{file_b} is executable!\n";
1193 sub svn_ensure_parent_path {
1194 my $dir_b = dirname(shift);
1195 svn_ensure_parent_path($dir_b) if ($dir_b ne File::Spec->curdir);
1196 mkpath([$dir_b]) unless (-d $dir_b);
1197 sys(qw(svn add -N), $dir_b) unless (-d "$dir_b/.svn");
1200 sub precommit_check {
1202 my (%rm_file, %rmdir_check, %added_check);
1204 my %o = ( D => 0, R => 1, C => 2, A => 3, M => 3, T => 3 );
1205 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1206 if ($m->{chg} eq 'R') {
1207 if (-d $m->{file_b}) {
1208 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1210 # dir/$file => dir/file/$file
1211 my $dirname = dirname($m->{file_b});
1212 while ($dirname ne File::Spec->curdir) {
1213 if ($dirname ne $m->{file_a}) {
1214 $dirname = dirname($dirname);
1217 err_file_to_dir("$m->{file_a} => $m->{file_b}");
1219 # baz/zzz => baz (baz is a file)
1220 $dirname = dirname($m->{file_a});
1221 while ($dirname ne File::Spec->curdir) {
1222 if ($dirname ne $m->{file_b}) {
1223 $dirname = dirname($dirname);
1226 err_dir_to_file("$m->{file_a} => $m->{file_b}");
1229 if ($m->{chg} =~ /^(D|R)$/) {
1230 my $t = $1 eq 'D' ? 'file_b' : 'file_a';
1231 $rm_file{ $m->{$t} } = 1;
1232 my $dirname = dirname( $m->{$t} );
1233 my $basename = basename( $m->{$t} );
1234 $rmdir_check{$dirname}->{$basename} = 1;
1235 } elsif ($m->{chg} =~ /^(?:A|C)$/) {
1236 if (-d $m->{file_b}) {
1237 err_dir_to_file($m->{file_b});
1239 my $dirname = dirname( $m->{file_b} );
1240 my $basename = basename( $m->{file_b} );
1241 $added_check{$dirname}->{$basename} = 1;
1242 while ($dirname ne File::Spec->curdir) {
1243 if ($rm_file{$dirname}) {
1244 err_file_to_dir($m->{file_b});
1246 $dirname = dirname $dirname;
1250 return (\%rmdir_check, \%added_check);
1252 sub err_dir_to_file {
1254 print STDERR "Node change from directory to file ",
1255 "is not supported by Subversion: ",$file,"\n";
1258 sub err_file_to_dir {
1260 print STDERR "Node change from file to directory ",
1261 "is not supported by Subversion: ",$file,"\n";
1268 my ($from, $treeish) = @_;
1270 print "diff-tree $from $treeish\n";
1271 my $pid = open my $diff_fh, '-|';
1272 defined $pid or croak $!;
1274 my @diff_tree = qw(git-diff-tree -z -r);
1275 if ($_cp_similarity) {
1276 push @diff_tree, "-C$_cp_similarity";
1278 push @diff_tree, '-C';
1280 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1281 push @diff_tree, "-l$_l" if defined $_l;
1282 exec(@diff_tree, $from, $treeish) or croak $!;
1284 return parse_diff_tree($diff_fh);
1287 sub svn_checkout_tree {
1288 my ($from, $treeish) = @_;
1289 my $mods = get_diff($from->{commit}, $treeish);
1290 return $mods unless (scalar @$mods);
1291 my ($rm, $add) = precommit_check($mods);
1293 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1294 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1295 if ($m->{chg} eq 'C') {
1296 svn_ensure_parent_path( $m->{file_b} );
1297 sys(qw(svn cp), $m->{file_a}, $m->{file_b});
1298 apply_mod_line_blob($m);
1299 svn_check_prop_executable($m);
1300 } elsif ($m->{chg} eq 'D') {
1301 sys(qw(svn rm --force), $m->{file_b});
1302 } elsif ($m->{chg} eq 'R') {
1303 svn_ensure_parent_path( $m->{file_b} );
1304 sys(qw(svn mv --force), $m->{file_a}, $m->{file_b});
1305 apply_mod_line_blob($m);
1306 svn_check_prop_executable($m);
1307 } elsif ($m->{chg} eq 'M') {
1308 apply_mod_line_blob($m);
1309 svn_check_prop_executable($m);
1310 } elsif ($m->{chg} eq 'T') {
1311 sys(qw(svn rm --force),$m->{file_b});
1312 apply_mod_line_blob($m);
1313 sys(qw(svn add), $m->{file_b});
1314 svn_check_prop_executable($m);
1315 } elsif ($m->{chg} eq 'A') {
1316 svn_ensure_parent_path( $m->{file_b} );
1317 apply_mod_line_blob($m);
1318 sys(qw(svn add), $m->{file_b});
1319 svn_check_prop_executable($m);
1321 croak "Invalid chg: $m->{chg}\n";
1325 assert_tree($treeish);
1326 if ($_rmdir) { # remove empty directories
1327 handle_rmdir($rm, $add);
1329 assert_tree($treeish);
1333 sub libsvn_checkout_tree {
1334 my ($from, $treeish, $ed) = @_;
1335 my $mods = get_diff($from, $treeish);
1336 return $mods unless (scalar @$mods);
1337 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
1338 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
1340 if (defined $o{$f}) {
1343 croak "Invalid change type: $f\n";
1346 $ed->rmdirs if $_rmdir;
1350 # svn ls doesn't work with respect to the current working tree, but what's
1351 # in the repository. There's not even an option for it... *sigh*
1352 # (added files don't show up and removed files remain in the ls listing)
1353 sub svn_ls_current {
1354 my ($dir, $rm, $add) = @_;
1355 chomp(my @ls = safe_qx('svn','ls',$dir));
1358 s#/$##; # trailing slashes are evil
1359 push @ret, $_ unless $rm->{$dir}->{$_};
1361 if (exists $add->{$dir}) {
1362 push @ret, keys %{$add->{$dir}};
1368 my ($rm, $add) = @_;
1370 foreach my $dir (sort {length $b <=> length $a} keys %$rm) {
1371 my $ls = svn_ls_current($dir, $rm, $add);
1372 next if (scalar @$ls);
1373 sys(qw(svn rm --force),$dir);
1375 my $dn = dirname $dir;
1376 $rm->{ $dn }->{ basename $dir } = 1;
1377 $ls = svn_ls_current($dn, $rm, $add);
1378 while (scalar @$ls == 0 && $dn ne File::Spec->curdir) {
1379 sys(qw(svn rm --force),$dn);
1380 $dir = basename $dn;
1382 $rm->{ $dn }->{ $dir } = 1;
1383 $ls = svn_ls_current($dn, $rm, $add);
1388 sub get_commit_message {
1389 my ($commit, $commit_msg) = (@_);
1390 my %log_msg = ( msg => '' );
1391 open my $msg, '>', $commit_msg or croak $!;
1393 print "commit: $commit\n";
1394 chomp(my $type = `git-cat-file -t $commit`);
1395 if ($type eq 'commit') {
1396 my $pid = open my $msg_fh, '-|';
1397 defined $pid or croak $!;
1400 exec(qw(git-cat-file commit), $commit) or croak $!;
1405 $in_msg = 1 if (/^\s*$/);
1406 } elsif (/^git-svn-id: /) {
1407 # skip this, we regenerate the correct one
1408 # on re-fetch anyways
1410 print $msg $_ or croak $!;
1413 close $msg_fh or croak $?;
1415 close $msg or croak $!;
1417 if ($_edit || ($type eq 'tree')) {
1418 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1419 system($editor, $commit_msg);
1422 # file_to_s removes all trailing newlines, so just use chomp() here:
1423 open $msg, '<', $commit_msg or croak $!;
1424 { local $/; chomp($log_msg{msg} = <$msg>); }
1425 close $msg or croak $!;
1430 sub svn_commit_tree {
1431 my ($last, $commit) = @_;
1432 my $commit_msg = "$GIT_SVN_DIR/.svn-commit.tmp.$$";
1433 my $log_msg = get_commit_message($commit, $commit_msg);
1434 my ($oneline) = ($log_msg->{msg} =~ /([^\n\r]+)/);
1435 print "Committing $commit: $oneline\n";
1437 if (defined $LC_ALL) {
1438 $ENV{LC_ALL} = $LC_ALL;
1440 delete $ENV{LC_ALL};
1442 my @ci_output = safe_qx(qw(svn commit -F),$commit_msg);
1445 my ($committed) = ($ci_output[$#ci_output] =~ /(\d+)/);
1446 if (!defined $committed) {
1447 my $out = join("\n",@ci_output);
1448 print STDERR "W: Trouble parsing \`svn commit' output:\n\n",
1449 $out, "\n\nAssuming English locale...";
1450 ($committed) = ($out =~ /^Committed revision \d+\./sm);
1451 defined $committed or die " FAILED!\n",
1452 "Commit output failed to parse committed revision!\n",
1453 print STDERR " OK\n";
1456 my @svn_up = qw(svn up);
1457 push @svn_up, '--ignore-externals' unless $_no_ignore_ext;
1458 if ($_optimize_commits && ($committed == ($last->{revision} + 1))) {
1459 push @svn_up, "-r$committed";
1461 my $info = svn_info('.');
1462 my $date = $info->{'Last Changed Date'} or die "Missing date\n";
1463 if ($info->{'Last Changed Rev'} != $committed) {
1464 croak "$info->{'Last Changed Rev'} != $committed\n"
1466 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1467 /(\d{4})\-(\d\d)\-(\d\d)\s
1468 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1469 or croak "Failed to parse date: $date\n";
1470 $log_msg->{date} = "$tz $Y-$m-$d $H:$M:$S";
1471 $log_msg->{author} = $info->{'Last Changed Author'};
1472 $log_msg->{revision} = $committed;
1473 $log_msg->{msg} .= "\n";
1474 $log_msg->{parents} = [ $last->{commit} ];
1475 $log_msg->{commit} = git_commit($log_msg, $commit);
1478 # resync immediately
1479 push @svn_up, "-r$last->{revision}";
1481 return fetch("$committed=$commit");
1486 my $pid = open my $fh, '-|';
1487 defined $pid or croak $!;
1489 exec(qw/git-rev-list --pretty=raw/, @args) or croak $!;
1491 return { fh => $fh, t => { } };
1494 sub next_rev_list_entry {
1499 if (/^commit ($sha1)$/o) {
1501 $rl->{t} = { c => $1 };
1506 } elsif (/^parent ($sha1)$/o) {
1513 return ($x != $rl->{t}) ? $x : undef;
1516 # read the entire log into a temporary file (which is removed ASAP)
1517 # and store the file handle + parser state
1519 my (@log_args) = @_;
1520 my $log_fh = IO::File->new_tmpfile or croak $!;
1522 defined $pid or croak $!;
1524 open STDOUT, '>&', $log_fh or croak $!;
1525 exec (qw(svn log), @log_args) or croak $!
1529 seek $log_fh, 0, 0 or croak $!;
1530 return { state => 'sep', fh => $log_fh };
1533 sub next_log_entry {
1534 my $log = shift; # retval of svn_log_raw()
1536 my $fh = $log->{fh};
1541 if ($log->{state} eq 'msg') {
1542 if ($ret->{lines}) {
1543 $ret->{msg} .= $_."\n";
1544 unless(--$ret->{lines}) {
1545 $log->{state} = 'sep';
1548 croak "Log parse error at: $_\n",
1554 if ($log->{state} ne 'sep') {
1555 croak "Log parse error at: $_\n",
1556 "state: $log->{state}\n",
1560 $log->{state} = 'rev';
1562 # if we have an empty log message, put something there:
1564 $ret->{msg} ||= "\n";
1565 delete $ret->{lines};
1570 if ($log->{state} eq 'rev' && s/^r(\d+)\s*\|\s*//) {
1572 my ($author, $date, $lines) = split(/\s*\|\s*/, $_, 3);
1573 ($lines) = ($lines =~ /(\d+)/);
1574 my ($Y,$m,$d,$H,$M,$S,$tz) = ($date =~
1575 /(\d{4})\-(\d\d)\-(\d\d)\s
1576 (\d\d)\:(\d\d)\:(\d\d)\s([\-\+]\d+)/x)
1577 or croak "Failed to parse date: $date\n";
1578 $ret = { revision => $rev,
1579 date => "$tz $Y-$m-$d $H:$M:$S",
1583 if (defined $_authors && ! defined $users{$author}) {
1584 die "Author: $author not defined in ",
1587 $log->{state} = 'msg_start';
1590 # skip the first blank line of the message:
1591 if ($log->{state} eq 'msg_start' && /^$/) {
1592 $log->{state} = 'msg';
1593 } elsif ($log->{state} eq 'msg') {
1594 if ($ret->{lines}) {
1595 $ret->{msg} .= $_."\n";
1596 unless (--$ret->{lines}) {
1597 $log->{state} = 'sep';
1600 croak "Log parse error at: $_\n",
1601 $ret->{revision},"\n";
1609 my $url = shift || $SVN_URL;
1611 my $pid = open my $info_fh, '-|';
1612 defined $pid or croak $!;
1615 exec(qw(svn info),$url) or croak $!;
1619 # only single-lines seem to exist in svn info output
1620 while (<$info_fh>) {
1622 if (m#^([^:]+)\s*:\s*(\S.*)$#) {
1624 push @{$ret->{-order}}, $1;
1627 close $info_fh or croak $?;
1631 sub sys { system(@_) == 0 or croak $? }
1634 my ($from, $to) = @_;
1635 my $es = svn_propget_base('svn:eol-style', $to);
1636 open my $rfd, '<', $from or croak $!;
1637 binmode $rfd or croak $!;
1638 open my $wfd, '>', $to or croak $!;
1639 binmode $wfd or croak $!;
1640 eol_cp_fd($rfd, $wfd, $es);
1641 close $rfd or croak $!;
1642 close $wfd or croak $!;
1646 my ($rfd, $wfd, $es) = @_;
1647 my $eol = defined $es ? $EOL{$es} : undef;
1652 defined($r = sysread($rfd, $buf, 4096)) or croak $!;
1655 if ($buf =~ /\015$/) {
1657 defined($r = sysread($rfd,$c,1)) or croak $!;
1658 $buf .= $c if $r > 0;
1660 $buf =~ s/(?:\015\012|\015|\012)/$eol/gs;
1663 for ($w = 0; $w < $r; $w += $t) {
1664 $t = syswrite($wfd, $buf, $r - $w, $w) or croak $!;
1670 sub do_update_index {
1671 my ($z_cmd, $cmd, $no_text_base) = @_;
1673 my $z = open my $p, '-|';
1674 defined $z or croak $!;
1675 unless ($z) { exec @$z_cmd or croak $! }
1677 my $pid = open my $ui, '|-';
1678 defined $pid or croak $!;
1680 exec('git-update-index',"--$cmd",'-z','--stdin') or croak $!;
1683 while (my $x = <$p>) {
1685 if (!$no_text_base && lstat $x && ! -l _ &&
1686 svn_propget_base('svn:keywords', $x)) {
1687 my $mode = -x _ ? 0755 : 0644;
1688 my ($v,$d,$f) = File::Spec->splitpath($x);
1689 my $tb = File::Spec->catfile($d, '.svn', 'tmp',
1690 'text-base',"$f.svn-base");
1693 $tb = File::Spec->catfile($d, '.svn',
1694 'text-base',"$f.svn-base");
1697 unlink $x or croak $!;
1699 chmod(($mode &~ umask), $x) or croak $!;
1703 close $ui or croak $?;
1707 return if $_use_lib;
1709 if (!-f "$GIT_SVN_DIR/info/exclude") {
1710 open my $fd, '>>', "$GIT_SVN_DIR/info/exclude" or croak $!;
1711 print $fd '.svn',"\n";
1712 close $fd or croak $!;
1714 my $no_text_base = shift;
1715 do_update_index([qw/git-diff-files --name-only -z/],
1718 do_update_index([qw/git-ls-files -z --others/,
1719 "--exclude-from=$GIT_SVN_DIR/info/exclude"],
1725 my ($str, $file, $mode) = @_;
1726 open my $fd,'>',$file or croak $!;
1727 print $fd $str,"\n" or croak $!;
1728 close $fd or croak $!;
1729 chmod ($mode &~ umask, $file) if (defined $mode);
1734 open my $fd,'<',$file or croak "$!: file: $file\n";
1737 close $fd or croak $!;
1742 sub assert_revision_unknown {
1744 if (my $c = revdb_get($REVDB, $r)) {
1745 croak "$r = $c already exists! Why are we refetching it?";
1751 my @x = safe_qx('git-cat-file','commit',$x);
1752 my @y = safe_qx('git-cat-file','commit',$y);
1753 if (($y[0] ne $x[0]) || $x[0] !~ /^tree $sha1\n$/
1754 || $y[0] !~ /^tree $sha1\n$/) {
1755 print STDERR "Trees not equal: $y[0] != $x[0]\n";
1762 my ($log_msg, @parents) = @_;
1763 assert_revision_unknown($log_msg->{revision});
1764 map_tree_joins() if (@_branch_from && !%tree_map);
1766 my (@tmp_parents, @exec_parents, %seen_parent);
1767 if (my $lparents = $log_msg->{parents}) {
1768 @tmp_parents = @$lparents
1770 # commit parents can be conditionally bound to a particular
1771 # svn revision via: "svn_revno=commit_sha1", filter them out here:
1772 foreach my $p (@parents) {
1773 next unless defined $p;
1774 if ($p =~ /^(\d+)=($sha1_short)$/o) {
1775 if ($1 == $log_msg->{revision}) {
1776 push @tmp_parents, $2;
1779 push @tmp_parents, $p if $p =~ /$sha1_short/o;
1782 my $tree = $log_msg->{tree};
1783 if (!defined $tree) {
1784 my $index = set_index($GIT_SVN_INDEX);
1786 chomp($tree = `git-write-tree`);
1788 restore_index($index);
1790 if (exists $tree_map{$tree}) {
1791 push @tmp_parents, @{$tree_map{$tree}};
1793 foreach (@tmp_parents) {
1794 next if $seen_parent{$_};
1795 $seen_parent{$_} = 1;
1796 push @exec_parents, $_;
1797 # MAXPARENT is defined to 16 in commit-tree.c:
1798 last if @exec_parents > 16;
1801 defined(my $pid = open my $out_fh, '-|') or croak $!;
1803 my $msg_fh = IO::File->new_tmpfile or croak $!;
1804 print $msg_fh $log_msg->{msg}, "\ngit-svn-id: ",
1805 "$SVN_URL\@$log_msg->{revision}",
1806 " $SVN_UUID\n" or croak $!;
1807 $msg_fh->flush == 0 or croak $!;
1808 seek $msg_fh, 0, 0 or croak $!;
1809 set_commit_env($log_msg);
1810 my @exec = ('git-commit-tree',$tree);
1811 push @exec, '-p', $_ foreach @exec_parents;
1812 open STDIN, '<&', $msg_fh or croak $!;
1813 exec @exec or croak $!;
1815 chomp(my $commit = do { local $/; <$out_fh> });
1816 close $out_fh or croak $?;
1817 if ($commit !~ /^$sha1$/o) {
1818 croak "Failed to commit, invalid sha1: $commit\n";
1820 my @update_ref = ('git-update-ref',"refs/remotes/$GIT_SVN",$commit);
1821 if (my $primary_parent = shift @exec_parents) {
1822 quiet_run(qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0");
1823 push @update_ref, $primary_parent unless $?;
1826 revdb_set($REVDB, $log_msg->{revision}, $commit);
1828 # this output is read via pipe, do not change:
1829 print "r$log_msg->{revision} = $commit\n";
1835 if ($_repack && (--$_repack_nr == 0)) {
1836 $_repack_nr = $_repack;
1837 sys("git repack $_repack_flags");
1841 sub set_commit_env {
1843 my $author = $log_msg->{author};
1844 if (!defined $author || length $author == 0) {
1845 $author = '(no author)';
1847 my ($name,$email) = defined $users{$author} ? @{$users{$author}}
1848 : ($author,"$author\@$SVN_UUID");
1849 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1850 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1851 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_msg->{date};
1854 sub apply_mod_line_blob {
1856 if ($m->{mode_b} =~ /^120/) {
1857 blob_to_symlink($m->{sha1_b}, $m->{file_b});
1859 blob_to_file($m->{sha1_b}, $m->{file_b});
1863 sub blob_to_symlink {
1864 my ($blob, $link) = @_;
1865 defined $link or croak "\$link not defined!\n";
1866 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1867 if (-l $link || -f _) {
1868 unlink $link or croak $!;
1871 my $dest = `git-cat-file blob $blob`; # no newline, so no chomp
1872 symlink $dest, $link or croak $!;
1876 my ($blob, $file) = @_;
1877 defined $file or croak "\$file not defined!\n";
1878 croak "Not a sha1: $blob\n" unless $blob =~ /^$sha1$/o;
1879 if (-l $file || -f _) {
1880 unlink $file or croak $!;
1883 open my $blob_fh, '>', $file or croak "$!: $file\n";
1885 defined $pid or croak $!;
1888 open STDOUT, '>&', $blob_fh or croak $!;
1889 exec('git-cat-file','blob',$blob) or croak $!;
1894 close $blob_fh or croak $!;
1898 my $pid = open my $child, '-|';
1899 defined $pid or croak $!;
1901 exec(@_) or croak $!;
1903 my @ret = (<$child>);
1904 close $child or croak $?;
1905 die $? if $?; # just in case close didn't error out
1906 return wantarray ? @ret : join('',@ret);
1909 sub svn_compat_check {
1910 my @co_help = safe_qx(qw(svn co -h));
1911 unless (grep /ignore-externals/,@co_help) {
1912 print STDERR "W: Installed svn version does not support ",
1913 "--ignore-externals\n";
1914 $_no_ignore_ext = 1;
1916 if (grep /usage: checkout URL\[\@REV\]/,@co_help) {
1917 $_svn_co_url_revs = 1;
1919 if (grep /\[TARGET\[\@REV\]\.\.\.\]/, `svn propget -h`) {
1920 $_svn_pg_peg_revs = 1;
1923 # I really, really hope nobody hits this...
1924 unless (grep /stop-on-copy/, (safe_qx(qw(svn log -h)))) {
1926 W: The installed svn version does not support the --stop-on-copy flag in
1928 Lets hope the directory you're tracking is not a branch or tag
1929 and was never moved within the repository...
1935 # *sigh*, new versions of svn won't honor -r<rev> without URL@<rev>,
1936 # (and they won't honor URL@<rev> without -r<rev>, too!)
1937 sub svn_cmd_checkout {
1938 my ($url, $rev, $dir) = @_;
1939 my @cmd = ('svn','co', "-r$rev");
1940 push @cmd, '--ignore-externals' unless $_no_ignore_ext;
1941 $url .= "\@$rev" if $_svn_co_url_revs;
1942 sys(@cmd, $url, $dir);
1945 sub check_upgrade_needed {
1947 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
1948 open my $fh, '>>',$REVDB or croak $!;
1952 my $pid = open my $child, '-|';
1953 defined $pid or croak $!;
1956 exec('git-rev-parse',"$GIT_SVN-HEAD") or croak $!;
1958 my @ret = (<$child>);
1959 close $child or croak $?;
1960 die $? if $?; # just in case close didn't error out
1961 return wantarray ? @ret : join('',@ret);
1964 my $head = eval { safe_qx('git-rev-parse',"refs/remotes/$GIT_SVN") };
1966 print STDERR "Please run: $0 rebuild --upgrade\n";
1971 # fills %tree_map with a reverse mapping of trees to commits. Useful
1972 # for finding parents to commit on.
1973 sub map_tree_joins {
1975 foreach my $br (@_branch_from) {
1976 my $pid = open my $pipe, '-|';
1977 defined $pid or croak $!;
1979 exec(qw(git-rev-list --topo-order --pretty=raw), $br)
1983 if (/^commit ($sha1)$/o) {
1986 # if we've seen a commit,
1987 # we've seen its parents
1988 last if $seen{$commit};
1989 my ($tree) = (<$pipe> =~ /^tree ($sha1)$/o);
1990 unless (defined $tree) {
1991 die "Failed to parse commit $commit\n";
1993 push @{$tree_map{$tree}}, $commit;
1997 close $pipe; # we could be breaking the pipe early
2002 if (@_branch_from) {
2003 print STDERR '--branch|-b parameters are ignored when ',
2004 "--branch-all-refs|-B is passed\n";
2007 # don't worry about rev-list on non-commit objects/tags,
2008 # it shouldn't blow up if a ref is a blob or tree...
2009 chomp(@_branch_from = `git-rev-parse --symbolic --all`);
2012 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
2014 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2015 while (<$authors>) {
2017 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2018 my ($user, $name, $email) = ($1, $2, $3);
2019 $users{$user} = [$name, $email];
2021 close $authors or croak $!;
2025 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
2026 while (<$authors>) {
2028 next unless /^(\S+?)\s*=\s*(.+?)\s*<(.+)>\s*$/;
2029 my ($user, $name, $email) = ($1, $2, $3);
2030 $rusers{"$name <$email>"} = $user;
2032 close $authors or croak $!;
2035 sub svn_propget_base {
2037 $f .= '@BASE' if $_svn_pg_peg_revs;
2038 return safe_qx(qw/svn propget/, $p, $f);
2043 foreach (`git-rev-parse --symbolic --all`) {
2044 next unless s#^refs/remotes/##;
2046 next unless -f "$GIT_DIR/svn/$_/info/url";
2054 defined(my $pid = fork) or croak $!;
2056 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
2058 exit 0 if -r $REVDB;
2059 print "Upgrading svn => git mapping...\n";
2060 -d $GIT_SVN_DIR or mkpath([$GIT_SVN_DIR]);
2061 open my $fh, '>>',$REVDB or croak $!;
2064 print "Done upgrading. You may now delete the ",
2065 "deprecated $GIT_SVN_DIR/revs directory\n";
2073 sub migration_check {
2074 migrate_revdb() unless (-e $REVDB);
2075 return if (-d "$GIT_DIR/svn" || !-d $GIT_DIR);
2076 print "Upgrading repository...\n";
2077 unless (-d "$GIT_DIR/svn") {
2078 mkdir "$GIT_DIR/svn" or croak $!;
2080 print "Data from a previous version of git-svn exists, but\n\t",
2081 "$GIT_SVN_DIR\n\t(required for this version ",
2082 "($VERSION) of git-svn) does not.\n";
2084 foreach my $x (`git-rev-parse --symbolic --all`) {
2085 next unless $x =~ s#^refs/remotes/##;
2087 next unless -f "$GIT_DIR/$x/info/url";
2088 my $u = eval { file_to_s("$GIT_DIR/$x/info/url") };
2090 my $dn = dirname("$GIT_DIR/svn/$x");
2091 mkpath([$dn]) unless -d $dn;
2092 rename "$GIT_DIR/$x", "$GIT_DIR/svn/$x" or croak "$!: $x";
2094 migrate_revdb() if (-d $GIT_SVN_DIR && !-w $REVDB);
2095 print "Done upgrading.\n";
2098 sub find_rev_before {
2099 my ($r, $id, $eq_ok) = @_;
2100 my $f = "$GIT_DIR/svn/$id/.rev_db";
2101 return (undef,undef) unless -r $f;
2104 if (my $c = revdb_get($f, $r)) {
2109 return (undef, undef);
2113 $GIT_SVN ||= $ENV{GIT_SVN_ID} || 'git-svn';
2114 $GIT_SVN_DIR = "$GIT_DIR/svn/$GIT_SVN";
2115 $REVDB = "$GIT_SVN_DIR/.rev_db";
2116 $GIT_SVN_INDEX = "$GIT_SVN_DIR/index";
2118 $SVN_WC = "$GIT_SVN_DIR/tree";
2121 # convert GetOpt::Long specs for use by git-repo-config
2122 sub read_repo_config {
2123 return unless -d $GIT_DIR;
2125 foreach my $o (keys %$opts) {
2126 my $v = $opts->{$o};
2127 my ($key) = ($o =~ /^([a-z\-]+)/);
2129 my $arg = 'git-repo-config';
2130 $arg .= ' --int' if ($o =~ /[:=]i$/);
2131 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
2132 if (ref $v eq 'ARRAY') {
2133 chomp(my @tmp = `$arg --get-all svn.$key`);
2136 chomp(my $tmp = `$arg --get svn.$key`);
2137 if ($tmp && !($arg =~ / --bool / && $tmp eq 'false')) {
2144 sub set_default_vals {
2145 if (defined $_repack) {
2146 $_repack = 1000 if ($_repack <= 0);
2147 $_repack_nr = $_repack;
2148 $_repack_flags ||= '-d';
2153 my $gr_file = shift;
2154 my ($grafts, $comments) = ({}, {});
2155 if (open my $fh, '<', $gr_file) {
2158 if (/^($sha1)\s+/) {
2161 @{$comments->{$c}} = @tmp;
2164 foreach my $p (split /\s+/, $_) {
2165 $grafts->{$c}->{$p} = 1;
2171 close $fh or croak $!;
2172 @{$comments->{'END'}} = @tmp if @tmp;
2174 return ($grafts, $comments);
2178 my ($grafts, $comments, $gr_file) = @_;
2180 open my $fh, '>', $gr_file or croak $!;
2181 foreach my $c (sort keys %$grafts) {
2182 if ($comments->{$c}) {
2183 print $fh $_ foreach @{$comments->{$c}};
2185 my $p = $grafts->{$c};
2186 delete $p->{$c}; # commits are not self-reproducing...
2187 my $pid = open my $ch, '-|';
2188 defined $pid or croak $!;
2190 exec(qw/git-cat-file commit/, $c) or croak $!;
2193 if (/^parent ([a-f\d]{40})/) {
2199 close $ch; # breaking the pipe
2200 print $fh $c, ' ', join(' ', sort keys %$p),"\n";
2202 if ($comments->{'END'}) {
2203 print $fh $_ foreach @{$comments->{'END'}};
2205 close $fh or croak $!;
2208 sub read_url_paths {
2210 git_svn_each(sub { my $x = shift;
2211 my $url = file_to_s("$GIT_DIR/svn/$x/info/url");
2212 my ($u, $p) = repo_path_split($url);
2213 $l_map->{$u}->{$p} = $x;
2218 sub extract_metadata {
2220 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
2222 if (!$rev || !$uuid || !$url) {
2223 # some of the original repositories I made had
2224 # indentifiers like this:
2225 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
2227 return ($url, $rev, $uuid);
2230 sub tz_to_s_offset {
2233 return ($1 * 60) + ($tz * 3600);
2236 sub setup_pager { # translated to Perl from pager.c
2237 return unless (-t *STDOUT);
2238 my $pager = $ENV{PAGER};
2239 if (!defined $pager) {
2241 } elsif (length $pager == 0 || $pager eq 'cat') {
2244 pipe my $rfd, my $wfd or return;
2245 defined(my $pid = fork) or croak $!;
2247 open STDOUT, '>&', $wfd or croak $!;
2250 open STDIN, '<&', $rfd or croak $!;
2251 $ENV{LESS} ||= '-S';
2252 exec $pager or croak "Can't run pager: $!\n";;
2255 sub get_author_info {
2256 my ($dest, $author, $t, $tz) = @_;
2257 $author =~ s/(?:^\s*|\s*$)//g;
2258 $dest->{a_raw} = $author;
2261 $_a = $rusers{$author} || undef;
2264 ($_a) = ($author =~ /<([^>]+)\@[^>]+>$/);
2269 # Date::Parse isn't in the standard Perl distro :(
2270 if ($tz =~ s/^\+//) {
2271 $t += tz_to_s_offset($tz);
2272 } elsif ($tz =~ s/^\-//) {
2273 $t -= tz_to_s_offset($tz);
2275 $dest->{t_utc} = $t;
2278 sub process_commit {
2279 my ($c, $r_min, $r_max, $defer) = @_;
2280 if (defined $r_min && defined $r_max) {
2281 if ($r_min == $c->{r} && $r_min == $r_max) {
2285 return 1 if $r_min == $r_max;
2286 if ($r_min < $r_max) {
2287 # we need to reverse the print order
2288 return 0 if (defined $_limit && --$_limit < 0);
2292 if ($r_min != $r_max) {
2293 return 1 if ($r_min < $c->{r});
2294 return 1 if ($r_max > $c->{r});
2297 return 0 if (defined $_limit && --$_limit < 0);
2306 if (my $l = $c->{l}) {
2307 while ($l->[0] =~ /^\s*$/) { shift @$l }
2310 $_l_fmt ||= 'A' . length($c->{r});
2311 print 'r',pack($_l_fmt, $c->{r}),' | ';
2312 print "$c->{c} | " if $_show_commit;
2315 show_commit_normal($c);
2319 sub show_commit_normal {
2321 print '-' x72, "\nr$c->{r} | ";
2322 print "$c->{c} | " if $_show_commit;
2323 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2324 localtime($c->{t_utc})), ' | ';
2327 if (my $l = $c->{l}) {
2328 while ($l->[$#$l] eq "\n" && $l->[($#$l - 1)] eq "\n") {
2331 $nr_line = scalar @$l;
2333 print "1 line\n\n\n";
2335 if ($nr_line == 1) {
2336 $nr_line = '1 line';
2338 $nr_line .= ' lines';
2340 print $nr_line, "\n\n";
2341 print $_ foreach @$l;
2347 foreach my $x (qw/raw diff/) {
2350 print $_ foreach @{$c->{$x}}
2356 return unless $_use_lib;
2359 if ($SVN::Core::VERSION lt '1.2.1') {
2360 die "Need SVN::Core 1.2.1 or better ",
2361 "(got $SVN::Core::VERSION) ",
2362 "Falling back to command-line svn\n";
2366 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
2367 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2368 $SVN::Node::dir.$SVN::Node::unknown.
2369 $SVN::Node::none.$SVN::Node::file.
2370 $SVN::Node::dir.$SVN::Node::unknown;
2375 sub libsvn_connect {
2377 my $auth = SVN::Core::auth_open([SVN::Client::get_simple_provider(),
2378 SVN::Client::get_ssl_server_trust_file_provider(),
2379 SVN::Client::get_username_provider()]);
2380 my $s = eval { SVN::Ra->new(url => $url, auth => $auth) };
2384 sub libsvn_get_file {
2385 my ($gui, $f, $rev) = @_;
2387 return unless ($p =~ s#^\Q$SVN_PATH\E/?##);
2389 my ($hash, $pid, $in, $out);
2390 my $pool = SVN::Pool->new;
2391 defined($pid = open3($in, $out, '>&STDERR',
2392 qw/git-hash-object -w --stdin/)) or croak $!;
2393 my ($r, $props) = $SVN->get_file($f, $rev, $in, $pool);
2394 $in->flush == 0 or croak $!;
2395 close $in or croak $!;
2397 chomp($hash = do { local $/; <$out> });
2398 close $out or croak $!;
2400 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2402 my $mode = exists $props->{'svn:executable'} ? '100755' : '100644';
2403 if (exists $props->{'svn:special'}) {
2405 my $link = `git-cat-file blob $hash`;
2406 $link =~ s/^link // or die "svn:special file with contents: <",
2407 $link, "> is not understood\n";
2408 defined($pid = open3($in, $out, '>&STDERR',
2409 qw/git-hash-object -w --stdin/)) or croak $!;
2411 $in->flush == 0 or croak $!;
2412 close $in or croak $!;
2413 chomp($hash = do { local $/; <$out> });
2414 close $out or croak $!;
2416 $hash =~ /^$sha1$/o or die "not a sha1: $hash\n";
2418 print $gui $mode,' ',$hash,"\t",$p,"\0" or croak $!;
2421 sub libsvn_log_entry {
2422 my ($rev, $author, $date, $msg, $parents) = @_;
2423 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2424 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x)
2425 or die "Unable to parse date: $date\n";
2426 if (defined $_authors && ! defined $users{$author}) {
2427 die "Author: $author not defined in $_authors file\n";
2429 return { revision => $rev, date => "+0000 $Y-$m-$d $H:$M:$S",
2430 author => $author, msg => $msg."\n", parents => $parents || [] }
2434 my ($gui, $last_commit, $f) = @_;
2435 $f =~ s#^\Q$SVN_PATH\E/?## or return;
2436 # remove entire directories.
2437 if (safe_qx('git-ls-tree',$last_commit,'--',$f) =~ /^040000 tree/) {
2438 defined(my $pid = open my $ls, '-|') or croak $!;
2440 exec(qw/git-ls-tree -r --name-only -z/,
2441 $last_commit,'--',$f) or croak $!;
2445 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
2447 close $ls or croak $?;
2449 print $gui '0 ',0 x 40,"\t",$f,"\0" or croak $!;
2454 my ($last_commit, $paths, $rev, $author, $date, $msg) = @_;
2455 open my $gui, '| git-update-index -z --index-info' or croak $!;
2457 foreach my $f (keys %$paths) {
2458 my $m = $paths->{$f}->action();
2460 if ($m =~ /^[DR]$/) {
2461 process_rm($gui, $last_commit, $f);
2463 # 'R' can be file replacements, too, right?
2465 my $pool = SVN::Pool->new;
2466 my $t = $SVN->check_path($f, $rev, $pool);
2467 if ($t == $SVN::Node::file) {
2468 if ($m =~ /^[AMR]$/) {
2471 die "Unrecognized action: $m, ($f r$rev)\n";
2476 libsvn_get_file($gui, $_, $rev) foreach (@amr);
2477 close $gui or croak $?;
2478 return libsvn_log_entry($rev, $author, $date, $msg, [$last_commit]);
2481 sub svn_grab_base_rev {
2482 defined(my $pid = open my $fh, '-|') or croak $!;
2484 open my $null, '>', '/dev/null' or croak $!;
2485 open STDERR, '>&', $null or croak $!;
2486 exec qw/git-rev-parse --verify/,"refs/remotes/$GIT_SVN^0"
2489 chomp(my $c = do { local $/; <$fh> });
2491 if (defined $c && length $c) {
2492 my ($url, $rev, $uuid) = extract_metadata((grep(/^git-svn-id: /,
2493 safe_qx(qw/git-cat-file commit/, $c)))[-1]);
2496 return (undef, undef);
2499 sub libsvn_parse_revision {
2501 my $head = $SVN->get_latest_revnum();
2502 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
2503 return ($base + 1, $head) if (defined $base);
2506 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
2507 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
2508 if ($_revision =~ /^BASE:(\d+)$/) {
2509 return ($base + 1, $1) if (defined $base);
2512 return ($1, $head) if ($_revision =~ /^(\d+):HEAD$/);
2513 die "revision argument: $_revision not understood by git-svn\n",
2514 "Try using the command-line svn client instead\n";
2517 sub libsvn_traverse {
2518 my ($gui, $pfx, $path, $rev) = @_;
2519 my $cwd = "$pfx/$path";
2520 my $pool = SVN::Pool->new;
2522 my ($dirent, $r, $props) = $SVN->get_dir($cwd, $rev, $pool);
2523 foreach my $d (keys %$dirent) {
2524 my $t = $dirent->{$d}->kind;
2525 if ($t == $SVN::Node::dir) {
2526 libsvn_traverse($gui, $cwd, $d, $rev);
2527 } elsif ($t == $SVN::Node::file) {
2528 libsvn_get_file($gui, "$cwd/$d", $rev);
2534 sub libsvn_traverse_ignore {
2535 my ($fh, $path, $r) = @_;
2537 my $pool = SVN::Pool->new;
2538 my ($dirent, undef, $props) = $SVN->get_dir($path, $r, $pool);
2540 $p =~ s#^\Q$SVN_PATH\E/?##;
2541 print $fh length $p ? "\n# $p\n" : "\n# /\n";
2542 if (my $s = $props->{'svn:ignore'}) {
2543 $s =~ s/[\r\n]+/\n/g;
2545 if (length $p == 0) {
2549 $s =~ s#\n#\n/$p/#g;
2550 print $fh "/$p/$s\n";
2553 foreach (sort keys %$dirent) {
2554 next if $dirent->{$_}->kind != $SVN::Node::dir;
2555 libsvn_traverse_ignore($fh, "$path/$_", $r);
2561 my ($path, $r0, $r1) = @_;
2562 return 1 if $r0 == $r1;
2565 # should be OK to use Pool here (r1 - r0) should be small
2566 my $pool = SVN::Pool->new;
2567 $SVN->get_log("/$path", $r0, $r1, 0, 1, 1, sub {$nr++},$pool);
2570 my ($url, undef) = repo_path_split($SVN_URL);
2571 my $svn_log = svn_log_raw("$url/$path","-r$r0:$r1");
2572 while (next_log_entry($svn_log)) { $nr++ }
2573 close $svn_log->{fh};
2575 return 0 if ($nr > 1);
2579 sub libsvn_find_parent_branch {
2580 my ($paths, $rev, $author, $date, $msg) = @_;
2581 my $svn_path = '/'.$SVN_PATH;
2583 # look for a parent from another branch:
2584 my $i = $paths->{$svn_path} or return;
2585 my $branch_from = $i->copyfrom_path or return;
2586 my $r = $i->copyfrom_rev;
2587 print STDERR "Found possible branch point: ",
2588 "$branch_from => $svn_path, $r\n";
2589 $branch_from =~ s#^/##;
2590 my $l_map = read_url_paths();
2591 my $url = $SVN->{url};
2592 defined $l_map->{$url} or return;
2593 my $id = $l_map->{$url}->{$branch_from} or return;
2594 my ($r0, $parent) = find_rev_before($r,$id,1);
2595 return unless (defined $r0 && defined $parent);
2596 if (revisions_eq($branch_from, $r0, $r)) {
2597 unlink $GIT_SVN_INDEX;
2598 print STDERR "Found branch parent: $parent\n";
2599 sys(qw/git-read-tree/, $parent);
2600 return libsvn_fetch($parent, $paths, $rev,
2601 $author, $date, $msg);
2603 print STDERR "Nope, branch point not imported or unknown\n";
2607 sub libsvn_new_tree {
2608 if (my $log_entry = libsvn_find_parent_branch(@_)) {
2611 my ($paths, $rev, $author, $date, $msg) = @_;
2612 open my $gui, '| git-update-index -z --index-info' or croak $!;
2613 my $pool = SVN::Pool->new;
2614 libsvn_traverse($gui, '', $SVN_PATH, $rev, $pool);
2616 close $gui or croak $?;
2617 return libsvn_log_entry($rev, $author, $date, $msg);
2620 sub find_graft_path_commit {
2621 my ($tree_paths, $p1, $r1) = @_;
2622 foreach my $x (keys %$tree_paths) {
2623 next unless ($p1 =~ /^\Q$x\E/);
2624 my $i = $tree_paths->{$x};
2625 my ($r0, $parent) = find_rev_before($r1,$i,1);
2626 return $parent if (defined $r0 && $r0 == $r1);
2627 print STDERR "r$r1 of $i not imported\n";
2633 sub find_graft_path_parents {
2634 my ($grafts, $tree_paths, $c, $p0, $r0) = @_;
2635 foreach my $x (keys %$tree_paths) {
2636 next unless ($p0 =~ /^\Q$x\E/);
2637 my $i = $tree_paths->{$x};
2638 my ($r, $parent) = find_rev_before($r0, $i, 1);
2639 if (defined $r && defined $parent && revisions_eq($x,$r,$r0)) {
2640 $grafts->{$c}->{$parent} = 1;
2645 sub libsvn_graft_file_copies {
2646 my ($grafts, $tree_paths, $path, $paths, $rev) = @_;
2647 foreach (keys %$paths) {
2648 my $i = $paths->{$_};
2649 my ($m, $p0, $r0) = ($i->action, $i->copyfrom_path,
2651 next unless (defined $p0 && defined $r0);
2656 my $c = find_graft_path_commit($tree_paths, $p1, $rev);
2658 find_graft_path_parents($grafts, $tree_paths, $c, $p0, $r0);
2663 my $old = $ENV{GIT_INDEX_FILE};
2664 $ENV{GIT_INDEX_FILE} = shift;
2671 $ENV{GIT_INDEX_FILE} = $old;
2673 delete $ENV{GIT_INDEX_FILE};
2677 sub libsvn_commit_cb {
2678 my ($rev, $date, $committer, $c, $msg, $r_last, $cmt_last) = @_;
2679 if ($_optimize_commits && $rev == ($r_last + 1)) {
2680 my $log = libsvn_log_entry($rev,$committer,$date,$msg);
2681 $log->{tree} = get_tree_from_treeish($c);
2682 my $cmt = git_commit($log, $cmt_last, $c);
2683 my @diff = safe_qx('git-diff-tree', $cmt, $c);
2685 print STDERR "Trees differ: $cmt $c\n",
2686 join('',@diff),"\n";
2694 sub libsvn_ls_fullurl {
2695 my $fullurl = shift;
2696 my ($repo, $path) = repo_path_split($fullurl);
2697 $SVN ||= libsvn_connect($repo);
2699 my $pool = SVN::Pool->new;
2700 my ($dirent, undef, undef) = $SVN->get_dir($path,
2701 $SVN->get_latest_revnum, $pool);
2702 foreach my $d (keys %$dirent) {
2703 if ($dirent->{$d}->kind == $SVN::Node::dir) {
2704 push @ret, "$d/"; # add '/' for compat with cli svn
2712 sub libsvn_skip_unknown_revs {
2714 my $errno = $err->apr_err();
2715 # Maybe the branch we're tracking didn't
2716 # exist when the repo started, so it's
2717 # not an error if it doesn't, just continue
2719 # Wonderfully consistent library, eh?
2720 # 160013 - svn:// and file://
2721 # 175002 - http(s)://
2722 # More codes may be discovered later...
2723 if ($errno == 175002 || $errno == 160013) {
2726 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2729 # Tie::File seems to be prone to offset errors if revisions get sparse,
2730 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2731 # one of my favorite modules is out :< Next up would be one of the DBM
2732 # modules, but I'm not sure which is most portable... So I'll just
2733 # go with something that's plain-text, but still capable of
2734 # being randomly accessed. So here's my ultra-simple fixed-width
2735 # database. All records are 40 characters + "\n", so it's easy to seek
2736 # to a revision: (41 * rev) is the byte offset.
2737 # A record of 40 0s denotes an empty revision.
2738 # And yes, it's still pretty fast (faster than Tie::File).
2740 my ($file, $rev, $commit) = @_;
2741 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
2742 open my $fh, '+<', $file or croak $!;
2743 my $offset = $rev * 41;
2744 # assume that append is the common case:
2745 seek $fh, 0, 2 or croak $!;
2747 if ($pos < $offset) {
2748 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41);
2750 seek $fh, $offset, 0 or croak $!;
2751 print $fh $commit,"\n";
2752 close $fh or croak $!;
2756 my ($file, $rev) = @_;
2758 my $offset = $rev * 41;
2759 open my $fh, '<', $file or croak $!;
2760 seek $fh, $offset, 0;
2761 if (tell $fh == $offset) {
2762 $ret = readline $fh;
2765 $ret = undef if ($ret =~ /^0{40}$/);
2768 close $fh or croak $!;
2772 sub copy_remote_ref {
2773 my $origin = $_cp_remote ? $_cp_remote : 'origin';
2774 my $ref = "refs/remotes/$GIT_SVN";
2775 if (safe_qx('git-ls-remote', $origin, $ref)) {
2776 sys(qw/git fetch/, $origin, "$ref:$ref");
2778 die "Unable to find remote reference: ",
2779 "refs/remotes/$GIT_SVN on $origin\n";
2783 package SVN::Git::Editor;
2792 my $git_svn = shift;
2793 my $self = SVN::Delta::Editor->new(@_);
2794 bless $self, $class;
2795 foreach (qw/svn_path c r ra /) {
2796 die "$_ required!\n" unless (defined $git_svn->{$_});
2797 $self->{$_} = $git_svn->{$_};
2799 $self->{pool} = SVN::Pool->new;
2800 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2802 require Digest::MD5;
2807 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2811 (defined $_[1] && length $_[1]) ? "$_[0]->{svn_path}/$_[1]"
2816 my ($self, $path) = @_;
2817 $self->{ra}->{url} . '/' . $self->repo_path($path);
2822 my $rm = $self->{rm};
2823 delete $rm->{''}; # we never delete the url we're tracking
2826 foreach (keys %$rm) {
2827 my @d = split m#/#, $_;
2831 $c .= '/' . shift @d;
2835 delete $rm->{$self->{svn_path}};
2836 delete $rm->{''}; # we never delete the url we're tracking
2839 defined(my $pid = open my $fh,'-|') or croak $!;
2841 exec qw/git-ls-tree --name-only -r -z/, $self->{c} or croak $!;
2846 $_ = $self->{svn_path} . '/' . $_;
2847 my ($dn) = ($_ =~ m#^(.*?)/?(?:[^/]+)$#);
2851 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2852 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2853 $self->close_directory($bat->{$d}, $p);
2854 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2855 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2860 sub open_or_add_dir {
2861 my ($self, $full_path, $baton) = @_;
2862 my $p = SVN::Pool->new;
2863 my $t = $self->{ra}->check_path($full_path, $self->{r}, $p);
2865 if ($t == $SVN::Node::none) {
2866 return $self->add_directory($full_path, $baton,
2867 undef, -1, $self->{pool});
2868 } elsif ($t == $SVN::Node::dir) {
2869 return $self->open_directory($full_path, $baton,
2870 $self->{r}, $self->{pool});
2872 print STDERR "$full_path already exists in repository at ",
2873 "r$self->{r} and it is not a directory (",
2874 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2879 my ($self, $path) = @_;
2880 my $bat = $self->{bat};
2881 $path = $self->repo_path($path);
2882 return $bat->{''} unless (length $path);
2883 my @p = split m#/+#, $path;
2885 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2888 $c .= '/' . shift @p;
2889 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2895 my ($self, $m) = @_;
2896 my ($dir, $file) = split_path($m->{file_b});
2897 my $pbat = $self->ensure_path($dir);
2898 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2900 $self->chg_file($fbat, $m);
2901 $self->close_file($fbat,undef,$self->{pool});
2905 my ($self, $m) = @_;
2906 my ($dir, $file) = split_path($m->{file_b});
2907 my $pbat = $self->ensure_path($dir);
2908 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2909 $self->url_path($m->{file_a}), $self->{r});
2910 $self->chg_file($fbat, $m);
2911 $self->close_file($fbat,undef,$self->{pool});
2915 my ($self, $path, $pbat) = @_;
2916 my $rpath = $self->repo_path($path);
2917 my ($dir, $file) = split_path($rpath);
2918 $self->{rm}->{$dir} = 1;
2919 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2923 my ($self, $m) = @_;
2924 my ($dir, $file) = split_path($m->{file_b});
2925 my $pbat = $self->ensure_path($dir);
2926 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2927 $self->url_path($m->{file_a}), $self->{r});
2928 $self->chg_file($fbat, $m);
2929 $self->close_file($fbat,undef,$self->{pool});
2931 ($dir, $file) = split_path($m->{file_a});
2932 $pbat = $self->ensure_path($dir);
2933 $self->delete_entry($m->{file_a}, $pbat);
2937 my ($self, $m) = @_;
2938 my ($dir, $file) = split_path($m->{file_b});
2939 my $pbat = $self->ensure_path($dir);
2940 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2941 $pbat,$self->{r},$self->{pool});
2942 $self->chg_file($fbat, $m);
2943 $self->close_file($fbat,undef,$self->{pool});
2946 sub T { shift->M(@_) }
2948 sub change_file_prop {
2949 my ($self, $fbat, $pname, $pval) = @_;
2950 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2954 my ($self, $fbat, $m) = @_;
2955 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2956 $self->change_file_prop($fbat,'svn:executable','*');
2957 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2958 $self->change_file_prop($fbat,'svn:executable',undef);
2960 my $fh = IO::File->new_tmpfile or croak $!;
2961 if ($m->{mode_b} =~ /^120/) {
2962 print $fh 'link ' or croak $!;
2963 $self->change_file_prop($fbat,'svn:special','*');
2964 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2965 $self->change_file_prop($fbat,'svn:special',undef);
2967 defined(my $pid = fork) or croak $!;
2969 open STDOUT, '>&', $fh or croak $!;
2970 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2974 $fh->flush == 0 or croak $!;
2975 seek $fh, 0, 0 or croak $!;
2977 my $md5 = Digest::MD5->new;
2978 $md5->addfile($fh) or croak $!;
2979 seek $fh, 0, 0 or croak $!;
2981 my $exp = $md5->hexdigest;
2982 my $atd = $self->apply_textdelta($fbat, undef, $self->{pool});
2983 my $got = SVN::TxDelta::send_stream($fh, @$atd, $self->{pool});
2984 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2986 close $fh or croak $!;
2990 my ($self, $m) = @_;
2991 my ($dir, $file) = split_path($m->{file_b});
2992 my $pbat = $self->ensure_path($dir);
2993 $self->delete_entry($m->{file_b}, $pbat);
2998 my ($p,$bat) = ($self->{pool}, $self->{bat});
2999 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3000 $self->close_directory($bat->{$_}, $p);
3002 $self->SUPER::close_edit($p);
3008 $self->SUPER::abort_edit($self->{pool});
3009 $self->{pool}->clear;
3016 $svn_log hashref (as returned by svn_log_raw)
3018 fh => file handle of the log file,
3019 state => state of the log file parser (sep/msg/rev/msg_start...)
3022 $log_msg hashref as returned by next_log_entry($svn_log)
3024 msg => 'whitespace-formatted log entry
3025 ', # trailing newline is preserved
3026 revision => '8', # integer
3027 date => '2004-02-24T17:01:44.108345Z', # commit date
3028 author => 'committer name'
3032 @mods = array of diff-index line hashes, each element represents one line
3033 of diff-index output
3035 diff-index line ($m hash)
3037 mode_a => first column of diff-index output, no leading ':',
3038 mode_b => second column of diff-index output,
3039 sha1_b => sha1sum of the final blob,
3040 chg => change type [MCRADT],
3041 file_a => original file name of a file (iff chg is 'C' or 'R')
3042 file_b => new/current file name of a file (any chg)
3047 I don't trust the each() function on unless I created %hash myself
3048 because the internal iterator may not have started at base.