2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
8 $GIT_SVN_INDEX $GIT_SVN
9 $GIT_DIR $GIT_SVN_DIR $REVDB
10 $_follow_parent $sha1 $sha1_short $_revision
11 $_cp_remote $_upgrade $_rmdir $_q $_cp_similarity
12 $_find_copies_harder $_l $_authors %users/;
13 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
14 $VERSION = '@@GIT_VERSION@@';
16 $ENV{GIT_DIR} ||= '.git';
17 $Git::SVN::default_repo_id = $ENV{GIT_SVN_ID} || 'git-svn';
19 my $LC_ALL = $ENV{LC_ALL};
20 $Git::SVN::Log::TZ = $ENV{TZ};
21 # make sure the svn binary gives consistent output between locales and TZs:
24 $| = 1; # unbuffer STDOUT
26 sub fatal (@) { print STDERR @_; exit 1 }
27 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
30 if ($SVN::Core::VERSION lt '1.1.0') {
31 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
33 push @Git::SVN::Ra::ISA, 'SVN::Ra';
34 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
35 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
38 use File::Basename qw/dirname basename/;
39 use File::Path qw/mkpath/;
40 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
46 foreach (qw/command command_oneline command_noisy command_output_pipe
47 command_input_pipe command_close_pipe/) {
48 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
49 "*Git::SVN::Migration::$_ = ".
50 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
57 my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
58 $sha1 = qr/[a-f\d]{40}/;
59 $sha1_short = qr/[a-f\d]{4,40}/;
60 my ($_stdin, $_help, $_edit,
61 $_repack, $_repack_nr, $_repack_flags,
62 $_message, $_file, $_no_metadata,
65 $_merge, $_strategy, $_dry_run,
68 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
69 'config-dir=s' => \$Git::SVN::Ra::config_dir,
70 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
71 my %fc_opts = ( 'follow-parent|follow' => \$_follow_parent,
72 'authors-file|A=s' => \$_authors,
73 'repack:i' => \$_repack,
74 'no-metadata' => \$_no_metadata,
76 'repack-flags|repack-args|repack-opts=s' => \$_repack_flags,
79 my ($_trunk, $_tags, $_branches);
80 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
81 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches );
83 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
84 my %cmt_opts = ( 'edit|e' => \$_edit,
86 'find-copies-harder' => \$_find_copies_harder,
88 'copy-similarity|C=i'=> \$_cp_similarity
92 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
93 { 'revision|r=s' => \$_revision, %fc_opts } ],
94 init => [ \&cmd_init, "Initialize a repo for tracking" .
95 " (requires URL argument)",
97 dcommit => [ \&cmd_dcommit,
98 'Commit several diffs to merge with upstream',
99 { 'merge|m|M' => \$_merge,
100 'strategy|s=s' => \$_strategy,
101 'dry-run|n' => \$_dry_run,
102 %cmt_opts, %fc_opts } ],
103 'set-tree' => [ \&cmd_set_tree,
104 "Set an SVN repository to a git tree-ish",
105 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
106 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
107 { 'revision|r=i' => \$_revision } ],
108 rebuild => [ \&cmd_rebuild, "Rebuild git-svn metadata (after git clone)",
109 { 'copy-remote|remote=s' => \$_cp_remote,
110 'upgrade' => \$_upgrade } ],
111 'multi-init' => [ \&cmd_multi_init,
112 'Initialize multiple trees (like git-svnimport)',
113 { %multi_opts, %init_opts, %remote_opts,
114 'revision|r=i' => \$_revision,
115 'prefix=s' => \$_prefix,
117 'multi-fetch' => [ \&cmd_multi_fetch,
118 'Fetch multiple trees (like git-svnimport)',
120 'migrate' => [ sub { },
121 # no-op, we automatically run this anyways,
122 'Migrate configuration/metadata/layout from
123 previous versions of git-svn',
125 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
126 { 'limit=i' => \$Git::SVN::Log::limit,
127 'revision|r=s' => \$_revision,
128 'verbose|v' => \$Git::SVN::Log::verbose,
129 'incremental' => \$Git::SVN::Log::incremental,
130 'oneline' => \$Git::SVN::Log::oneline,
131 'show-commit' => \$Git::SVN::Log::show_commit,
132 'non-recursive' => \$Git::SVN::Log::non_recursive,
133 'authors-file|A=s' => \$_authors,
134 'color' => \$Git::SVN::Log::color,
135 'pager=s' => \$Git::SVN::Log::pager,
137 'commit-diff' => [ \&cmd_commit_diff,
138 'Commit a diff between two trees',
139 { 'message|m=s' => \$_message,
140 'file|F=s' => \$_file,
141 'revision|r=s' => \$_revision,
146 for (my $i = 0; $i < @ARGV; $i++) {
147 if (defined $cmd{$ARGV[$i]}) {
154 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
156 read_repo_config(\%opts);
157 my $rv = GetOptions(%opts, 'help|H|h' => \$_help,
158 'version|V' => \$_version,
159 'minimize-connections' =>
160 \$Git::SVN::Migration::_minimize,
161 'id|i=s' => \$Git::SVN::default_repo_id);
162 exit 1 if (!$rv && $cmd ne 'log');
165 version() if $_version;
166 usage(1) unless defined $cmd;
167 load_authors() if $_authors;
168 unless ($cmd =~ /^(?:init|rebuild|multi-init|commit-diff)$/) {
169 Git::SVN::Migration::migration_check();
171 $cmd{$cmd}->[0]->(@ARGV);
174 ####################### primary functions ######################
176 my $exit = shift || 0;
177 my $fd = $exit ? \*STDERR : \*STDOUT;
179 git-svn - bidirectional operations between a single Subversion tree and git
180 Usage: $0 <command> [options] [arguments]\n
182 print $fd "Available commands:\n" unless $cmd;
184 foreach (sort keys %cmd) {
185 next if $cmd && $cmd ne $_;
186 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
187 foreach (keys %{$cmd{$_}->[2]}) {
188 # prints out arguments as they should be passed:
189 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
190 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
192 split /\|/,$_)," $x\n";
196 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
197 arbitrary identifier if you're tracking multiple SVN branches/repositories in
198 one git repository and want to keep them separate. See git-svn(1) for more
205 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
211 my $gs = $url ? Git::SVN->init($url)
212 : eval { Git::SVN->new };
213 $gs ||= Git::SVN->_new;
214 if (!verify_ref($gs->refname.'^0')) {
215 $gs->copy_remote_ref;
218 my ($rev_list, $ctx) = command_output_pipe("rev-list", $gs->refname);
221 while (<$rev_list>) {
224 fatal "Non-SHA1: $c\n" unless $c =~ /^$sha1$/o;
225 my ($url, $rev, $uuid) = cmt_metadata($c);
227 # ignore merges (from set-tree)
228 next if (!defined $rev || !$uuid);
230 # if we merged or otherwise started elsewhere, this is
231 # how we break out of it
232 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
233 ($gs->{url} && $url && ($url ne $gs->{url}))) {
237 unless (defined $latest) {
238 if (!$gs->{url} && !$url) {
239 fatal "SVN repository location required\n";
241 $gs = Git::SVN->init($url);
244 $gs->rev_db_set($rev, $c);
245 print "r$rev = $c\n";
247 command_close_pipe($rev_list, $ctx);
251 unless (-d $ENV{GIT_DIR}) {
252 my @init_db = ('init');
253 push @init_db, "--template=$_template" if defined $_template;
254 push @init_db, "--shared" if defined $_shared;
255 command_noisy(@init_db);
260 my $url = shift or die "SVN repository location required " .
261 "as a command-line argument\n";
262 if (my $repo_path = shift) {
263 unless (-d $repo_path) {
264 mkpath([$repo_path]);
266 chdir $repo_path or croak $!;
267 $ENV{GIT_DIR} = $repo_path . "/.git";
271 Git::SVN->init($url);
275 my $gs = Git::SVN->new;
277 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
278 command_noisy(qw(update-ref refs/heads/master),
285 if ($_stdin || !@commits) {
286 print "Reading from stdin...\n";
289 if (/\b($sha1_short)\b/o) {
290 unshift @commits, $1;
295 foreach my $c (@commits) {
296 my @tmp = command('rev-parse',$c);
297 if (scalar @tmp == 1) {
299 } elsif (scalar @tmp > 1) {
300 push @revs, reverse(command('rev-list',@tmp));
302 fatal "Failed to rev-parse $c\n";
305 my $gs = Git::SVN->new;
306 my ($r_last, $cmt_last) = $gs->last_rev_commit;
308 if ($r_last != $gs->{last_rev}) {
309 fatal "There are new revisions that were fetched ",
310 "and need to be merged (or acknowledged) ",
311 "before committing.\nlast rev: $r_last\n",
312 " current: $gs->{last_rev}\n";
314 $gs->set_tree($_) foreach @revs;
315 print "Done committing ",scalar @revs," revisions to SVN\n";
320 my $gs = Git::SVN->new;
322 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
324 foreach my $d (reverse @refs) {
325 if (!verify_ref("$d~1")) {
327 "has no parent commit, and therefore ",
328 "nothing to diff against.\n",
329 "You should be working from a repository ",
330 "originally created by git-svn\n";
332 unless (defined $last_rev) {
333 (undef, $last_rev, undef) = cmt_metadata("$d~1");
334 unless (defined $last_rev) {
335 fatal "Unable to extract revision information ",
336 "from commit $d~1\n";
340 print "diff-tree $d~1 $d\n";
342 my $log = get_commit_entry($d)->{log};
344 my $pool = SVN::Pool->new;
345 my %ed_opts = ( r => $last_rev,
347 svn_path => $ra->{svn_path} );
348 my $ed = SVN::Git::Editor->new(\%ed_opts,
349 $ra->get_commit_editor($log,
350 sub { print "Committed r$_[0]\n";
351 $last_rev = $_[0]; }),
353 my $mods = $ed->apply_diff("$d~1", $d);
355 print "No changes\n$d~1 == $d\n";
361 # we always want to rebase against the current HEAD, not any
362 # head that was passed to us
363 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
366 @finish = qw/rebase/;
367 push @finish, qw/--merge/ if $_merge;
368 push @finish, "--strategy=$_strategy" if $_strategy;
369 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
370 "using @finish:\n", "@diff";
372 print "No changes between current HEAD and ",
373 $gs->refname, "\nResetting to the latest ",
375 @finish = qw/reset --mixed/;
377 command_noisy(@finish, $gs->refname);
380 sub cmd_show_ignore {
381 my $gs = Git::SVN->new;
382 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
383 $gs->traverse_ignore(\*STDOUT, '', $r);
388 unless (defined $_trunk || defined $_branches || defined $_tags) {
392 $_prefix = '' unless defined $_prefix;
393 $url =~ s#/+$## if defined $url;
394 if (defined $_trunk) {
395 my $trunk_ref = $_prefix . 'trunk';
396 # try both old-style and new-style lookups:
397 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
399 my ($trunk_url, $trunk_path) =
400 complete_svn_url($url, $_trunk);
401 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
405 return unless defined $_branches || defined $_tags;
406 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
407 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
408 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
411 sub cmd_multi_fetch {
413 foreach (command(qw/config -l/)) {
414 next unless m!^svn-remote\.(.+)\.fetch=
415 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
416 my ($repo_id, $path, $ref_id) = ($1, $2, $3);
417 push @gs, Git::SVN->new($ref_id, $repo_id, $path);
424 # this command is special because it requires no metadata
425 sub cmd_commit_diff {
426 my ($ta, $tb, $url) = @_;
427 my $usage = "Usage: $0 commit-diff -r<revision> ".
428 "<tree-ish> <tree-ish> [<URL>]\n";
429 fatal($usage) if (!defined $ta || !defined $tb);
431 my $gs = eval { Git::SVN->new };
433 fatal("Needed URL or usable git-svn --id in ",
434 "the command-line\n", $usage);
438 unless (defined $_revision) {
439 fatal("-r|--revision is a required argument\n", $usage);
441 if (defined $_message && defined $_file) {
442 fatal("Both --message/-m and --file/-F specified ",
443 "for the commit message.\n",
444 "I have no idea what you mean\n");
446 if (defined $_file) {
447 $_message = file_to_s($_file);
449 $_message ||= get_commit_entry($tb)->{log};
451 my $ra ||= Git::SVN::Ra->new($url);
454 $r = $ra->get_latest_revnum;
455 } elsif ($r !~ /^\d+$/) {
456 die "revision argument: $r not understood by git-svn\n";
458 my $pool = SVN::Pool->new;
459 my %ed_opts = ( r => $r,
461 svn_path => $ra->{svn_path} );
462 my $ed = SVN::Git::Editor->new(\%ed_opts,
463 $ra->get_commit_editor($_message,
464 sub { print "Committed r$_[0]\n" }),
466 my $mods = $ed->apply_diff($ta, $tb);
468 print "No changes\n$ta == $tb\n";
473 ########################### utility functions #########################
475 sub complete_svn_url {
476 my ($url, $path) = @_;
478 if ($path !~ m#^[a-z\+]+://#) {
479 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
480 fatal("E: '$path' is not a complete URL ",
481 "and a separate URL is not specified\n");
483 return ($url, $path);
488 sub complete_url_ls_init {
489 my ($ra, $repo_path, $switch, $pfx) = @_;
490 unless ($repo_path) {
491 print STDERR "W: $switch not specified\n";
494 $repo_path =~ s#/+$##;
495 if ($repo_path =~ m#^[a-z\+]+://#) {
496 $ra = Git::SVN::Ra->new($repo_path);
499 $repo_path =~ s#^/+##;
501 fatal("E: '$repo_path' is not a complete URL ",
502 "and a separate URL is not specified\n");
505 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
506 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
507 my $url = $ra->{url};
508 foreach my $d (sort keys %$dirent) {
509 next if ($dirent->{$d}->kind != $SVN::Node::dir);
510 my $path = "$repo_path/$d";
512 my $gs = eval { Git::SVN->new($ref) };
513 # don't try to init already existing refs
515 print "init $url/$path => $ref\n";
516 Git::SVN->init($url, $path, undef, $ref);
523 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
527 sub get_tree_from_treeish {
529 # $treeish can be a symbolic ref, too:
530 my $type = command_oneline(qw/cat-file -t/, $treeish);
532 while ($type eq 'tag') {
533 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
535 if ($type eq 'commit') {
536 $expected = (grep /^tree /, command(qw/cat-file commit/,
538 ($expected) = ($expected =~ /^tree ($sha1)$/o);
539 die "Unable to get tree from $treeish\n" unless $expected;
540 } elsif ($type eq 'tree') {
541 $expected = $treeish;
543 die "$treeish is a $type, expected tree, tag or commit\n";
548 sub get_commit_entry {
549 my ($treeish) = shift;
550 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
551 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
552 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
553 open my $log_fh, '>', $commit_editmsg or croak $!;
555 my $type = command_oneline(qw/cat-file -t/, $treeish);
556 if ($type eq 'commit' || $type eq 'tag') {
557 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
562 $in_msg = 1 if (/^\s*$/);
563 } elsif (/^git-svn-id: /) {
564 # skip this for now, we regenerate the
565 # correct one on re-fetch anyways
566 # TODO: set *:merge properties or like...
568 print $log_fh $_ or croak $!;
571 command_close_pipe($msg_fh, $ctx);
573 close $log_fh or croak $!;
575 if ($_edit || ($type eq 'tree')) {
576 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
577 # TODO: strip out spaces, comments, like git-commit.sh
578 system($editor, $commit_editmsg);
580 rename $commit_editmsg, $commit_msg or croak $!;
581 open $log_fh, '<', $commit_msg or croak $!;
582 { local $/; chomp($log_entry{log} = <$log_fh>); }
583 close $log_fh or croak $!;
589 my ($str, $file, $mode) = @_;
590 open my $fd,'>',$file or croak $!;
591 print $fd $str,"\n" or croak $!;
592 close $fd or croak $!;
593 chmod ($mode &~ umask, $file) if (defined $mode);
598 open my $fd,'<',$file or croak "$!: file: $file\n";
601 close $fd or croak $!;
606 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
608 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
609 my $log = $cmd eq 'log';
612 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
613 my ($user, $name, $email) = ($1, $2, $3);
615 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
617 $users{$user} = [$name, $email];
620 close $authors or croak $!;
623 # convert GetOpt::Long specs for use by git-config
624 sub read_repo_config {
625 return unless -d $ENV{GIT_DIR};
627 foreach my $o (keys %$opts) {
629 my ($key) = ($o =~ /^([a-z\-]+)/);
631 my $arg = 'git-config';
632 $arg .= ' --int' if ($o =~ /[:=]i$/);
633 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
634 if (ref $v eq 'ARRAY') {
635 chomp(my @tmp = `$arg --get-all svn.$key`);
638 chomp(my $tmp = `$arg --get svn.$key`);
639 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
646 sub extract_metadata {
647 my $id = shift or return (undef, undef, undef);
648 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
650 if (!defined $rev || !$uuid || !$url) {
651 # some of the original repositories I made had
652 # identifiers like this:
653 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
655 return ($url, $rev, $uuid);
659 return extract_metadata((grep(/^git-svn-id: /,
660 command(qw/cat-file commit/, shift)))[-1]);
663 sub get_commit_time {
665 my $fh = command_output_pipe(qw/rev-list --pretty=raw -n1/, $cmt);
667 /^committer\s(?:.+) (\d+) ([\-\+]?\d+)$/ or next;
668 my ($s, $tz) = ($1, $2);
669 if ($tz =~ s/^\+//) {
670 $s += tz_to_s_offset($tz);
671 } elsif ($tz =~ s/^\-//) {
672 $s -= tz_to_s_offset($tz);
677 die "Can't get commit time for commit: $cmt\n";
683 return ($1 * 60) + ($tz * 3600);
689 use vars qw/$default_repo_id/;
691 use File::Path qw/mkpath/;
694 # properties that we do not log:
697 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
698 svn:special svn:executable
699 svn:entry:committed-rev
700 svn:entry:last-author
702 svn:entry:committed-date/;
705 sub read_all_remotes {
707 foreach (grep { s/^svn-remote\.// } command(qw/repo-config -l/)) {
708 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
709 $r->{$1}->{fetch}->{$2} = $3;
710 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
711 $r->{$1}->{url} = $2;
717 # we allow more chars than remotes2config.sh...
718 sub sanitize_remote_name {
720 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
725 my ($class, $url, $path, $repo_id, $ref_id) = @_;
726 my $self = _new($class, $repo_id, $ref_id, $path);
727 mkpath([$self->{dir}]);
729 $url =~ s!/+$!!; # strip trailing slash
730 my $orig_url = eval {
731 command_oneline('config', '--get',
732 "svn-remote.$repo_id.url")
735 if ($orig_url ne $url) {
736 die "svn-remote.$repo_id.url already set: ",
737 "$orig_url\nwanted to set to: $url\n";
740 command_noisy('config',
741 "svn-remote.$repo_id.url", $url);
743 command_noisy('config', '--add',
744 "svn-remote.$repo_id.fetch",
745 "$path:".$self->refname);
748 unless (-f $self->{db_path}) {
749 open my $fh, '>>', $self->{db_path} or croak $!;
750 close $fh or croak $!;
757 foreach (command(qw/config -l/)) {
758 next unless m!^svn-remote\.(.+)\.fetch=
759 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
760 my ($repo_id, $path, $ref) = ($1, $2, $3);
761 if ($ref eq $ref_id) {
762 $path = '' if ($path =~ m#^\./?#);
763 return ($repo_id, $path);
766 (undef, undef, undef);
770 my ($class, $ref_id, $repo_id, $path) = @_;
771 if (defined $ref_id && !defined $repo_id && !defined $path) {
772 ($repo_id, $path) = find_ref($ref_id);
773 if (!defined $repo_id) {
774 die "Could not find a \"svn-remote.*.fetch\" key ",
775 "in the repository configuration matching: ",
776 "refs/remotes/$ref_id\n";
779 my $self = _new($class, $repo_id, $ref_id, $path);
780 $self->{url} = command_oneline('config', '--get',
781 "svn-remote.$repo_id.url") or
782 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
786 sub refname { "refs/remotes/$_[0]->{ref_id}" }
790 $self->{ra} ||= Git::SVN::Ra->new($self->{url});
793 sub copy_remote_ref {
795 my $origin = $::_cp_remote ? $::_cp_remote : 'origin';
796 my $ref = $self->refname;
797 if (command('ls-remote', $origin, $ref)) {
798 command_noisy('fetch', $origin, "$ref:$ref");
799 } elsif ($::_cp_remote && !$::_upgrade) {
800 die "Unable to find remote reference: $ref on $origin\n";
804 sub traverse_ignore {
805 my ($self, $fh, $path, $r) = @_;
807 my ($dirent, undef, $props) = $self->ra->get_dir($path, $r);
809 $p =~ s#^\Q$self->{ra}->{svn_path}\E/##;
810 print $fh length $p ? "\n# $p\n" : "\n# /\n";
811 if (my $s = $props->{'svn:ignore'}) {
812 $s =~ s/[\r\n]+/\n/g;
814 if (length $p == 0) {
819 print $fh "/$p/$s\n";
822 foreach (sort keys %$dirent) {
823 next if $dirent->{$_}->kind != $SVN::Node::dir;
824 $self->traverse_ignore($fh, "$path/$_", $r);
828 # returns the newest SVN revision number and newest commit SHA1
829 sub last_rev_commit {
831 if (defined $self->{last_rev} && defined $self->{last_commit}) {
832 return ($self->{last_rev}, $self->{last_commit});
834 my $c = ::verify_ref($self->refname.'^0');
836 my $rev = (::cmt_metadata($c))[1];
838 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
842 my $offset = -41; # from tail
844 open my $fh, '<', $self->{db_path} or
845 croak "$self->{db_path} not readable: $!\n";
846 seek $fh, $offset, 2;
848 defined $rl or return (undef, undef);
850 while ($c ne $rl && tell $fh != 0) {
852 seek $fh, $offset, 2;
854 defined $rl or return (undef, undef);
858 croak $! if ($rev < 0);
859 $rev = ($rev - 41) / 41;
860 close $fh or croak $!;
861 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
866 my ($self, $base) = @_;
867 my $head = $self->ra->get_latest_revnum;
868 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
869 return ($base + 1, $head) if (defined $base);
872 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
873 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
874 if ($::_revision =~ /^BASE:(\d+)$/) {
875 return ($base + 1, $1) if (defined $base);
878 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
879 die "revision argument: $::_revision not understood by git-svn\n",
880 "Try using the command-line svn client instead\n";
884 my ($self, $sub) = @_;
885 my $old_index = $ENV{GIT_INDEX_FILE};
886 $ENV{GIT_INDEX_FILE} = $self->{index};
889 $ENV{GIT_INDEX_FILE} = $old_index;
891 delete $ENV{GIT_INDEX_FILE};
893 wantarray ? @ret : $ret[0];
896 sub assert_index_clean {
897 my ($self, $treeish) = @_;
899 $self->tmp_index_do(sub {
900 command_noisy('read-tree', $treeish) unless -e $self->{index};
901 my $x = command_oneline('write-tree');
902 my ($y) = (command(qw/cat-file commit/, $treeish) =~
903 /^tree ($::sha1)/mo);
905 unlink $self->{index} or croak $!;
906 command_noisy('read-tree', $treeish);
908 $x = command_oneline('write-tree');
910 ::fatal "trees ($treeish) $y != $x\n",
911 "Something is seriously wrong...\n";
916 sub get_commit_parents {
917 my ($self, $log_entry, @parents) = @_;
918 my (%seen, @ret, @tmp);
919 # commit parents can be conditionally bound to a particular
920 # svn revision via: "svn_revno=commit_sha1", filter them out here:
921 foreach my $p (@parents) {
922 next unless defined $p;
923 if ($p =~ /^(\d+)=($::sha1_short)$/o) {
924 push @tmp, $2 if $1 == $log_entry->{revision};
926 push @tmp, $p if $p =~ /^$::sha1_short$/o;
929 if (my $cur = ::verify_ref($self->refname.'^0')) {
932 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
933 while (my $p = shift @tmp) {
937 # MAXPARENT is defined to 16 in commit-tree.c:
941 die "r$log_entry->{revision}: No room for parents:\n\t",
942 join("\n\t", @tmp), "\n";
949 $self->ra->{url} . (length $self->{path} ? '/' . $self->{path} : '');
953 my ($self, $log_entry, @parents) = @_;
954 if (my $c = $self->rev_db_get($log_entry->{revision})) {
955 croak "$log_entry->{revision} = $c already exists! ",
956 "Why are we refetching it?\n";
958 my $author = $log_entry->{author};
959 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
960 : ($author, "$author\@".$self->ra->uuid));
961 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
962 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
963 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
965 my $tree = $log_entry->{tree};
966 if (!defined $tree) {
967 $tree = $self->tmp_index_do(sub {
968 command_oneline('write-tree') });
970 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
972 my @exec = ('git-commit-tree', $tree);
973 foreach ($self->get_commit_parents($log_entry, @parents)) {
974 push @exec, '-p', $_;
976 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
978 print $msg_fh $log_entry->{log} or croak $!;
979 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
980 $log_entry->{revision}, ' ',
981 $self->ra->uuid, "\n" or croak $!;
982 $msg_fh->flush == 0 or croak $!;
983 close $msg_fh or croak $!;
984 chomp(my $commit = do { local $/; <$out_fh> });
985 close $out_fh or croak $!;
988 if ($commit !~ /^$::sha1$/o) {
989 die "Failed to commit, invalid sha1: $commit\n";
992 command_noisy('update-ref',$self->refname, $commit);
993 $self->rev_db_set($log_entry->{revision}, $commit);
995 $self->{last_rev} = $log_entry->{revision};
996 $self->{last_commit} = $commit;
997 print "r$log_entry->{revision} = $commit\n";
1002 my ($self, $paths, $rev) = @_;
1003 my $ed = SVN::Git::Fetcher->new($self);
1004 my ($last_rev, @parents);
1005 if ($self->{last_commit}) {
1006 $last_rev = $self->{last_rev};
1007 $ed->{c} = $self->{last_commit};
1008 @parents = ($self->{last_commit});
1012 unless ($self->ra->gs_do_update($last_rev, $rev,
1013 $self->{path}, 1, $ed)) {
1014 die "SVN connection failed somewhere...\n";
1016 $self->make_log_entry($rev, \@parents, $ed);
1019 sub write_untracked {
1020 my ($self, $rev, $fh, $untracked) = @_;
1022 print $fh "r$rev\n" or croak $!;
1023 $h = $untracked->{empty};
1024 foreach (sort keys %$h) {
1025 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1026 print $fh " $act: ", uri_encode($_), "\n" or croak $!;
1027 warn "W: $act: $_\n";
1029 foreach my $t (qw/dir_prop file_prop/) {
1030 $h = $untracked->{$t} or next;
1031 foreach my $path (sort keys %$h) {
1032 my $ppath = $path eq '' ? '.' : $path;
1033 foreach my $prop (sort keys %{$h->{$path}}) {
1034 next if $SKIP_PROP{$prop};
1035 my $v = $h->{$path}->{$prop};
1038 uri_encode($ppath), ' ',
1039 uri_encode($prop), ' ',
1040 uri_encode($v), "\n"
1044 uri_encode($ppath), ' ',
1045 uri_encode($prop), "\n"
1051 foreach my $t (qw/absent_file absent_directory/) {
1052 $h = $untracked->{$t} or next;
1053 foreach my $parent (sort keys %$h) {
1054 foreach my $path (sort @{$h->{$parent}}) {
1056 uri_encode("$parent/$path"), "\n"
1058 warn "W: $t: $parent/$path ",
1059 "Insufficient permissions?\n";
1065 sub parse_svn_date {
1066 my $date = shift || return '+0000 1970-01-01 00:00:00';
1067 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1068 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1069 croak "Unable to parse date: $date\n";
1070 "+0000 $Y-$m-$d $H:$M:$S";
1075 if (!defined $author || length $author == 0) {
1076 $author = '(no author)';
1078 if (defined $::_authors && ! defined $::users{$author}) {
1079 die "Author: $author not defined in $::_authors file\n";
1084 sub make_log_entry {
1085 my ($self, $rev, $parents, $untracked) = @_;
1086 my $rp = $self->ra->rev_proplist($rev);
1087 my %log_entry = ( parents => $parents || [], revision => $rev,
1088 revprops => $rp, log => '');
1089 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1090 $self->write_untracked($rev, $un, $untracked);
1091 foreach (sort keys %$rp) {
1093 if (/^svn:(author|date|log)$/) {
1094 $log_entry{$1} = $v;
1096 print $un " rev_prop: ", uri_encode($_), ' ',
1097 uri_encode($v), "\n";
1100 close $un or croak $!;
1101 $log_entry{date} = parse_svn_date($log_entry{date});
1102 $log_entry{author} = check_author($log_entry{author});
1103 $log_entry{log} .= "\n";
1108 my ($self, @parents) = @_;
1109 my ($last_rev, $last_commit) = $self->last_rev_commit;
1110 my ($base, $head) = $self->parse_revision($last_rev);
1111 return if ($base > $head);
1112 if (defined $last_commit) {
1113 $self->assert_index_clean($last_commit);
1116 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
1117 my $err_handler = $SVN::Error::handler;
1118 $SVN::Error::handler = \&skip_unknown_revs;
1121 $self->ra->get_log([''], $min, $max, 0, 1, 1, sub {
1122 my ($paths, $rev, $author, $date, $log) = @_;
1123 push @revs, $rev });
1125 my $log_entry = $self->do_fetch(undef, $_);
1126 $self->do_git_commit($log_entry, @parents);
1128 last if $max >= $head;
1131 $max = $head if ($max > $head);
1133 $SVN::Error::handler = $err_handler;
1137 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1138 # TODO: enable and test optimized commits:
1139 if (0 && $rev == ($self->{last_rev} + 1)) {
1140 $log_entry->{revision} = $rev;
1141 $log_entry->{author} = $author;
1142 $self->do_git_commit($log_entry, "$rev=$tree");
1144 $self->fetch("$rev=$tree");
1149 my ($self, $tree) = (shift, shift);
1150 my $log_entry = ::get_commit_entry($tree);
1151 unless ($self->{last_rev}) {
1152 fatal("Must have an existing revision to commit\n");
1154 my $pool = SVN::Pool->new;
1155 my $ed = SVN::Git::Editor->new({ r => $self->{last_rev},
1156 ra => $self->ra->dup,
1157 svn_path => $self->ra->{svn_path}
1159 $self->ra->get_commit_editor(
1160 $log_entry->{log}, sub {
1161 $self->set_tree_cb($log_entry,
1165 my $mods = $ed->apply_diff($self->{last_commit}, $tree);
1167 print "No changes\nr$self->{last_rev} = $tree\n";
1172 sub skip_unknown_revs {
1174 my $errno = $err->apr_err();
1175 # Maybe the branch we're tracking didn't
1176 # exist when the repo started, so it's
1177 # not an error if it doesn't, just continue
1179 # Wonderfully consistent library, eh?
1180 # 160013 - svn:// and file://
1181 # 175002 - http(s)://
1182 # 175007 - http(s):// (this repo required authorization, too...)
1183 # More codes may be discovered later...
1184 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
1187 croak "Error from SVN, ($errno): ", $err->expanded_message,"\n";
1191 # Tie::File seems to be prone to offset errors if revisions get sparse,
1192 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1193 # one of my favorite modules is out :< Next up would be one of the DBM
1194 # modules, but I'm not sure which is most portable... So I'll just
1195 # go with something that's plain-text, but still capable of
1196 # being randomly accessed. So here's my ultra-simple fixed-width
1197 # database. All records are 40 characters + "\n", so it's easy to seek
1198 # to a revision: (41 * rev) is the byte offset.
1199 # A record of 40 0s denotes an empty revision.
1200 # And yes, it's still pretty fast (faster than Tie::File).
1203 my ($self, $rev, $commit) = @_;
1204 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1205 open my $fh, '+<', $self->{db_path} or croak $!;
1206 my $offset = $rev * 41;
1207 # assume that append is the common case:
1208 seek $fh, 0, 2 or croak $!;
1210 if ($pos < $offset) {
1211 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1214 seek $fh, $offset, 0 or croak $!;
1215 print $fh $commit,"\n" or croak $!;
1216 close $fh or croak $!;
1220 my ($self, $rev) = @_;
1222 my $offset = $rev * 41;
1223 open my $fh, '<', $self->{db_path} or croak $!;
1224 if (seek $fh, $offset, 0) {
1225 $ret = readline $fh;
1228 $ret = undef if ($ret =~ /^0{40}$/);
1231 close $fh or croak $!;
1236 my ($class, $repo_id, $ref_id, $path) = @_;
1237 unless (defined $repo_id && length $repo_id) {
1238 $repo_id = $Git::SVN::default_repo_id;
1240 unless (defined $ref_id && length $ref_id) {
1241 $_[2] = $ref_id = $repo_id;
1243 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1244 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1245 $_[3] = $path = '' unless (defined $path);
1246 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1248 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1253 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1257 package Git::SVN::Prompt;
1261 use vars qw/$_no_auth_cache $_username/;
1264 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1265 $may_save = undef if $_no_auth_cache;
1266 $default_username = $_username if defined $_username;
1267 if (defined $default_username && length $default_username) {
1268 if (defined $realm && length $realm) {
1269 print STDERR "Authentication realm: $realm\n";
1272 $cred->username($default_username);
1274 username($cred, $realm, $may_save, $pool);
1276 $cred->password(_read_password("Password for '" .
1277 $cred->username . "': ", $realm));
1278 $cred->may_save($may_save);
1279 $SVN::_Core::SVN_NO_ERROR;
1282 sub ssl_server_trust {
1283 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1284 $may_save = undef if $_no_auth_cache;
1285 print STDERR "Error validating server certificate for '$realm':\n";
1286 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1287 print STDERR " - The certificate is not issued by a trusted ",
1288 "authority. Use the\n",
1289 " fingerprint to validate the certificate manually!\n";
1291 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1292 print STDERR " - The certificate hostname does not match.\n";
1294 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1295 print STDERR " - The certificate is not yet valid.\n";
1297 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1298 print STDERR " - The certificate has expired.\n";
1300 if ($failures & $SVN::Auth::SSL::OTHER) {
1301 print STDERR " - The certificate has an unknown error.\n";
1304 "Certificate information:\n".
1305 " - Hostname: %s\n".
1306 " - Valid: from %s until %s\n".
1308 " - Fingerprint: %s\n",
1309 map $cert_info->$_, qw(hostname valid_from valid_until
1310 issuer_dname fingerprint);
1313 print STDERR $may_save ?
1314 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1315 "(R)eject or accept (t)emporarily? ";
1317 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1318 if ($choice =~ /^t$/i) {
1319 $cred->may_save(undef);
1320 } elsif ($choice =~ /^r$/i) {
1322 } elsif ($may_save && $choice =~ /^p$/i) {
1323 $cred->may_save($may_save);
1327 $cred->accepted_failures($failures);
1328 $SVN::_Core::SVN_NO_ERROR;
1331 sub ssl_client_cert {
1332 my ($cred, $realm, $may_save, $pool) = @_;
1333 $may_save = undef if $_no_auth_cache;
1334 print STDERR "Client certificate filename: ";
1336 chomp(my $filename = <STDIN>);
1337 $cred->cert_file($filename);
1338 $cred->may_save($may_save);
1339 $SVN::_Core::SVN_NO_ERROR;
1342 sub ssl_client_cert_pw {
1343 my ($cred, $realm, $may_save, $pool) = @_;
1344 $may_save = undef if $_no_auth_cache;
1345 $cred->password(_read_password("Password: ", $realm));
1346 $cred->may_save($may_save);
1347 $SVN::_Core::SVN_NO_ERROR;
1351 my ($cred, $realm, $may_save, $pool) = @_;
1352 $may_save = undef if $_no_auth_cache;
1353 if (defined $realm && length $realm) {
1354 print STDERR "Authentication realm: $realm\n";
1357 if (defined $_username) {
1358 $username = $_username;
1360 print STDERR "Username: ";
1362 chomp($username = <STDIN>);
1364 $cred->username($username);
1365 $cred->may_save($may_save);
1366 $SVN::_Core::SVN_NO_ERROR;
1369 sub _read_password {
1370 my ($prompt, $realm) = @_;
1371 print STDERR $prompt;
1373 require Term::ReadKey;
1374 Term::ReadKey::ReadMode('noecho');
1376 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1377 last if $key =~ /[\012\015]/; # \n\r
1380 Term::ReadKey::ReadMode('restore');
1390 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1397 $f =~ s/%([A-F0-9]{2})/chr hex($1)/ge;
1402 my ($path, $r0, $r1) = @_;
1403 return 1 if $r0 == $r1;
1405 # should be OK to use Pool here (r1 - r0) should be small
1406 $SVN->get_log([$path], $r0, $r1, 0, 0, 1, sub {$nr++});
1407 return 0 if ($nr > 1);
1411 sub libsvn_find_parent_branch {
1412 my ($paths, $rev, $author, $date, $log) = @_;
1413 my $svn_path = '/'.$SVN->{svn_path};
1415 # look for a parent from another branch:
1416 my $i = $paths->{$svn_path} or return;
1417 my $branch_from = $i->copyfrom_path or return;
1418 my $r = $i->copyfrom_rev;
1419 print STDERR "Found possible branch point: ",
1420 "$branch_from => $svn_path, $r\n";
1421 $branch_from =~ s#^/##;
1423 read_url_paths_all($l_map, '', "$GIT_DIR/svn");
1424 my $url = $SVN->{repos_root};
1425 defined $l_map->{$url} or return;
1426 my $id = $l_map->{$url}->{$branch_from};
1427 if (!defined $id && $_follow_parent) {
1428 print STDERR "Following parent: $branch_from\@$r\n";
1429 # auto create a new branch and follow it
1430 $id = basename($branch_from);
1431 $id .= '@'.$r if -r "$GIT_DIR/svn/$id";
1432 while (-r "$GIT_DIR/svn/$id") {
1433 # just grow a tail if we're not unique enough :x
1437 return unless defined $id;
1439 my ($r0, $parent) = find_rev_before($r,$id,1);
1440 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1441 defined(my $pid = fork) or croak $!;
1443 $GIT_SVN = $ENV{GIT_SVN_ID} = $id;
1445 $SVN_URL = "$url/$branch_from";
1448 # we can't assume SVN_URL exists at r+1:
1449 $_revision = "0:$r";
1455 ($r0, $parent) = find_rev_before($r,$id,1);
1457 return unless (defined $r0 && defined $parent);
1458 if (revisions_eq($branch_from, $r0, $r)) {
1459 unlink $GIT_SVN_INDEX;
1460 print STDERR "Found branch parent: ($GIT_SVN) $parent\n";
1461 command_noisy('read-tree', $parent);
1462 unless ($SVN->can_do_switch) {
1463 return _libsvn_new_tree($paths, $rev, $author, $date,
1466 # do_switch works with svn/trunk >= r22312, but that is not
1467 # included with SVN 1.4.2 (the latest version at the moment),
1468 # so we can't rely on it.
1469 my $ra = Git::SVN::Ra->new("$url/$branch_from");
1470 my $ed = SVN::Git::Fetcher->new({c => $parent, q => $_q });
1471 $ra->gs_do_switch($r0, $rev, '', 1, $SVN->{url}, $ed) or
1472 die "SVN connection failed somewhere...\n";
1473 return libsvn_log_entry($rev, $author, $date, $log, [$parent]);
1475 print STDERR "Nope, branch point not imported or unknown\n";
1479 sub _libsvn_new_tree {
1480 my ($paths, $rev, $author, $date, $log, $parents) = @_;
1481 my $ed = SVN::Git::Fetcher->new({q => $_q});
1482 unless ($SVN->gs_do_update($rev, $rev, '', 1, $ed)) {
1483 die "SVN connection failed somewhere...\n";
1485 libsvn_log_entry($rev, $author, $date, $log, $parents, $ed);
1489 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1490 $SVN::Node::dir.$SVN::Node::unknown.
1491 $SVN::Node::none.$SVN::Node::file.
1492 $SVN::Node::dir.$SVN::Node::unknown.
1493 $SVN::Auth::SSL::CNMISMATCH.
1494 $SVN::Auth::SSL::NOTYETVALID.
1495 $SVN::Auth::SSL::EXPIRED.
1496 $SVN::Auth::SSL::UNKNOWNCA.
1497 $SVN::Auth::SSL::OTHER;
1500 package SVN::Git::Fetcher;
1507 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1509 my ($class, $git_svn) = @_;
1510 my $self = SVN::Delta::Editor->new;
1511 bless $self, $class;
1512 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1513 if (length $git_svn->{path}) {
1514 $self->{path_strip} = qr/\Q$git_svn->{path}\E\/?/;
1516 $self->{empty} = {};
1517 $self->{dir_prop} = {};
1518 $self->{file_prop} = {};
1519 $self->{absent_dir} = {};
1520 $self->{absent_file} = {};
1521 ($self->{gui}, $self->{ctx}) = $git_svn->tmp_index_do(
1522 sub { command_input_pipe(qw/update-index -z --index-info/) } );
1523 require Digest::MD5;
1531 sub open_directory {
1532 my ($self, $path, $pb, $rev) = @_;
1537 my ($self, $path) = @_;
1538 $path =~ s!$self->{path_strip}!! if $self->{path_strip};
1543 my ($self, $path, $rev, $pb) = @_;
1544 my $gui = $self->{gui};
1546 my $gpath = $self->git_path($path);
1547 # remove entire directories.
1548 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1549 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1551 $self->{c}, '--', $gpath);
1554 print $gui '0 ',0 x 40,"\t",$_ or croak $!;
1555 print "\tD\t$_\n" unless $self->{q};
1557 print "\tD\t$gpath/\n" unless $self->{q};
1558 command_close_pipe($ls, $ctx);
1559 $self->{empty}->{$path} = 0
1561 print $gui '0 ',0 x 40,"\t",$gpath,"\0" or croak $!;
1562 print "\tD\t$gpath\n" unless $self->{q};
1568 my ($self, $path, $pb, $rev) = @_;
1569 my $gpath = $self->git_path($path);
1570 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1571 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1572 unless (defined $mode && defined $blob) {
1573 die "$path was not found in commit $self->{c} (r$rev)\n";
1575 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1576 pool => SVN::Pool->new, action => 'M' };
1580 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1581 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1582 delete $self->{empty}->{$dir};
1583 { path => $path, mode_a => 100644, mode_b => 100644,
1584 pool => SVN::Pool->new, action => 'A' };
1588 my ($self, $path, $cp_path, $cp_rev) = @_;
1589 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1590 delete $self->{empty}->{$dir};
1591 $self->{empty}->{$path} = 1;
1595 sub change_dir_prop {
1596 my ($self, $db, $prop, $value) = @_;
1597 $self->{dir_prop}->{$db->{path}} ||= {};
1598 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1602 sub absent_directory {
1603 my ($self, $path, $pb) = @_;
1604 $self->{absent_dir}->{$pb->{path}} ||= [];
1605 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1610 my ($self, $path, $pb) = @_;
1611 $self->{absent_file}->{$pb->{path}} ||= [];
1612 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1616 sub change_file_prop {
1617 my ($self, $fb, $prop, $value) = @_;
1618 if ($prop eq 'svn:executable') {
1619 if ($fb->{mode_b} != 120000) {
1620 $fb->{mode_b} = defined $value ? 100755 : 100644;
1622 } elsif ($prop eq 'svn:special') {
1623 $fb->{mode_b} = defined $value ? 120000 : 100644;
1625 $self->{file_prop}->{$fb->{path}} ||= {};
1626 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1631 sub apply_textdelta {
1632 my ($self, $fb, $exp) = @_;
1633 my $fh = IO::File->new_tmpfile;
1635 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1636 # (but $base does not,) so dup() it for reading in close_file
1637 open my $dup, '<&', $fh or croak $!;
1638 my $base = IO::File->new_tmpfile;
1639 $base->autoflush(1);
1641 defined (my $pid = fork) or croak $!;
1643 open STDOUT, '>&', $base or croak $!;
1644 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1645 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1651 seek $base, 0, 0 or croak $!;
1652 my $md5 = Digest::MD5->new;
1653 $md5->addfile($base);
1654 my $got = $md5->hexdigest;
1655 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1657 " got: $got\n" if ($got ne $exp);
1660 seek $base, 0, 0 or croak $!;
1662 $fb->{base} = $base;
1663 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1667 my ($self, $fb, $exp) = @_;
1669 my $path = $self->git_path($fb->{path});
1670 if (my $fh = $fb->{fh}) {
1671 seek($fh, 0, 0) or croak $!;
1672 my $md5 = Digest::MD5->new;
1674 my $got = $md5->hexdigest;
1675 die "Checksum mismatch: $path\n",
1676 "expected: $exp\n got: $got\n" if ($got ne $exp);
1677 seek($fh, 0, 0) or croak $!;
1678 if ($fb->{mode_b} == 120000) {
1679 read($fh, my $buf, 5) == 5 or croak $!;
1680 $buf eq 'link ' or die "$path has mode 120000",
1681 "but is not a link\n";
1683 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1685 open STDIN, '<&', $fh or croak $!;
1686 exec qw/git-hash-object -w --stdin/ or croak $!;
1688 chomp($hash = do { local $/; <$out> });
1689 close $out or croak $!;
1690 close $fh or croak $!;
1691 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1692 close $fb->{base} or croak $!;
1694 $hash = $fb->{blob} or die "no blob information\n";
1697 my $gui = $self->{gui};
1698 print $gui "$fb->{mode_b} $hash\t$path\0" or croak $!;
1699 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
1705 eval { command_close_pipe($self->{gui}, $self->{ctx}) };
1706 $self->SUPER::abort_edit(@_);
1711 command_close_pipe($self->{gui}, $self->{ctx});
1712 $self->{git_commit_ok} = 1;
1713 $self->SUPER::close_edit(@_);
1716 package SVN::Git::Editor;
1725 my $git_svn = shift;
1726 my $self = SVN::Delta::Editor->new(@_);
1727 bless $self, $class;
1728 foreach (qw/svn_path r ra/) {
1729 die "$_ required!\n" unless (defined $git_svn->{$_});
1730 $self->{$_} = $git_svn->{$_};
1732 $self->{pool} = SVN::Pool->new;
1733 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1735 require Digest::MD5;
1740 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1744 (defined $_[1] && length $_[1]) ? $_[1] : ''
1748 my ($self, $path) = @_;
1749 $self->{ra}->{url} . '/' . $self->repo_path($path);
1753 my ($self, $tree_b) = @_;
1754 my $rm = $self->{rm};
1755 delete $rm->{''}; # we never delete the url we're tracking
1758 foreach (keys %$rm) {
1759 my @d = split m#/#, $_;
1763 $c .= '/' . shift @d;
1767 delete $rm->{$self->{svn_path}};
1768 delete $rm->{''}; # we never delete the url we're tracking
1771 my ($fh, $ctx) = command_output_pipe(
1772 qw/ls-tree --name-only -r -z/, $tree_b);
1776 my @dn = split m#/#, $_;
1778 delete $rm->{join '/', @dn};
1785 command_close_pipe($fh, $ctx);
1787 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1788 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1789 $self->close_directory($bat->{$d}, $p);
1790 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
1791 print "\tD+\t$d/\n" unless $::_q;
1792 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1797 sub open_or_add_dir {
1798 my ($self, $full_path, $baton) = @_;
1799 my $t = $self->{ra}->check_path($full_path, $self->{r});
1800 if ($t == $SVN::Node::none) {
1801 return $self->add_directory($full_path, $baton,
1802 undef, -1, $self->{pool});
1803 } elsif ($t == $SVN::Node::dir) {
1804 return $self->open_directory($full_path, $baton,
1805 $self->{r}, $self->{pool});
1807 print STDERR "$full_path already exists in repository at ",
1808 "r$self->{r} and it is not a directory (",
1809 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1814 my ($self, $path) = @_;
1815 my $bat = $self->{bat};
1816 $path = $self->repo_path($path);
1817 return $bat->{''} unless (length $path);
1818 my @p = split m#/+#, $path;
1820 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
1823 $c .= '/' . shift @p;
1824 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
1830 my ($self, $m) = @_;
1831 my ($dir, $file) = split_path($m->{file_b});
1832 my $pbat = $self->ensure_path($dir);
1833 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1835 print "\tA\t$m->{file_b}\n" unless $::_q;
1836 $self->chg_file($fbat, $m);
1837 $self->close_file($fbat,undef,$self->{pool});
1841 my ($self, $m) = @_;
1842 my ($dir, $file) = split_path($m->{file_b});
1843 my $pbat = $self->ensure_path($dir);
1844 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1845 $self->url_path($m->{file_a}), $self->{r});
1846 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1847 $self->chg_file($fbat, $m);
1848 $self->close_file($fbat,undef,$self->{pool});
1852 my ($self, $path, $pbat) = @_;
1853 my $rpath = $self->repo_path($path);
1854 my ($dir, $file) = split_path($rpath);
1855 $self->{rm}->{$dir} = 1;
1856 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
1860 my ($self, $m) = @_;
1861 my ($dir, $file) = split_path($m->{file_b});
1862 my $pbat = $self->ensure_path($dir);
1863 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
1864 $self->url_path($m->{file_a}), $self->{r});
1865 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
1866 $self->chg_file($fbat, $m);
1867 $self->close_file($fbat,undef,$self->{pool});
1869 ($dir, $file) = split_path($m->{file_a});
1870 $pbat = $self->ensure_path($dir);
1871 $self->delete_entry($m->{file_a}, $pbat);
1875 my ($self, $m) = @_;
1876 my ($dir, $file) = split_path($m->{file_b});
1877 my $pbat = $self->ensure_path($dir);
1878 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
1879 $pbat,$self->{r},$self->{pool});
1880 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
1881 $self->chg_file($fbat, $m);
1882 $self->close_file($fbat,undef,$self->{pool});
1885 sub T { shift->M(@_) }
1887 sub change_file_prop {
1888 my ($self, $fbat, $pname, $pval) = @_;
1889 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
1893 my ($self, $fbat, $m) = @_;
1894 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
1895 $self->change_file_prop($fbat,'svn:executable','*');
1896 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
1897 $self->change_file_prop($fbat,'svn:executable',undef);
1899 my $fh = IO::File->new_tmpfile or croak $!;
1900 if ($m->{mode_b} =~ /^120/) {
1901 print $fh 'link ' or croak $!;
1902 $self->change_file_prop($fbat,'svn:special','*');
1903 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
1904 $self->change_file_prop($fbat,'svn:special',undef);
1906 defined(my $pid = fork) or croak $!;
1908 open STDOUT, '>&', $fh or croak $!;
1909 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
1913 $fh->flush == 0 or croak $!;
1914 seek $fh, 0, 0 or croak $!;
1916 my $md5 = Digest::MD5->new;
1917 $md5->addfile($fh) or croak $!;
1918 seek $fh, 0, 0 or croak $!;
1920 my $exp = $md5->hexdigest;
1921 my $pool = SVN::Pool->new;
1922 my $atd = $self->apply_textdelta($fbat, undef, $pool);
1923 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
1924 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
1927 close $fh or croak $!;
1931 my ($self, $m) = @_;
1932 my ($dir, $file) = split_path($m->{file_b});
1933 my $pbat = $self->ensure_path($dir);
1934 print "\tD\t$m->{file_b}\n" unless $::_q;
1935 $self->delete_entry($m->{file_b}, $pbat);
1940 my ($p,$bat) = ($self->{pool}, $self->{bat});
1941 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
1942 $self->close_directory($bat->{$_}, $p);
1944 $self->SUPER::close_edit($p);
1950 $self->SUPER::abort_edit($self->{pool});
1951 $self->{pool}->clear;
1954 # this drives the editor
1956 my ($self, $tree_a, $tree_b) = @_;
1957 my @diff_tree = qw(diff-tree -z -r);
1958 if ($::_cp_similarity) {
1959 push @diff_tree, "-C$::_cp_similarity";
1961 push @diff_tree, '-C';
1963 push @diff_tree, '--find-copies-harder' if $::_find_copies_harder;
1964 push @diff_tree, "-l$::_l" if defined $::_l;
1965 push @diff_tree, $tree_a, $tree_b;
1966 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1971 while (<$diff_fh>) {
1972 chomp $_; # this gets rid of the trailing "\0"
1973 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1974 $::sha1\s($::sha1)\s
1975 ([MTCRAD])\d*$/xo) {
1976 push @mods, { mode_a => $1, mode_b => $2,
1977 sha1_b => $3, chg => $4 };
1978 if ($4 =~ /^(?:C|R)$/) {
1983 } elsif ($state eq 'file_a') {
1984 my $x = $mods[$#mods] or croak "Empty array\n";
1985 if ($x->{chg} !~ /^(?:C|R)$/) {
1986 croak "Error parsing $_, $x->{chg}\n";
1990 } elsif ($state eq 'file_b') {
1991 my $x = $mods[$#mods] or croak "Empty array\n";
1992 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1993 croak "Error parsing $_, $x->{chg}\n";
1995 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1996 croak "Error parsing $_, $x->{chg}\n";
2001 croak "Error parsing $_\n";
2004 command_close_pipe($diff_fh, $ctx);
2007 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2008 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @mods) {
2010 if (defined $o{$f}) {
2013 fatal("Invalid change type: $f\n");
2016 $self->rmdirs($tree_b) if $::_rmdir;
2025 package Git::SVN::Ra;
2026 use vars qw/@ISA $config_dir/;
2029 my ($can_do_switch);
2033 # enforce temporary pool usage for some simple functions
2035 foreach (qw/get_latest_revnum rev_proplist get_file
2036 check_path get_dir get_uuid get_repos_root/) {
2039 my \$pool = SVN::Pool->new;
2040 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2042 wantarray ? \@ret : \$ret[0]; }\n";
2048 my ($class, $url) = @_;
2050 return $RA{$url} if $RA{$url};
2052 SVN::_Core::svn_config_ensure($config_dir, undef);
2053 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2054 SVN::Client::get_simple_provider(),
2055 SVN::Client::get_ssl_server_trust_file_provider(),
2056 SVN::Client::get_simple_prompt_provider(
2057 \&Git::SVN::Prompt::simple, 2),
2058 SVN::Client::get_ssl_client_cert_prompt_provider(
2059 \&Git::SVN::Prompt::ssl_client_cert, 2),
2060 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2061 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2062 SVN::Client::get_username_provider(),
2063 SVN::Client::get_ssl_server_trust_prompt_provider(
2064 \&Git::SVN::Prompt::ssl_server_trust),
2065 SVN::Client::get_username_prompt_provider(
2066 \&Git::SVN::Prompt::username, 2),
2068 my $config = SVN::Core::config_get_config($config_dir);
2069 my $self = SVN::Ra->new(url => $url, auth => $baton,
2071 pool => SVN::Pool->new,
2072 auth_provider_callbacks => $callbacks);
2073 $self->{svn_path} = $url;
2074 $self->{repos_root} = $self->get_repos_root;
2075 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
2076 $RA{$url} = bless $self, $class;
2080 # do not call the real DESTROY since we store ourselves in %RA
2085 my $dup = SVN::Ra->new(pool => SVN::Pool->new,
2086 map { $_ => $self->{$_} } qw/config url
2087 auth auth_provider_callbacks repos_root svn_path/);
2088 bless $dup, ref $self;
2092 my ($self, @args) = @_;
2093 my $pool = SVN::Pool->new;
2094 $args[4]-- if $args[4] && ! $::_follow_parent;
2095 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2096 my $ret = $self->SUPER::get_log(@args, $pool);
2101 sub get_commit_editor {
2102 my ($self, $log, $cb, $pool) = @_;
2103 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2104 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2109 $self->{uuid} ||= $self->get_uuid;
2113 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2114 my $pool = SVN::Pool->new;
2115 my $reporter = $self->do_update($rev_b, $path, $recurse,
2117 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2118 my $new = ($rev_a == $rev_b);
2119 $reporter->set_path('', $rev_a, $new, @lock, $pool);
2120 $reporter->finish_report($pool);
2122 $editor->{git_commit_ok};
2126 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2127 my $pool = SVN::Pool->new;
2128 my $reporter = $self->do_switch($rev_b, $path, $recurse,
2129 $url_b, $editor, $pool);
2130 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2131 $reporter->set_path($path, $rev_a, 0, @lock, $pool);
2132 $reporter->finish_report($pool);
2134 $editor->{git_commit_ok};
2139 unless (defined $can_do_switch) {
2140 my $pool = SVN::Pool->new;
2142 $self->do_switch(1, '', 0, $self->{url},
2143 SVN::Delta::Editor->new, $pool);
2148 $rep->abort_report($pool);
2156 package Git::SVN::Log;
2159 use POSIX qw/strftime/;
2160 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2161 %rusers $show_commit $incremental/;
2166 return 1 if defined $c->{r};
2167 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2168 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2169 my @log = command(qw/cat-file commit/, $c->{c});
2170 shift @log while ($log[0] ne "\n");
2172 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2174 (undef, $c->{r}, undef) = ::extract_metadata(
2175 (grep(/^git-svn-id: /, @log))[-1]);
2177 return defined $c->{r};
2183 $dcvar = 'color.diff';
2184 $dc = `git-config --get $dcvar`;
2186 # nothing at all; fallback to "diff.color"
2187 $dcvar = 'diff.color';
2188 $dc = `git-config --get $dcvar`;
2191 if ($dc eq 'auto') {
2193 $pc = `git-config --get color.pager`;
2195 # does not have it -- fallback to pager.color
2196 $pc = `git-config --bool --get pager.color`;
2199 $pc = `git-config --bool --get color.pager`;
2205 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2206 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2210 return 0 if $dc eq 'never';
2211 return 1 if $dc eq 'always';
2212 chomp($dc = `git-config --bool --get $dcvar`);
2213 return ($dc eq 'true');
2216 sub git_svn_log_cmd {
2217 my ($r_min, $r_max) = @_;
2218 my $gs = Git::SVN->_new;
2219 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2221 push @cmd, '-r' unless $non_recursive;
2222 push @cmd, qw/--raw --name-status/ if $verbose;
2223 push @cmd, '--color' if log_use_color();
2224 return @cmd unless defined $r_max;
2225 if ($r_max == $r_min) {
2226 push @cmd, '--max-count=1';
2227 if (my $c = $gs->rev_db_get($r_max)) {
2231 my ($c_min, $c_max);
2232 $c_max = $gs->rev_db_get($r_max);
2233 $c_min = $gs->rev_db_get($r_min);
2234 if (defined $c_min && defined $c_max) {
2235 if ($r_max > $r_max) {
2236 push @cmd, "$c_min..$c_max";
2238 push @cmd, "$c_max..$c_min";
2240 } elsif ($r_max > $r_min) {
2249 # adapted from pager.c
2251 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2252 if (!defined $pager) {
2254 } elsif (length $pager == 0 || $pager eq 'cat') {
2260 return unless -t *STDOUT;
2261 pipe my $rfd, my $wfd or return;
2262 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2264 open STDOUT, '>&', $wfd or
2265 ::fatal "Can't redirect to stdout: $!\n";
2268 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2269 $ENV{LESS} ||= 'FRSX';
2270 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2273 sub get_author_info {
2274 my ($dest, $author, $t, $tz) = @_;
2275 $author =~ s/(?:^\s*|\s*$)//g;
2276 $dest->{a_raw} = $author;
2279 $au = $rusers{$author} || undef;
2282 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2287 # Date::Parse isn't in the standard Perl distro :(
2288 if ($tz =~ s/^\+//) {
2289 $t += ::tz_to_s_offset($tz);
2290 } elsif ($tz =~ s/^\-//) {
2291 $t -= ::tz_to_s_offset($tz);
2293 $dest->{t_utc} = $t;
2296 sub process_commit {
2297 my ($c, $r_min, $r_max, $defer) = @_;
2298 if (defined $r_min && defined $r_max) {
2299 if ($r_min == $c->{r} && $r_min == $r_max) {
2303 return 1 if $r_min == $r_max;
2304 if ($r_min < $r_max) {
2305 # we need to reverse the print order
2306 return 0 if (defined $limit && --$limit < 0);
2310 if ($r_min != $r_max) {
2311 return 1 if ($r_min < $c->{r});
2312 return 1 if ($r_max > $c->{r});
2315 return 0 if (defined $limit && --$limit < 0);
2324 if (my $l = $c->{l}) {
2325 while ($l->[0] =~ /^\s*$/) { shift @$l }
2328 $l_fmt ||= 'A' . length($c->{r});
2329 print 'r',pack($l_fmt, $c->{r}),' | ';
2330 print "$c->{c} | " if $show_commit;
2333 show_commit_normal($c);
2337 sub show_commit_changed_paths {
2339 return unless $c->{changed};
2340 print "Changed paths:\n", @{$c->{changed}};
2343 sub show_commit_normal {
2345 print '-' x72, "\nr$c->{r} | ";
2346 print "$c->{c} | " if $show_commit;
2347 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2348 localtime($c->{t_utc})), ' | ';
2351 if (my $l = $c->{l}) {
2352 while ($l->[$#$l] eq "\n" && $#$l > 0
2353 && $l->[($#$l - 1)] eq "\n") {
2356 $nr_line = scalar @$l;
2358 print "1 line\n\n\n";
2360 if ($nr_line == 1) {
2361 $nr_line = '1 line';
2363 $nr_line .= ' lines';
2365 print $nr_line, "\n";
2366 show_commit_changed_paths($c);
2368 print $_ foreach @$l;
2372 show_commit_changed_paths($c);
2376 foreach my $x (qw/raw diff/) {
2379 print $_ foreach @{$c->{$x}}
2386 my ($r_min, $r_max);
2387 my $r_last = -1; # prevent dupes
2393 if (defined $::_revision) {
2394 if ($::_revision =~ /^(\d+):(\d+)$/) {
2395 ($r_min, $r_max) = ($1, $2);
2396 } elsif ($::_revision =~ /^\d+$/) {
2397 $r_min = $r_max = $::_revision;
2399 ::fatal "-r$::_revision is not supported, use ",
2400 "standard \'git log\' arguments instead\n";
2405 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2406 my $log = command_output_pipe(@args);
2409 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2411 if (/^${esc_color}commit ($::sha1_short)/o) {
2413 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2415 process_commit($c, $r_min, $r_max, \@k) or
2420 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2421 get_author_info($c, $1, $2, $3);
2422 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2424 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2425 push @{$c->{raw}}, $_;
2426 } elsif (/^${esc_color}[ACRMDT]\t/) {
2427 # we could add $SVN->{svn_path} here, but that requires
2428 # remote access at the moment (repo_path_split)...
2429 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2430 push @{$c->{changed}}, $_;
2431 } elsif (/^${esc_color}diff /o) {
2433 push @{$c->{diff}}, $_;
2435 push @{$c->{diff}}, $_;
2436 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2437 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2438 } elsif (s/^${esc_color} //o) {
2439 push @{$c->{l}}, $_;
2442 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2444 process_commit($c, $r_min, $r_max, \@k);
2450 process_commit($_, $r_min, $r_max) foreach reverse @k;
2454 print '-' x72,"\n" unless $incremental || $oneline;
2457 package Git::SVN::Migration;
2458 # these version numbers do NOT correspond to actual version numbers
2459 # of git nor git-svn. They are just relative.
2461 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2463 # v1 layout: .git/$id/info/url, refs/remotes/$id
2465 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2467 # v3 layout: .git/svn/$id, refs/remotes/$id
2468 # - info/url may remain for backwards compatibility
2469 # - this is what we migrate up to this layout automatically,
2470 # - this will be used by git svn init on single branches
2472 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2473 # - this is only created for newly multi-init-ed
2474 # repositories. Similar in spirit to the
2475 # --use-separate-remotes option in git-clone (now default)
2476 # - we do not automatically migrate to this (following
2477 # the example set by core git)
2481 use File::Path qw/mkpath/;
2482 use File::Basename qw/dirname basename/;
2483 use vars qw/$_minimize/;
2485 sub migrate_from_v0 {
2486 my $git_dir = $ENV{GIT_DIR};
2487 return undef unless -d $git_dir;
2488 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2492 my ($id, $orig_ref) = ($_, $_);
2493 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2494 next unless -f "$git_dir/$id/info/url";
2495 my $new_ref = "refs/remotes/$id";
2496 if (::verify_ref("$new_ref^0")) {
2497 print STDERR "W: $orig_ref is probably an old ",
2498 "branch used by an ancient version of ",
2500 "However, $new_ref also exists.\n",
2501 "We will not be able ",
2502 "to use this branch until this ",
2503 "ambiguity is resolved.\n";
2506 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2507 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2508 command_noisy('update-ref', $new_ref, $orig_ref);
2509 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2512 command_close_pipe($fh, $ctx);
2513 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2517 sub migrate_from_v1 {
2518 my $git_dir = $ENV{GIT_DIR};
2520 return $migrated unless -d $git_dir;
2521 my $svn_dir = "$git_dir/svn";
2523 # just in case somebody used 'svn' as their $id at some point...
2524 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2526 print STDERR "Migrating from a git-svn v1 layout...\n";
2528 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2529 "$svn_dir\n\t(required for this version ",
2530 "($::VERSION) of git-svn) does not. exist\n";
2531 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2534 next unless $x =~ s#^refs/remotes/##;
2536 next unless -f "$git_dir/$x/info/url";
2537 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2539 my $dn = dirname("$git_dir/svn/$x");
2540 mkpath([$dn]) unless -d $dn;
2541 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2542 mkpath(["$git_dir/svn/svn"]);
2543 print STDERR " - $git_dir/$x/info => ",
2544 "$git_dir/svn/$x/info\n";
2545 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2547 # don't worry too much about these, they probably
2548 # don't exist with repos this old (save for index,
2549 # and we can easily regenerate that)
2550 foreach my $f (qw/unhandled.log index .rev_db/) {
2551 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2554 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2555 rename "$git_dir/$x", "$git_dir/svn/$x" or
2560 command_close_pipe($fh, $ctx);
2561 print STDERR "Done migrating from a git-svn v1 layout\n";
2566 my ($l_map, $pfx, $path) = @_;
2568 foreach (<$path/*>) {
2569 if (-r "$_/info/url") {
2570 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2571 my $ref_id = $pfx . basename $_;
2572 my $url = ::file_to_s("$_/info/url");
2573 $l_map->{$ref_id} = $url;
2580 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2581 read_old_urls($l_map, $x, $_);
2585 sub migrate_from_v2 {
2586 my @cfg = command(qw/config -l/);
2587 return if grep /^svn-remote\..+\.url=/, @cfg;
2589 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2592 foreach my $ref_id (sort keys %l_map) {
2593 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2599 sub minimize_connections {
2600 my $r = Git::SVN::read_all_remotes();
2602 my $root_repos = {};
2603 foreach my $repo_id (keys %$r) {
2604 my $url = $r->{$repo_id}->{url} or next;
2605 my $fetch = $r->{$repo_id}->{fetch} or next;
2606 my $ra = Git::SVN::Ra->new($url);
2608 # skip existing cases where we already connect to the root
2609 if (($ra->{url} eq $ra->{repos_root}) ||
2610 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2612 $root_repos->{$ra->{url}} = $repo_id;
2616 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2617 my $root_path = $ra->{url};
2618 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2619 foreach my $path (keys %$fetch) {
2620 my $ref_id = $fetch->{$path};
2621 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2623 # make sure we can read when connecting to
2624 # a higher level of a repository
2625 my ($last_rev, undef) = $gs->last_rev_commit;
2626 if (!defined $last_rev) {
2628 $root_ra->get_latest_revnum;
2632 my $new = $root_path;
2633 $new .= length $path ? "/$path" : '';
2635 $root_ra->get_log([$new], $last_rev, $last_rev,
2639 $new_urls->{$ra->{repos_root}}->{$new} =
2640 { ref_id => $ref_id,
2641 old_repo_id => $repo_id,
2642 old_path => $path };
2647 foreach my $url (keys %$new_urls) {
2648 # see if we can re-use an existing [svn-remote "repo_id"]
2649 # instead of creating a(n ugly) new section:
2650 my $repo_id = $root_repos->{$url} ||
2651 Git::SVN::sanitize_remote_name($url);
2653 my $fetch = $new_urls->{$url};
2654 foreach my $path (keys %$fetch) {
2655 my $x = $fetch->{$path};
2656 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2657 my $pfx = "svn-remote.$x->{old_repo_id}";
2659 my $old_fetch = quotemeta("$x->{old_path}:".
2660 "refs/remotes/$x->{ref_id}");
2661 command_noisy(qw/repo-config --unset/,
2662 "$pfx.fetch", '^'. $old_fetch . '$');
2663 delete $r->{$x->{old_repo_id}}->
2664 {fetch}->{$x->{old_path}};
2665 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
2666 command_noisy(qw/repo-config --unset/,
2668 push @emptied, $x->{old_repo_id}
2673 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2674 "$ENV{GIT_DIR}/config";
2676 The following [svn-remote] sections in your config file ($file) are empty
2677 and can be safely removed:
2679 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2683 sub migration_check {
2687 minimize_connections() if $_minimize;
2694 $log_entry hashref as returned by libsvn_log_entry()
2696 log => 'whitespace-formatted log entry
2697 ', # trailing newline is preserved
2698 revision => '8', # integer
2699 date => '2004-02-24T17:01:44.108345Z', # commit date
2700 author => 'committer name'
2703 @mods = array of diff-index line hashes, each element represents one line
2704 of diff-index output
2706 diff-index line ($m hash)
2708 mode_a => first column of diff-index output, no leading ':',
2709 mode_b => second column of diff-index output,
2710 sha1_b => sha1sum of the final blob,
2711 chg => change type [MCRADT],
2712 file_a => original file name of a file (iff chg is 'C' or 'R')
2713 file_b => new/current file name of a file (any chg)
2717 # retval of read_url_paths{,_all}();
2719 # repository root url
2720 'https://svn.musicpd.org' => {
2721 # repository path # GIT_SVN_ID
2722 'mpd/trunk' => 'trunk',
2723 'mpd/tags/0.11.5' => 'tags/0.11.5',
2728 I don't trust the each() function on unless I created %hash myself
2729 because the internal iterator may not have started at base.