2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 $ENV{GIT_DIR} ||= '.git';
13 $Git::SVN::default_repo_id = 'svn';
14 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Log::TZ = $ENV{TZ};
18 $| = 1; # unbuffer STDOUT
20 sub fatal (@) { print STDERR @_; exit 1 }
21 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
24 if ($SVN::Core::VERSION lt '1.1.0') {
25 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
27 push @Git::SVN::Ra::ISA, 'SVN::Ra';
28 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
29 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
32 use File::Basename qw/dirname basename/;
33 use File::Path qw/mkpath/;
34 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
40 foreach (qw/command command_oneline command_noisy command_output_pipe
41 command_input_pipe command_close_pipe/) {
42 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
43 "*Git::SVN::Migration::$_ = ".
44 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
51 $sha1 = qr/[a-f\d]{40}/;
52 $sha1_short = qr/[a-f\d]{4,40}/;
53 my ($_stdin, $_help, $_edit,
57 $_merge, $_strategy, $_dry_run,
59 $Git::SVN::_follow_parent = 1;
60 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
61 'config-dir=s' => \$Git::SVN::Ra::config_dir,
62 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
63 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
64 'authors-file|A=s' => \$_authors,
65 'repack:i' => \$Git::SVN::_repack,
66 'no-metadata' => \$Git::SVN::_no_metadata,
68 'repack-flags|repack-args|repack-opts=s' =>
69 \$Git::SVN::_repack_flags,
72 my ($_trunk, $_tags, $_branches);
73 my %multi_opts = ( 'trunk|T=s' => \$_trunk,
74 'tags|t=s' => \$_tags,
75 'branches|b=s' => \$_branches );
76 my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
77 my %cmt_opts = ( 'edit|e' => \$_edit,
78 'rmdir' => \$SVN::Git::Editor::_rmdir,
79 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
80 'l=i' => \$SVN::Git::Editor::_rename_limit,
81 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
85 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
86 { 'revision|r=s' => \$_revision, %fc_opts } ],
87 init => [ \&cmd_init, "Initialize a repo for tracking" .
88 " (requires URL argument)",
90 dcommit => [ \&cmd_dcommit,
91 'Commit several diffs to merge with upstream',
92 { 'merge|m|M' => \$_merge,
93 'strategy|s=s' => \$_strategy,
94 'dry-run|n' => \$_dry_run,
95 %cmt_opts, %fc_opts } ],
96 'set-tree' => [ \&cmd_set_tree,
97 "Set an SVN repository to a git tree-ish",
98 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
99 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
100 { 'revision|r=i' => \$_revision } ],
101 'multi-init' => [ \&cmd_multi_init,
102 'Initialize multiple trees (like git-svnimport)',
103 { %multi_opts, %init_opts, %remote_opts,
104 'revision|r=i' => \$_revision,
105 'prefix=s' => \$_prefix,
107 'multi-fetch' => [ \&cmd_multi_fetch,
108 'Fetch multiple trees (like git-svnimport)',
110 'migrate' => [ sub { },
111 # no-op, we automatically run this anyways,
112 'Migrate configuration/metadata/layout from
113 previous versions of git-svn',
115 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
116 { 'limit=i' => \$Git::SVN::Log::limit,
117 'revision|r=s' => \$_revision,
118 'verbose|v' => \$Git::SVN::Log::verbose,
119 'incremental' => \$Git::SVN::Log::incremental,
120 'oneline' => \$Git::SVN::Log::oneline,
121 'show-commit' => \$Git::SVN::Log::show_commit,
122 'non-recursive' => \$Git::SVN::Log::non_recursive,
123 'authors-file|A=s' => \$_authors,
124 'color' => \$Git::SVN::Log::color,
125 'pager=s' => \$Git::SVN::Log::pager,
127 'commit-diff' => [ \&cmd_commit_diff,
128 'Commit a diff between two trees',
129 { 'message|m=s' => \$_message,
130 'file|F=s' => \$_file,
131 'revision|r=s' => \$_revision,
136 for (my $i = 0; $i < @ARGV; $i++) {
137 if (defined $cmd{$ARGV[$i]}) {
144 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
146 read_repo_config(\%opts);
147 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
148 'minimize-connections' => \$Git::SVN::Migration::_minimize,
149 'id|i=s' => \$Git::SVN::default_ref_id,
150 'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
151 exit 1 if (!$rv && $cmd ne 'log');
154 version() if $_version;
155 usage(1) unless defined $cmd;
156 load_authors() if $_authors;
157 unless ($cmd =~ /^(?:init|multi-init|commit-diff)$/) {
158 Git::SVN::Migration::migration_check();
160 Git::SVN::init_vars();
162 Git::SVN::verify_remotes_sanity();
163 $cmd{$cmd}->[0]->(@ARGV);
168 ####################### primary functions ######################
170 my $exit = shift || 0;
171 my $fd = $exit ? \*STDERR : \*STDOUT;
173 git-svn - bidirectional operations between a single Subversion tree and git
174 Usage: $0 <command> [options] [arguments]\n
176 print $fd "Available commands:\n" unless $cmd;
178 foreach (sort keys %cmd) {
179 next if $cmd && $cmd ne $_;
180 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
181 foreach (keys %{$cmd{$_}->[2]}) {
182 # prints out arguments as they should be passed:
183 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
184 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
186 split /\|/,$_)," $x\n";
190 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
191 arbitrary identifier if you're tracking multiple SVN branches/repositories in
192 one git repository and want to keep them separate. See git-svn(1) for more
199 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
204 unless (-d $ENV{GIT_DIR}) {
205 my @init_db = ('init');
206 push @init_db, "--template=$_template" if defined $_template;
207 push @init_db, "--shared" if defined $_shared;
208 command_noisy(@init_db);
213 my $url = shift or die "SVN repository location required " .
214 "as a command-line argument\n";
215 if (my $repo_path = shift) {
216 unless (-d $repo_path) {
217 mkpath([$repo_path]);
219 chdir $repo_path or croak $!;
220 $ENV{GIT_DIR} = $repo_path . "/.git";
224 Git::SVN->init($url);
229 die "Additional fetch arguments are no longer supported.\n",
230 "Use --follow-parent if you have moved/copied directories
233 my $gs = Git::SVN->new;
234 $gs->fetch(parse_revision_argument());
235 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
236 command_noisy(qw(update-ref refs/heads/master),
243 if ($_stdin || !@commits) {
244 print "Reading from stdin...\n";
247 if (/\b($sha1_short)\b/o) {
248 unshift @commits, $1;
253 foreach my $c (@commits) {
254 my @tmp = command('rev-parse',$c);
255 if (scalar @tmp == 1) {
257 } elsif (scalar @tmp > 1) {
258 push @revs, reverse(command('rev-list',@tmp));
260 fatal "Failed to rev-parse $c\n";
263 my $gs = Git::SVN->new;
264 my ($r_last, $cmt_last) = $gs->last_rev_commit;
266 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
267 fatal "There are new revisions that were fetched ",
268 "and need to be merged (or acknowledged) ",
269 "before committing.\nlast rev: $r_last\n",
270 " current: $gs->{last_rev}\n";
272 $gs->set_tree($_) foreach @revs;
273 print "Done committing ",scalar @revs," revisions to SVN\n";
278 my $gs = Git::SVN->new;
280 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
282 foreach my $d (reverse @refs) {
283 if (!verify_ref("$d~1")) {
285 "has no parent commit, and therefore ",
286 "nothing to diff against.\n",
287 "You should be working from a repository ",
288 "originally created by git-svn\n";
290 unless (defined $last_rev) {
291 (undef, $last_rev, undef) = cmt_metadata("$d~1");
292 unless (defined $last_rev) {
293 fatal "Unable to extract revision information ",
294 "from commit $d~1\n";
298 print "diff-tree $d~1 $d\n";
300 my %ed_opts = ( r => $last_rev,
301 log => get_commit_entry($d)->{log},
306 print "Committed r$_[0]\n";
307 $last_rev = $_[0]; },
308 svn_path => $gs->{path} );
309 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
310 print "No changes\n$d~1 == $d\n";
316 # we always want to rebase against the current HEAD, not any
317 # head that was passed to us
318 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
321 @finish = qw/rebase/;
322 push @finish, qw/--merge/ if $_merge;
323 push @finish, "--strategy=$_strategy" if $_strategy;
324 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
325 "using @finish:\n", "@diff";
327 print "No changes between current HEAD and ",
328 $gs->refname, "\nResetting to the latest ",
330 @finish = qw/reset --mixed/;
332 command_noisy(@finish, $gs->refname);
335 sub cmd_show_ignore {
336 my $gs = Git::SVN->new;
337 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
338 $gs->traverse_ignore(\*STDOUT, '', $r);
343 unless (defined $_trunk || defined $_branches || defined $_tags) {
347 $_prefix = '' unless defined $_prefix;
348 $url =~ s#/+$## if defined $url;
349 if (defined $_trunk) {
350 my $trunk_ref = $_prefix . 'trunk';
351 # try both old-style and new-style lookups:
352 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
354 my ($trunk_url, $trunk_path) =
355 complete_svn_url($url, $_trunk);
356 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
360 return unless defined $_branches || defined $_tags;
361 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
362 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
363 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
366 sub cmd_multi_fetch {
367 my $remotes = Git::SVN::read_all_remotes();
368 foreach my $repo_id (sort keys %$remotes) {
369 if ($remotes->{$repo_id}->{url} &&
370 $remotes->{$repo_id}->{fetch}) {
371 Git::SVN::fetch_all($repo_id, $remotes);
376 # this command is special because it requires no metadata
377 sub cmd_commit_diff {
378 my ($ta, $tb, $url) = @_;
379 my $usage = "Usage: $0 commit-diff -r<revision> ".
380 "<tree-ish> <tree-ish> [<URL>]\n";
381 fatal($usage) if (!defined $ta || !defined $tb);
384 my $gs = eval { Git::SVN->new };
386 fatal("Needed URL or usable git-svn --id in ",
387 "the command-line\n", $usage);
390 $svn_path = $gs->{path};
392 unless (defined $_revision) {
393 fatal("-r|--revision is a required argument\n", $usage);
395 if (defined $_message && defined $_file) {
396 fatal("Both --message/-m and --file/-F specified ",
397 "for the commit message.\n",
398 "I have no idea what you mean\n");
400 if (defined $_file) {
401 $_message = file_to_s($_file);
403 $_message ||= get_commit_entry($tb)->{log};
405 my $ra ||= Git::SVN::Ra->new($url);
406 $svn_path ||= $ra->{svn_path};
409 $r = $ra->get_latest_revnum;
410 } elsif ($r !~ /^\d+$/) {
411 die "revision argument: $r not understood by git-svn\n";
413 my %ed_opts = ( r => $r,
418 editor_cb => sub { print "Committed r$_[0]\n" },
419 svn_path => $svn_path );
420 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
421 print "No changes\n$ta == $tb\n";
425 ########################### utility functions #########################
427 sub parse_revision_argument {
428 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
429 return (undef, undef);
431 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
432 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
433 return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
434 return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
435 die "revision argument: $_revision not understood by git-svn\n",
436 "Try using the command-line svn client instead\n";
439 sub complete_svn_url {
440 my ($url, $path) = @_;
442 if ($path !~ m#^[a-z\+]+://#) {
443 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
444 fatal("E: '$path' is not a complete URL ",
445 "and a separate URL is not specified\n");
447 return ($url, $path);
452 sub complete_url_ls_init {
453 my ($ra, $repo_path, $switch, $pfx) = @_;
454 unless ($repo_path) {
455 print STDERR "W: $switch not specified\n";
458 $repo_path =~ s#/+$##;
459 if ($repo_path =~ m#^[a-z\+]+://#) {
460 $ra = Git::SVN::Ra->new($repo_path);
463 $repo_path =~ s#^/+##;
465 fatal("E: '$repo_path' is not a complete URL ",
466 "and a separate URL is not specified\n");
469 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
470 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
471 my $url = $ra->{url};
474 foreach my $d (sort keys %$dirent) {
475 next if ($dirent->{$d}->kind != $SVN::Node::dir);
476 my $path = "$repo_path/$d";
478 my $gs = eval { Git::SVN->new($ref) };
479 # don't try to init already existing refs
481 print "init $url/$path => $ref\n";
482 $gs = Git::SVN->init($url, $path, undef, $ref, 1);
485 $remote_id = $gs->{repo_id};
489 if (defined $remote_id) {
490 $remote_path = "$ra->{svn_path}/$repo_path/*";
491 $remote_path =~ s#/+#/#g;
492 $remote_path =~ s#^/##g;
493 my ($n) = ($switch =~ /^--(\w+)/);
494 if (length $pfx && $pfx !~ m#/$#) {
495 die "--prefix='$pfx' must have a trailing slash '/'\n";
497 command_noisy('config', "svn-remote.$remote_id.$n",
498 "$remote_path:refs/remotes/$pfx*");
504 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
508 sub get_tree_from_treeish {
510 # $treeish can be a symbolic ref, too:
511 my $type = command_oneline(qw/cat-file -t/, $treeish);
513 while ($type eq 'tag') {
514 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
516 if ($type eq 'commit') {
517 $expected = (grep /^tree /, command(qw/cat-file commit/,
519 ($expected) = ($expected =~ /^tree ($sha1)$/o);
520 die "Unable to get tree from $treeish\n" unless $expected;
521 } elsif ($type eq 'tree') {
522 $expected = $treeish;
524 die "$treeish is a $type, expected tree, tag or commit\n";
529 sub get_commit_entry {
530 my ($treeish) = shift;
531 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
532 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
533 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
534 open my $log_fh, '>', $commit_editmsg or croak $!;
536 my $type = command_oneline(qw/cat-file -t/, $treeish);
537 if ($type eq 'commit' || $type eq 'tag') {
538 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
543 $in_msg = 1 if (/^\s*$/);
544 } elsif (/^git-svn-id: /) {
545 # skip this for now, we regenerate the
546 # correct one on re-fetch anyways
547 # TODO: set *:merge properties or like...
549 print $log_fh $_ or croak $!;
552 command_close_pipe($msg_fh, $ctx);
554 close $log_fh or croak $!;
556 if ($_edit || ($type eq 'tree')) {
557 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
558 # TODO: strip out spaces, comments, like git-commit.sh
559 system($editor, $commit_editmsg);
561 rename $commit_editmsg, $commit_msg or croak $!;
562 open $log_fh, '<', $commit_msg or croak $!;
563 { local $/; chomp($log_entry{log} = <$log_fh>); }
564 close $log_fh or croak $!;
570 my ($str, $file, $mode) = @_;
571 open my $fd,'>',$file or croak $!;
572 print $fd $str,"\n" or croak $!;
573 close $fd or croak $!;
574 chmod ($mode &~ umask, $file) if (defined $mode);
579 open my $fd,'<',$file or croak "$!: file: $file\n";
582 close $fd or croak $!;
587 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
589 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
590 my $log = $cmd eq 'log';
593 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
594 my ($user, $name, $email) = ($1, $2, $3);
596 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
598 $users{$user} = [$name, $email];
601 close $authors or croak $!;
604 # convert GetOpt::Long specs for use by git-config
605 sub read_repo_config {
606 return unless -d $ENV{GIT_DIR};
608 foreach my $o (keys %$opts) {
610 my ($key) = ($o =~ /^([a-z\-]+)/);
612 my $arg = 'git-config';
613 $arg .= ' --int' if ($o =~ /[:=]i$/);
614 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
615 if (ref $v eq 'ARRAY') {
616 chomp(my @tmp = `$arg --get-all svn.$key`);
619 chomp(my $tmp = `$arg --get svn.$key`);
620 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
627 sub extract_metadata {
628 my $id = shift or return (undef, undef, undef);
629 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
631 if (!defined $rev || !$uuid || !$url) {
632 # some of the original repositories I made had
633 # identifiers like this:
634 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
636 return ($url, $rev, $uuid);
640 return extract_metadata((grep(/^git-svn-id: /,
641 command(qw/cat-file commit/, shift)))[-1]);
647 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
648 $_repack $_repack_flags/;
650 use File::Path qw/mkpath/;
651 use File::Copy qw/copy/;
655 # properties that we do not log:
658 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
659 svn:special svn:executable
660 svn:entry:committed-rev
661 svn:entry:last-author
663 svn:entry:committed-date/;
667 END { unlink keys %LOCKFILES if %LOCKFILES }
669 sub resolve_local_globs {
670 my ($url, $fetch, $glob_spec) = @_;
671 return unless defined $glob_spec;
672 my $ref = $glob_spec->{ref};
673 my $path = $glob_spec->{path};
674 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
675 next unless m#^refs/remotes/$ref->{regex}$#;
677 my $pathname = $path->full_path($p);
678 my $refname = $ref->full_path($p);
679 if (my $existing = $fetch->{$pathname}) {
680 if ($existing ne $refname) {
681 die "Refspec conflict:\n",
682 "existing: refs/remotes/$existing\n",
683 " globbed: refs/remotes/$refname\n";
685 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
686 $u =~ s!^\Q$url\E(/|$)!! or die
687 "refs/remotes/$refname: '$url' not found in '$u'\n";
688 if ($pathname ne $u) {
689 warn "W: Refspec glob conflict ",
690 "(ref: refs/remotes/$refname):\n",
691 "expected path: $pathname\n",
693 "Continuing ahead with $u\n";
697 $fetch->{$pathname} = $refname;
703 my ($repo_id, $remotes) = @_;
704 my $remote = $remotes->{$repo_id};
705 my $fetch = $remote->{fetch};
706 my $url = $remote->{url};
708 my $ra = Git::SVN::Ra->new($url);
709 my $uuid = $ra->uuid;
710 my $head = $ra->get_latest_revnum;
713 # read the max revs for wildcard expansion (branches/*, tags/*)
714 foreach my $t (qw/branches tags/) {
715 defined $remote->{$t} or next;
716 push @globs, $remote->{$t};
717 my $f = "$ENV{GIT_DIR}/svn/.$uuid.$t";
718 if (open my $fh, '<', $f) {
719 chomp(my $max_rev = <$fh>);
720 close $fh or die "Error closing $f: $!\n";
722 if ($max_rev !~ /^\d+$/) {
723 die "$max_rev (in $f) is not an integer!\n";
725 $remote->{$t}->{max_rev} = $max_rev;
726 $base = $max_rev if ($max_rev < $base);
730 foreach my $p (sort keys %$fetch) {
731 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
732 my $lr = $gs->rev_db_max;
734 $base = $lr if ($lr < $base);
738 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
741 sub read_all_remotes {
743 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
744 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
745 $r->{$1}->{fetch}->{$2} = $3;
746 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
747 $r->{$1}->{url} = $2;
748 } elsif (m!^(.+)\.(branches|tags)=
749 (.*):refs/remotes/(.+)\s*$/!x) {
750 my ($p, $g) = ($3, $4);
751 my $rs = $r->{$1}->{$2} = {
753 path => Git::SVN::GlobSpec->new($p),
754 ref => Git::SVN::GlobSpec->new($g) };
755 if (length($rs->{ref}->{right}) != 0) {
756 die "The '*' glob character must be the last ",
757 "character of '$g'\n";
765 if (defined $_repack) {
766 $_repack = 1000 if ($_repack <= 0);
767 $_repack_nr = $_repack;
768 $_repack_flags ||= '-d';
772 sub verify_remotes_sanity {
773 return unless -d $ENV{GIT_DIR};
775 foreach (command(qw/config -l/)) {
776 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
778 die "Remote ref refs/remote/$1 is tracked by",
779 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
780 "Please resolve this ambiguity in ",
781 "your git configuration file before ",
789 # we allow more chars than remotes2config.sh...
790 sub sanitize_remote_name {
792 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
796 sub find_existing_remote {
797 my ($url, $remotes) = @_;
799 foreach my $repo_id (keys %$remotes) {
800 my $u = $remotes->{$repo_id}->{url} or next;
802 $existing = $repo_id;
808 sub init_remote_config {
809 my ($self, $url, $no_write) = @_;
810 $url =~ s!/+$!!; # strip trailing slash
811 my $r = read_all_remotes();
812 my $existing = find_existing_remote($url, $r);
815 print STDERR "Using existing ",
816 "[svn-remote \"$existing\"]\n";
818 $self->{repo_id} = $existing;
820 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
821 $existing = find_existing_remote($min_url, $r);
824 print STDERR "Using existing ",
825 "[svn-remote \"$existing\"]\n";
827 $self->{repo_id} = $existing;
829 if ($min_url ne $url) {
831 print STDERR "Using higher level of URL: ",
832 "$url => $min_url\n";
834 my $old_path = $self->{path};
835 $self->{path} = $url;
836 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
837 if (length $old_path) {
838 $self->{path} .= "/$old_path";
845 # verify that we aren't overwriting anything:
847 command_oneline('config', '--get',
848 "svn-remote.$self->{repo_id}.url")
850 if ($orig_url && ($orig_url ne $url)) {
851 die "svn-remote.$self->{repo_id}.url already set: ",
852 "$orig_url\nwanted to set to: $url\n";
855 my ($xrepo_id, $xpath) = find_ref($self->refname);
856 if (defined $xpath) {
857 die "svn-remote.$xrepo_id.fetch already set to track ",
858 "$xpath:refs/remotes/", $self->refname, "\n";
861 command_noisy('config',
862 "svn-remote.$self->{repo_id}.url", $url);
863 command_noisy('config', '--add',
864 "svn-remote.$self->{repo_id}.fetch",
865 "$self->{path}:".$self->refname);
871 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
872 my $self = _new($class, $repo_id, $ref_id, $path);
874 $self->init_remote_config($url, $no_write);
881 foreach (command(qw/config -l/)) {
882 next unless m!^svn-remote\.(.+)\.fetch=
883 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
884 my ($repo_id, $path, $ref) = ($1, $2, $3);
885 if ($ref eq $ref_id) {
886 $path = '' if ($path =~ m#^\./?#);
887 return ($repo_id, $path);
890 (undef, undef, undef);
894 my ($class, $ref_id, $repo_id, $path) = @_;
895 if (defined $ref_id && !defined $repo_id && !defined $path) {
896 ($repo_id, $path) = find_ref($ref_id);
897 if (!defined $repo_id) {
898 die "Could not find a \"svn-remote.*.fetch\" key ",
899 "in the repository configuration matching: ",
900 "refs/remotes/$ref_id\n";
903 my $self = _new($class, $repo_id, $ref_id, $path);
904 if (!defined $self->{path} || !length $self->{path}) {
905 my $fetch = command_oneline('config', '--get',
906 "svn-remote.$repo_id.fetch",
907 ":refs/remotes/$ref_id\$") or
908 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
909 "\":refs/remotes/$ref_id\$\" in config\n";
910 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
912 $self->{url} = command_oneline('config', '--get',
913 "svn-remote.$repo_id.url") or
914 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
915 if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
921 sub refname { "refs/remotes/$_[0]->{ref_id}" }
925 Git::SVN::Ra->new($self->{url});
930 my $repos_root = $self->ra->{repos_root};
931 return $self->{path} if ($self->{url} eq $repos_root);
932 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
933 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
936 sub traverse_ignore {
937 my ($self, $fh, $path, $r) = @_;
940 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
942 $p =~ s#^\Q$ra->{svn_path}\E/##;
943 print $fh length $p ? "\n# $p\n" : "\n# /\n";
944 if (my $s = $props->{'svn:ignore'}) {
945 $s =~ s/[\r\n]+/\n/g;
947 if (length $p == 0) {
952 print $fh "/$p/$s\n";
955 foreach (sort keys %$dirent) {
956 next if $dirent->{$_}->kind != $SVN::Node::dir;
957 $self->traverse_ignore($fh, "$path/$_", $r);
961 sub last_rev { ($_[0]->last_rev_commit)[0] }
962 sub last_commit { ($_[0]->last_rev_commit)[1] }
964 # returns the newest SVN revision number and newest commit SHA1
965 sub last_rev_commit {
967 if (defined $self->{last_rev} && defined $self->{last_commit}) {
968 return ($self->{last_rev}, $self->{last_commit});
970 my $c = ::verify_ref($self->refname.'^0');
972 my $rev = (::cmt_metadata($c))[1];
974 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
978 my $offset = -41; # from tail
980 open my $fh, '<', $self->{db_path} or
981 croak "$self->{db_path} not readable: $!\n";
982 sysseek($fh, $offset, 2); # don't care for errors
983 sysread($fh, $rl, 41) == 41 or return (undef, undef);
985 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
987 sysseek($fh, $offset, 2); # don't care for errors
988 sysread($fh, $rl, 41) == 41 or return (undef, undef);
992 die "$self->{db_path} and ", $self->refname,
993 " inconsistent!:\n$c != $rl\n";
995 my $rev = sysseek($fh, 0, 1) or croak $!;
996 $rev = ($rev - 41) / 41;
997 close $fh or croak $!;
998 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1002 sub get_fetch_range {
1003 my ($self, $min, $max) = @_;
1004 $max ||= $self->ra->get_latest_revnum;
1005 $min ||= $self->rev_db_max;
1010 my ($self, $sub) = @_;
1011 my $old_index = $ENV{GIT_INDEX_FILE};
1012 $ENV{GIT_INDEX_FILE} = $self->{index};
1015 $ENV{GIT_INDEX_FILE} = $old_index;
1017 delete $ENV{GIT_INDEX_FILE};
1019 wantarray ? @ret : $ret[0];
1022 sub assert_index_clean {
1023 my ($self, $treeish) = @_;
1025 $self->tmp_index_do(sub {
1026 command_noisy('read-tree', $treeish) unless -e $self->{index};
1027 my $x = command_oneline('write-tree');
1028 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1029 /^tree ($::sha1)/mo);
1031 unlink $self->{index} or croak $!;
1032 command_noisy('read-tree', $treeish);
1034 $x = command_oneline('write-tree');
1036 ::fatal "trees ($treeish) $y != $x\n",
1037 "Something is seriously wrong...\n";
1042 sub get_commit_parents {
1043 my ($self, $log_entry) = @_;
1044 my (%seen, @ret, @tmp);
1045 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1046 if (my $ip = $self->{inject_parents}) {
1047 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1051 if (my $cur = ::verify_ref($self->refname.'^0')) {
1054 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1055 while (my $p = shift @tmp) {
1059 # MAXPARENT is defined to 16 in commit-tree.c:
1063 die "r$log_entry->{revision}: No room for parents:\n\t",
1064 join("\n\t", @tmp), "\n";
1071 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1075 my ($self, $log_entry) = @_;
1076 my $lr = $self->last_rev;
1077 if (defined $lr && $lr >= $log_entry->{revision}) {
1078 die "Last fetched revision of ", $self->refname,
1079 " was r$lr, but we are about to fetch: ",
1080 "r$log_entry->{revision}!\n";
1082 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1083 croak "$log_entry->{revision} = $c already exists! ",
1084 "Why are we refetching it?\n";
1086 my $author = $log_entry->{author};
1087 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1088 : ($author, "$author\@".$self->ra->uuid));
1089 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1090 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
1091 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1093 my $tree = $log_entry->{tree};
1094 if (!defined $tree) {
1095 $tree = $self->tmp_index_do(sub {
1096 command_oneline('write-tree') });
1098 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1100 my @exec = ('git-commit-tree', $tree);
1101 foreach ($self->get_commit_parents($log_entry)) {
1102 push @exec, '-p', $_;
1104 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1106 print $msg_fh $log_entry->{log} or croak $!;
1107 unless ($_no_metadata) {
1108 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1109 $log_entry->{revision}, ' ',
1110 $self->ra->uuid, "\n" or croak $!;
1112 $msg_fh->flush == 0 or croak $!;
1113 close $msg_fh or croak $!;
1114 chomp(my $commit = do { local $/; <$out_fh> });
1115 close $out_fh or croak $!;
1118 if ($commit !~ /^$::sha1$/o) {
1119 die "Failed to commit, invalid sha1: $commit\n";
1122 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1124 $self->{last_rev} = $log_entry->{revision};
1125 $self->{last_commit} = $commit;
1126 print "r$log_entry->{revision} = $commit ($self->{ref_id})\n";
1127 if (defined $_repack && (--$_repack_nr == 0)) {
1128 $_repack_nr = $_repack;
1129 # repack doesn't use any arguments with spaces in them, does it?
1130 print "Running git repack $_repack_flags ...\n";
1131 command_noisy('repack', split(/\s+/, $_repack_flags));
1132 print "Done repacking\n";
1138 my ($self, $paths, $r) = @_;
1139 return 1 if $self->{path} eq '';
1140 if (my $path = $paths->{"/$self->{path}"}) {
1141 return ($path->{action} eq 'D') ? 0 : 1;
1143 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1144 if (grep /$self->{path_regex}/, keys %$paths) {
1148 foreach (split m#/#, $self->{path}) {
1150 next unless ($paths->{$c} &&
1151 ($paths->{$c}->{action} =~ /^[AR]$/));
1152 if ($self->ra->check_path($self->{path}, $r) ==
1160 sub find_parent_branch {
1161 my ($self, $paths, $rev) = @_;
1162 return undef unless $_follow_parent;
1163 unless (defined $paths) {
1164 my $err_handler = $SVN::Error::handler;
1165 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1166 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1168 Git::SVN::Ra::dup_changed_paths($_[0]) });
1169 $SVN::Error::handler = $err_handler;
1171 return undef unless defined $paths;
1173 # look for a parent from another branch:
1174 my @b_path_components = split m#/#, $self->rel_path;
1175 my @a_path_components;
1177 while (@b_path_components) {
1178 $i = $paths->{'/'.join('/', @b_path_components)};
1179 last if $i && defined $i->{copyfrom_path};
1180 unshift(@a_path_components, pop(@b_path_components));
1182 return undef unless defined $i && defined $i->{copyfrom_path};
1183 my $branch_from = $i->{copyfrom_path};
1184 if (@a_path_components) {
1185 print STDERR "branch_from: $branch_from => ";
1186 $branch_from .= '/'.join('/', @a_path_components);
1187 print STDERR $branch_from, "\n";
1189 my $r = $i->{copyfrom_rev};
1190 my $repos_root = $self->ra->{repos_root};
1191 my $url = $self->ra->{url};
1192 my $new_url = $repos_root . $branch_from;
1193 print STDERR "Found possible branch point: ",
1194 "$new_url => ", $self->full_url, ", $r\n";
1195 $branch_from =~ s#^/##;
1196 my $remotes = read_all_remotes();
1198 foreach my $repo_id (keys %$remotes) {
1199 my $u = $remotes->{$repo_id}->{url} or next;
1201 my $fetch = $remotes->{$repo_id}->{fetch};
1202 foreach (qw/branches tags/) {
1203 resolve_local_globs($url, $fetch,
1204 $remotes->{$repo_id}->{$_});
1206 foreach my $f (keys %$fetch) {
1207 next if $f ne $branch_from;
1208 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1214 my $ref_id = $self->{ref_id};
1215 $ref_id =~ s/\@\d+$//;
1217 # just grow a tail if we're not unique enough :x
1218 $ref_id .= '-' while find_ref($ref_id);
1219 print STDERR "Initializing parent: $ref_id\n";
1220 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1222 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1223 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
1225 ($r0, $parent) = $gs->last_rev_commit;
1227 if (defined $r0 && defined $parent) {
1228 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1229 $self->assert_index_clean($parent);
1231 if ($self->ra->can_do_switch) {
1232 print STDERR "Following parent with do_switch\n";
1233 # do_switch works with svn/trunk >= r22312, but that
1234 # is not included with SVN 1.4.3 (the latest version
1235 # at the moment), so we can't rely on it
1236 $self->{last_commit} = $parent;
1237 $ed = SVN::Git::Fetcher->new($self);
1238 $gs->ra->gs_do_switch($r0, $rev, $gs,
1239 $self->full_url, $ed)
1240 or die "SVN connection failed somewhere...\n";
1242 print STDERR "Following parent with do_update\n";
1243 $ed = SVN::Git::Fetcher->new($self);
1244 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1245 or die "SVN connection failed somewhere...\n";
1247 print STDERR "Successfully followed parent\n";
1248 return $self->make_log_entry($rev, [$parent], $ed);
1254 my ($self, $paths, $rev) = @_;
1256 my ($last_rev, @parents);
1257 if (my $lc = $self->last_commit) {
1258 # we can have a branch that was deleted, then re-added
1259 # under the same name but copied from another path, in
1260 # which case we'll have multiple parents (we don't
1261 # want to break the original ref, nor lose copypath info):
1262 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1263 push @{$log_entry->{parents}}, $lc;
1266 $ed = SVN::Git::Fetcher->new($self);
1267 $last_rev = $self->{last_rev};
1272 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1275 $ed = SVN::Git::Fetcher->new($self);
1277 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1278 die "SVN connection failed somewhere...\n";
1280 $self->make_log_entry($rev, \@parents, $ed);
1284 my ($self, $ed) = @_;
1286 my $h = $ed->{empty};
1287 foreach (sort keys %$h) {
1288 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1289 push @out, " $act: " . uri_encode($_);
1290 warn "W: $act: $_\n";
1292 foreach my $t (qw/dir_prop file_prop/) {
1293 $h = $ed->{$t} or next;
1294 foreach my $path (sort keys %$h) {
1295 my $ppath = $path eq '' ? '.' : $path;
1296 foreach my $prop (sort keys %{$h->{$path}}) {
1297 next if $SKIP_PROP{$prop};
1298 my $v = $h->{$path}->{$prop};
1299 my $t_ppath_prop = "$t: " .
1300 uri_encode($ppath) . ' ' .
1303 push @out, " +$t_ppath_prop " .
1306 push @out, " -$t_ppath_prop";
1311 foreach my $t (qw/absent_file absent_directory/) {
1312 $h = $ed->{$t} or next;
1313 foreach my $parent (sort keys %$h) {
1314 foreach my $path (sort @{$h->{$parent}}) {
1315 push @out, " $t: " .
1316 uri_encode("$parent/$path");
1317 warn "W: $t: $parent/$path ",
1318 "Insufficient permissions?\n";
1325 sub parse_svn_date {
1326 my $date = shift || return '+0000 1970-01-01 00:00:00';
1327 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1328 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1329 croak "Unable to parse date: $date\n";
1330 "+0000 $Y-$m-$d $H:$M:$S";
1335 if (!defined $author || length $author == 0) {
1336 $author = '(no author)';
1338 if (defined $::_authors && ! defined $::users{$author}) {
1339 die "Author: $author not defined in $::_authors file\n";
1344 sub make_log_entry {
1345 my ($self, $rev, $parents, $ed) = @_;
1346 my $untracked = $self->get_untracked($ed);
1348 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1349 print $un "r$rev\n" or croak $!;
1350 print $un $_, "\n" foreach @$untracked;
1351 my %log_entry = ( parents => $parents || [], revision => $rev,
1354 my $logged = delete $self->{logged_rev_props};
1355 if (!$logged || $self->{-want_extra_revprops}) {
1356 my $rp = $self->ra->rev_proplist($rev);
1357 foreach (sort keys %$rp) {
1359 if (/^svn:(author|date|log)$/) {
1360 $log_entry{$1} = $v;
1362 print $un " rev_prop: ", uri_encode($_), ' ',
1363 uri_encode($v), "\n";
1367 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1369 close $un or croak $!;
1371 $log_entry{date} = parse_svn_date($log_entry{date});
1372 $log_entry{author} = check_author($log_entry{author});
1373 $log_entry{log} .= "\n";
1378 my ($self, $min_rev, $max_rev, @parents) = @_;
1379 my ($last_rev, $last_commit) = $self->last_rev_commit;
1380 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1381 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1385 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1386 $self->{inject_parents} = { $rev => $tree };
1387 $self->fetch(undef, undef);
1391 my ($self, $tree) = (shift, shift);
1392 my $log_entry = ::get_commit_entry($tree);
1393 unless ($self->{last_rev}) {
1394 fatal("Must have an existing revision to commit\n");
1396 my %ed_opts = ( r => $self->{last_rev},
1397 log => $log_entry->{log},
1399 tree_a => $self->{last_commit},
1402 $self->set_tree_cb($log_entry, $tree, @_) },
1403 svn_path => $self->{path} );
1404 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1405 print "No changes\nr$self->{last_rev} = $tree\n";
1411 print "Rebuilding $self->{db_path} ...\n";
1412 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1414 my $full_url = $self->full_url;
1416 while (<$rev_list>) {
1419 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1420 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1422 # ignore merges (from set-tree)
1423 next if (!defined $rev || !$uuid);
1425 # if we merged or otherwise started elsewhere, this is
1426 # how we break out of it
1427 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1428 ($full_url && $url && ($url ne $full_url))) {
1432 $svn_uuid ||= $uuid;
1434 $self->rev_db_set($rev, $c);
1435 print "r$rev = $c\n";
1437 command_close_pipe($rev_list, $ctx);
1438 print "Done rebuilding $self->{db_path}\n";
1442 # Tie::File seems to be prone to offset errors if revisions get sparse,
1443 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1444 # one of my favorite modules is out :< Next up would be one of the DBM
1445 # modules, but I'm not sure which is most portable... So I'll just
1446 # go with something that's plain-text, but still capable of
1447 # being randomly accessed. So here's my ultra-simple fixed-width
1448 # database. All records are 40 characters + "\n", so it's easy to seek
1449 # to a revision: (41 * rev) is the byte offset.
1450 # A record of 40 0s denotes an empty revision.
1451 # And yes, it's still pretty fast (faster than Tie::File).
1452 # These files are disposable unless --no-metadata is set
1455 my ($self, $rev, $commit, $update_ref) = @_;
1456 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1457 my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1460 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1461 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1463 $LOCKFILES{$db_lock} = 1;
1464 if ($_no_metadata) {
1465 copy($db, $db_lock) or die "rev_db_set(@_): ",
1467 "$db => $db_lock ($!)\n";
1469 rename $db, $db_lock or die "rev_db_set(@_): ",
1470 "Failed to rename: ",
1471 "$db => $db_lock ($!)\n";
1473 open my $fh, '+<', $db_lock or croak $!;
1474 my $offset = $rev * 41;
1475 # assume that append is the common case:
1476 seek $fh, 0, 2 or croak $!;
1478 if ($pos < $offset) {
1479 for (1 .. (($offset - $pos) / 41)) {
1480 print $fh (('0' x 40),"\n") or croak $!;
1483 seek $fh, $offset, 0 or croak $!;
1484 print $fh $commit,"\n" or croak $!;
1485 close $fh or croak $!;
1487 command_noisy('update-ref', '-m', "r$rev",
1488 $self->refname, $commit);
1490 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1491 "$db_lock => $db ($!)\n";
1492 delete $LOCKFILES{$db_lock};
1494 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1495 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1496 kill $sig, $$ if defined $sig;
1502 my @stat = stat $self->{db_path} or
1503 die "Couldn't stat $self->{db_path}: $!\n";
1504 ($stat[7] % 41) == 0 or
1505 die "$self->{db_path} inconsistent size:$stat[7]\n";
1506 my $max = $stat[7] / 41;
1507 (($max > 0) ? $max - 1 : 0);
1511 my ($self, $rev) = @_;
1513 my $offset = $rev * 41;
1514 open my $fh, '<', $self->{db_path} or croak $!;
1515 if (sysseek($fh, $offset, 0) == $offset) {
1516 my $read = sysread($fh, $ret, 40);
1517 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1519 close $fh or croak $!;
1523 sub find_rev_before {
1524 my ($self, $rev, $eq_ok) = @_;
1525 --$rev unless $eq_ok;
1527 if (my $c = $self->rev_db_get($rev)) {
1532 return (undef, undef);
1536 my ($class, $repo_id, $ref_id, $path) = @_;
1537 unless (defined $repo_id && length $repo_id) {
1538 $repo_id = $Git::SVN::default_repo_id;
1540 unless (defined $ref_id && length $ref_id) {
1541 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1543 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1544 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1545 $_[3] = $path = '' unless (defined $path);
1547 unless (-f "$dir/.rev_db") {
1548 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1549 close $fh or croak $!;
1551 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1553 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
1558 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1562 package Git::SVN::Prompt;
1566 use vars qw/$_no_auth_cache $_username/;
1569 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1570 $may_save = undef if $_no_auth_cache;
1571 $default_username = $_username if defined $_username;
1572 if (defined $default_username && length $default_username) {
1573 if (defined $realm && length $realm) {
1574 print STDERR "Authentication realm: $realm\n";
1577 $cred->username($default_username);
1579 username($cred, $realm, $may_save, $pool);
1581 $cred->password(_read_password("Password for '" .
1582 $cred->username . "': ", $realm));
1583 $cred->may_save($may_save);
1584 $SVN::_Core::SVN_NO_ERROR;
1587 sub ssl_server_trust {
1588 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1589 $may_save = undef if $_no_auth_cache;
1590 print STDERR "Error validating server certificate for '$realm':\n";
1591 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
1592 print STDERR " - The certificate is not issued by a trusted ",
1593 "authority. Use the\n",
1594 " fingerprint to validate the certificate manually!\n";
1596 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
1597 print STDERR " - The certificate hostname does not match.\n";
1599 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
1600 print STDERR " - The certificate is not yet valid.\n";
1602 if ($failures & $SVN::Auth::SSL::EXPIRED) {
1603 print STDERR " - The certificate has expired.\n";
1605 if ($failures & $SVN::Auth::SSL::OTHER) {
1606 print STDERR " - The certificate has an unknown error.\n";
1609 "Certificate information:\n".
1610 " - Hostname: %s\n".
1611 " - Valid: from %s until %s\n".
1613 " - Fingerprint: %s\n",
1614 map $cert_info->$_, qw(hostname valid_from valid_until
1615 issuer_dname fingerprint);
1618 print STDERR $may_save ?
1619 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1620 "(R)eject or accept (t)emporarily? ";
1622 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1623 if ($choice =~ /^t$/i) {
1624 $cred->may_save(undef);
1625 } elsif ($choice =~ /^r$/i) {
1627 } elsif ($may_save && $choice =~ /^p$/i) {
1628 $cred->may_save($may_save);
1632 $cred->accepted_failures($failures);
1633 $SVN::_Core::SVN_NO_ERROR;
1636 sub ssl_client_cert {
1637 my ($cred, $realm, $may_save, $pool) = @_;
1638 $may_save = undef if $_no_auth_cache;
1639 print STDERR "Client certificate filename: ";
1641 chomp(my $filename = <STDIN>);
1642 $cred->cert_file($filename);
1643 $cred->may_save($may_save);
1644 $SVN::_Core::SVN_NO_ERROR;
1647 sub ssl_client_cert_pw {
1648 my ($cred, $realm, $may_save, $pool) = @_;
1649 $may_save = undef if $_no_auth_cache;
1650 $cred->password(_read_password("Password: ", $realm));
1651 $cred->may_save($may_save);
1652 $SVN::_Core::SVN_NO_ERROR;
1656 my ($cred, $realm, $may_save, $pool) = @_;
1657 $may_save = undef if $_no_auth_cache;
1658 if (defined $realm && length $realm) {
1659 print STDERR "Authentication realm: $realm\n";
1662 if (defined $_username) {
1663 $username = $_username;
1665 print STDERR "Username: ";
1667 chomp($username = <STDIN>);
1669 $cred->username($username);
1670 $cred->may_save($may_save);
1671 $SVN::_Core::SVN_NO_ERROR;
1674 sub _read_password {
1675 my ($prompt, $realm) = @_;
1676 print STDERR $prompt;
1678 require Term::ReadKey;
1679 Term::ReadKey::ReadMode('noecho');
1681 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1682 last if $key =~ /[\012\015]/; # \n\r
1685 Term::ReadKey::ReadMode('restore');
1694 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1695 $SVN::Node::dir.$SVN::Node::unknown.
1696 $SVN::Node::none.$SVN::Node::file.
1697 $SVN::Node::dir.$SVN::Node::unknown.
1698 $SVN::Auth::SSL::CNMISMATCH.
1699 $SVN::Auth::SSL::NOTYETVALID.
1700 $SVN::Auth::SSL::EXPIRED.
1701 $SVN::Auth::SSL::UNKNOWNCA.
1702 $SVN::Auth::SSL::OTHER;
1705 package SVN::Git::Fetcher;
1713 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
1715 my ($class, $git_svn) = @_;
1716 my $self = SVN::Delta::Editor->new;
1717 bless $self, $class;
1718 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
1719 $self->{empty} = {};
1720 $self->{dir_prop} = {};
1721 $self->{file_prop} = {};
1722 $self->{absent_dir} = {};
1723 $self->{absent_file} = {};
1724 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
1728 sub set_path_strip {
1729 my ($self, $path) = @_;
1730 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
1737 sub open_directory {
1738 my ($self, $path, $pb, $rev) = @_;
1743 my ($self, $path) = @_;
1744 if ($self->{path_strip}) {
1745 $path =~ s!$self->{path_strip}!! or
1746 die "Failed to strip path '$path' ($self->{path_strip})\n";
1752 my ($self, $path, $rev, $pb) = @_;
1754 my $gpath = $self->git_path($path);
1755 return undef if ($gpath eq '');
1757 # remove entire directories.
1758 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
1759 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1761 $self->{c}, '--', $gpath);
1765 $self->{gii}->remove($_);
1766 print "\tD\t$_\n" unless $::_q;
1768 print "\tD\t$gpath/\n" unless $::_q;
1769 command_close_pipe($ls, $ctx);
1770 $self->{empty}->{$path} = 0
1772 $self->{gii}->remove($gpath);
1773 print "\tD\t$gpath\n" unless $::_q;
1779 my ($self, $path, $pb, $rev) = @_;
1780 my $gpath = $self->git_path($path);
1781 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
1782 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
1783 unless (defined $mode && defined $blob) {
1784 die "$path was not found in commit $self->{c} (r$rev)\n";
1786 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
1787 pool => SVN::Pool->new, action => 'M' };
1791 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
1792 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1793 delete $self->{empty}->{$dir};
1794 { path => $path, mode_a => 100644, mode_b => 100644,
1795 pool => SVN::Pool->new, action => 'A' };
1799 my ($self, $path, $cp_path, $cp_rev) = @_;
1800 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1801 delete $self->{empty}->{$dir};
1802 $self->{empty}->{$path} = 1;
1806 sub change_dir_prop {
1807 my ($self, $db, $prop, $value) = @_;
1808 $self->{dir_prop}->{$db->{path}} ||= {};
1809 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1813 sub absent_directory {
1814 my ($self, $path, $pb) = @_;
1815 $self->{absent_dir}->{$pb->{path}} ||= [];
1816 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1821 my ($self, $path, $pb) = @_;
1822 $self->{absent_file}->{$pb->{path}} ||= [];
1823 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1827 sub change_file_prop {
1828 my ($self, $fb, $prop, $value) = @_;
1829 if ($prop eq 'svn:executable') {
1830 if ($fb->{mode_b} != 120000) {
1831 $fb->{mode_b} = defined $value ? 100755 : 100644;
1833 } elsif ($prop eq 'svn:special') {
1834 $fb->{mode_b} = defined $value ? 120000 : 100644;
1836 $self->{file_prop}->{$fb->{path}} ||= {};
1837 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
1842 sub apply_textdelta {
1843 my ($self, $fb, $exp) = @_;
1844 my $fh = IO::File->new_tmpfile;
1846 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1847 # (but $base does not,) so dup() it for reading in close_file
1848 open my $dup, '<&', $fh or croak $!;
1849 my $base = IO::File->new_tmpfile;
1850 $base->autoflush(1);
1852 defined (my $pid = fork) or croak $!;
1854 open STDOUT, '>&', $base or croak $!;
1855 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1856 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1862 seek $base, 0, 0 or croak $!;
1863 my $md5 = Digest::MD5->new;
1864 $md5->addfile($base);
1865 my $got = $md5->hexdigest;
1866 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1868 " got: $got\n" if ($got ne $exp);
1871 seek $base, 0, 0 or croak $!;
1873 $fb->{base} = $base;
1874 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1878 my ($self, $fb, $exp) = @_;
1880 my $path = $self->git_path($fb->{path});
1881 if (my $fh = $fb->{fh}) {
1882 seek($fh, 0, 0) or croak $!;
1883 my $md5 = Digest::MD5->new;
1885 my $got = $md5->hexdigest;
1886 die "Checksum mismatch: $path\n",
1887 "expected: $exp\n got: $got\n" if ($got ne $exp);
1888 seek($fh, 0, 0) or croak $!;
1889 if ($fb->{mode_b} == 120000) {
1890 read($fh, my $buf, 5) == 5 or croak $!;
1891 $buf eq 'link ' or die "$path has mode 120000",
1892 "but is not a link\n";
1894 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1896 open STDIN, '<&', $fh or croak $!;
1897 exec qw/git-hash-object -w --stdin/ or croak $!;
1899 chomp($hash = do { local $/; <$out> });
1900 close $out or croak $!;
1901 close $fh or croak $!;
1902 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1903 close $fb->{base} or croak $!;
1905 $hash = $fb->{blob} or die "no blob information\n";
1908 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
1909 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
1915 $self->{nr} = $self->{gii}->{nr};
1916 delete $self->{gii};
1917 $self->SUPER::abort_edit(@_);
1922 $self->{git_commit_ok} = 1;
1923 $self->{nr} = $self->{gii}->{nr};
1924 delete $self->{gii};
1925 $self->SUPER::close_edit(@_);
1928 package SVN::Git::Editor;
1929 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
1937 my ($class, $opts) = @_;
1938 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1939 die "$_ required!\n" unless (defined $opts->{$_});
1942 my $pool = SVN::Pool->new;
1943 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1944 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1947 # $opts->{ra} functions should not be used after this:
1948 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
1949 $opts->{editor_cb}, $pool);
1950 my $self = SVN::Delta::Editor->new(@ce, $pool);
1951 bless $self, $class;
1952 foreach (qw/svn_path r tree_a tree_b/) {
1953 $self->{$_} = $opts->{$_};
1955 $self->{url} = $opts->{ra}->{url};
1956 $self->{mods} = $mods;
1957 $self->{types} = $types;
1958 $self->{pool} = $pool;
1959 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1961 $self->{path_prefix} = length $self->{svn_path} ?
1962 "$self->{svn_path}/" : '';
1967 my ($tree_a, $tree_b) = @_;
1968 my @diff_tree = qw(diff-tree -z -r);
1969 if ($_cp_similarity) {
1970 push @diff_tree, "-C$_cp_similarity";
1972 push @diff_tree, '-C';
1974 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1975 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
1976 push @diff_tree, $tree_a, $tree_b;
1977 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1981 while (<$diff_fh>) {
1982 chomp $_; # this gets rid of the trailing "\0"
1983 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1984 $::sha1\s($::sha1)\s
1985 ([MTCRAD])\d*$/xo) {
1986 push @mods, { mode_a => $1, mode_b => $2,
1987 sha1_b => $3, chg => $4 };
1988 if ($4 =~ /^(?:C|R)$/) {
1993 } elsif ($state eq 'file_a') {
1994 my $x = $mods[$#mods] or croak "Empty array\n";
1995 if ($x->{chg} !~ /^(?:C|R)$/) {
1996 croak "Error parsing $_, $x->{chg}\n";
2000 } elsif ($state eq 'file_b') {
2001 my $x = $mods[$#mods] or croak "Empty array\n";
2002 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2003 croak "Error parsing $_, $x->{chg}\n";
2005 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2006 croak "Error parsing $_, $x->{chg}\n";
2011 croak "Error parsing $_\n";
2014 command_close_pipe($diff_fh, $ctx);
2018 sub check_diff_paths {
2019 my ($ra, $pfx, $rev, $mods) = @_;
2021 $pfx .= '/' if length $pfx;
2023 sub type_diff_paths {
2024 my ($ra, $types, $path, $rev) = @_;
2025 my @p = split m#/+#, $path;
2027 unless (defined $types->{$c}) {
2028 $types->{$c} = $ra->check_path($c, $rev);
2031 $c .= '/' . shift @p;
2032 next if defined $types->{$c};
2033 $types->{$c} = $ra->check_path($c, $rev);
2037 foreach my $m (@$mods) {
2038 foreach my $f (qw/file_a file_b/) {
2039 next unless defined $m->{$f};
2040 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2041 if (length $pfx.$dir && ! defined $types{$dir}) {
2042 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2050 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2054 my ($self, $path) = @_;
2055 $self->{path_prefix}.(defined $path ? $path : '');
2059 my ($self, $path) = @_;
2060 $self->{url} . '/' . $self->repo_path($path);
2065 my $rm = $self->{rm};
2066 delete $rm->{''}; # we never delete the url we're tracking
2069 foreach (keys %$rm) {
2070 my @d = split m#/#, $_;
2074 $c .= '/' . shift @d;
2078 delete $rm->{$self->{svn_path}};
2079 delete $rm->{''}; # we never delete the url we're tracking
2082 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2087 my @dn = split m#/#, $_;
2089 delete $rm->{join '/', @dn};
2096 command_close_pipe($fh, $ctx);
2098 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2099 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2100 $self->close_directory($bat->{$d}, $p);
2101 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2102 print "\tD+\t$d/\n" unless $::_q;
2103 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2108 sub open_or_add_dir {
2109 my ($self, $full_path, $baton) = @_;
2110 my $t = $self->{types}->{$full_path};
2112 die "$full_path not known in r$self->{r} or we have a bug!\n";
2114 if ($t == $SVN::Node::none) {
2115 return $self->add_directory($full_path, $baton,
2116 undef, -1, $self->{pool});
2117 } elsif ($t == $SVN::Node::dir) {
2118 return $self->open_directory($full_path, $baton,
2119 $self->{r}, $self->{pool});
2121 print STDERR "$full_path already exists in repository at ",
2122 "r$self->{r} and it is not a directory (",
2123 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2128 my ($self, $path) = @_;
2129 my $bat = $self->{bat};
2130 my $repo_path = $self->repo_path($path);
2131 return $bat->{''} unless (length $repo_path);
2132 my @p = split m#/+#, $repo_path;
2134 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2137 $c .= '/' . shift @p;
2138 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2144 my ($self, $m) = @_;
2145 my ($dir, $file) = split_path($m->{file_b});
2146 my $pbat = $self->ensure_path($dir);
2147 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2149 print "\tA\t$m->{file_b}\n" unless $::_q;
2150 $self->chg_file($fbat, $m);
2151 $self->close_file($fbat,undef,$self->{pool});
2155 my ($self, $m) = @_;
2156 my ($dir, $file) = split_path($m->{file_b});
2157 my $pbat = $self->ensure_path($dir);
2158 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2159 $self->url_path($m->{file_a}), $self->{r});
2160 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2161 $self->chg_file($fbat, $m);
2162 $self->close_file($fbat,undef,$self->{pool});
2166 my ($self, $path, $pbat) = @_;
2167 my $rpath = $self->repo_path($path);
2168 my ($dir, $file) = split_path($rpath);
2169 $self->{rm}->{$dir} = 1;
2170 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2174 my ($self, $m) = @_;
2175 my ($dir, $file) = split_path($m->{file_b});
2176 my $pbat = $self->ensure_path($dir);
2177 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2178 $self->url_path($m->{file_a}), $self->{r});
2179 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2180 $self->chg_file($fbat, $m);
2181 $self->close_file($fbat,undef,$self->{pool});
2183 ($dir, $file) = split_path($m->{file_a});
2184 $pbat = $self->ensure_path($dir);
2185 $self->delete_entry($m->{file_a}, $pbat);
2189 my ($self, $m) = @_;
2190 my ($dir, $file) = split_path($m->{file_b});
2191 my $pbat = $self->ensure_path($dir);
2192 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2193 $pbat,$self->{r},$self->{pool});
2194 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2195 $self->chg_file($fbat, $m);
2196 $self->close_file($fbat,undef,$self->{pool});
2199 sub T { shift->M(@_) }
2201 sub change_file_prop {
2202 my ($self, $fbat, $pname, $pval) = @_;
2203 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2207 my ($self, $fbat, $m) = @_;
2208 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2209 $self->change_file_prop($fbat,'svn:executable','*');
2210 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2211 $self->change_file_prop($fbat,'svn:executable',undef);
2213 my $fh = IO::File->new_tmpfile or croak $!;
2214 if ($m->{mode_b} =~ /^120/) {
2215 print $fh 'link ' or croak $!;
2216 $self->change_file_prop($fbat,'svn:special','*');
2217 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2218 $self->change_file_prop($fbat,'svn:special',undef);
2220 defined(my $pid = fork) or croak $!;
2222 open STDOUT, '>&', $fh or croak $!;
2223 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2227 $fh->flush == 0 or croak $!;
2228 seek $fh, 0, 0 or croak $!;
2230 my $md5 = Digest::MD5->new;
2231 $md5->addfile($fh) or croak $!;
2232 seek $fh, 0, 0 or croak $!;
2234 my $exp = $md5->hexdigest;
2235 my $pool = SVN::Pool->new;
2236 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2237 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2238 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2241 close $fh or croak $!;
2245 my ($self, $m) = @_;
2246 my ($dir, $file) = split_path($m->{file_b});
2247 my $pbat = $self->ensure_path($dir);
2248 print "\tD\t$m->{file_b}\n" unless $::_q;
2249 $self->delete_entry($m->{file_b}, $pbat);
2254 my ($p,$bat) = ($self->{pool}, $self->{bat});
2255 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2256 $self->close_directory($bat->{$_}, $p);
2258 $self->SUPER::close_edit($p);
2264 $self->SUPER::abort_edit($self->{pool});
2269 $self->SUPER::DESTROY(@_);
2270 $self->{pool}->clear;
2273 # this drives the editor
2276 my $mods = $self->{mods};
2277 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2278 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2280 if (defined $o{$f}) {
2283 fatal("Invalid change type: $f\n");
2286 $self->rmdirs if $_rmdir;
2292 return scalar @$mods;
2295 package Git::SVN::Ra;
2296 use vars qw/@ISA $config_dir/;
2299 my ($can_do_switch);
2303 # enforce temporary pool usage for some simple functions
2305 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2308 my \$pool = SVN::Pool->new;
2309 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2311 wantarray ? \@ret : \$ret[0]; }\n";
2314 # get_dir needs $pool held in cache for dirents to work,
2315 # check_path is cacheable and rev_proplist is close enough
2317 foreach (qw/check_path get_dir rev_proplist/) {
2318 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2321 my \$k = join(\"\\0\", \@_);
2322 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2323 return wantarray ? \@\$x : \$x->[0];
2325 my \$pool = SVN::Pool->new;
2326 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2327 if (\$r != \$${_}_rev) {
2328 \%${_}_cache = ( pool => [] );
2331 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2332 push \@{\$${_}_cache{pool}}, \$pool;
2333 wantarray ? \@ret : \$ret[0]; }\n";
2340 my ($class, $url) = @_;
2342 return $RA if ($RA && $RA->{url} eq $url);
2344 SVN::_Core::svn_config_ensure($config_dir, undef);
2345 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2346 SVN::Client::get_simple_provider(),
2347 SVN::Client::get_ssl_server_trust_file_provider(),
2348 SVN::Client::get_simple_prompt_provider(
2349 \&Git::SVN::Prompt::simple, 2),
2350 SVN::Client::get_ssl_client_cert_prompt_provider(
2351 \&Git::SVN::Prompt::ssl_client_cert, 2),
2352 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2353 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2354 SVN::Client::get_username_provider(),
2355 SVN::Client::get_ssl_server_trust_prompt_provider(
2356 \&Git::SVN::Prompt::ssl_server_trust),
2357 SVN::Client::get_username_prompt_provider(
2358 \&Git::SVN::Prompt::username, 2),
2360 my $config = SVN::Core::config_get_config($config_dir);
2361 my $self = SVN::Ra->new(url => $url, auth => $baton,
2363 pool => SVN::Pool->new,
2364 auth_provider_callbacks => $callbacks);
2365 $self->{svn_path} = $url;
2366 $self->{repos_root} = $self->get_repos_root;
2367 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2368 $RA = bless $self, $class;
2372 # do not call the real DESTROY since we store ourselves in $RA
2376 my ($self, @args) = @_;
2377 my $pool = SVN::Pool->new;
2378 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2379 my $ret = $self->SUPER::get_log(@args, $pool);
2384 sub get_commit_editor {
2385 my ($self, $log, $cb, $pool) = @_;
2386 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2387 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2392 $self->{uuid} ||= $self->get_uuid;
2396 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2397 my $new = ($rev_a == $rev_b);
2398 my $path = $gs->{path};
2400 my $pool = SVN::Pool->new;
2401 $editor->set_path_strip($path);
2402 my (@pc) = split m#/#, $path;
2403 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2405 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2407 # Since we can't rely on svn_ra_reparent being available, we'll
2408 # just have to do some magic with set_path to make it so
2409 # we only want a partial path.
2411 my $final = join('/', @pc);
2413 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2414 $sp .= '/' if length $sp;
2417 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2419 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2421 $reporter->finish_report($pool);
2423 $editor->{git_commit_ok};
2426 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2427 # svn_ra_reparent didn't work before 1.4)
2429 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2430 my $path = $gs->{path};
2431 my $pool = SVN::Pool->new;
2433 my $full_url = $self->{url};
2434 my $old_url = $full_url;
2435 $full_url .= "/$path" if length $path;
2436 my ($ra, $reparented);
2437 if ($old_url ne $full_url) {
2438 if ($old_url !~ m#^svn(\+ssh)?://#) {
2439 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2441 $self->{url} = $full_url;
2444 $ra = Git::SVN::Ra->new($full_url);
2448 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2449 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2450 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2451 $reporter->finish_report($pool);
2454 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2455 $self->{url} = $old_url;
2459 $editor->{git_commit_ok};
2462 sub gs_fetch_loop_common {
2463 my ($self, $base, $head, $gsv, $globs) = @_;
2464 return if ($base > $head);
2466 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2468 my $common_max = scalar @$gsv;
2470 foreach my $gs (@$gsv) {
2471 if (my $last_commit = $gs->last_commit) {
2472 $gs->assert_index_clean($last_commit);
2474 my @tmp = split m#/#, $gs->{path};
2477 $p .= length($p) ? "/$_" : $_;
2483 $common_max += scalar @$globs;
2484 foreach my $glob (@$globs) {
2485 my @tmp = split m#/#, $glob->{path}->{left};
2488 $p .= length($p) ? "/$_" : $_;
2494 my $longest_path = '';
2495 foreach (sort {length $b <=> length $a} keys %common) {
2496 if ($common{$_} == $common_max) {
2504 my $err_handler = $SVN::Error::handler;
2505 $SVN::Error::handler = sub {
2507 skip_unknown_revs($err);
2510 my ($paths, $r, $author, $date, $log) = @_;
2511 [ dup_changed_paths($paths),
2512 { author => $author, date => $date, log => $log } ];
2514 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2515 sub { $revs{$_[1]} = _cb(@_) });
2516 if ($err && $max >= $head) {
2517 print STDERR "Path '$longest_path' ",
2518 "was probably deleted:\n",
2519 $err->expanded_message,
2520 "\nWill attempt to follow ",
2521 "revisions r$min .. r$max ",
2522 "committed before the deletion\n";
2524 while (--$hi >= $min) {
2526 $self->get_log([$longest_path], $min, $hi,
2529 $revs{$_[1]} = _cb(@_) });
2531 print STDERR "r$min .. r$ok OK\n";
2536 $SVN::Error::handler = $err_handler;
2538 my %exists = map { $_->{path} => $_ } @$gsv;
2539 foreach my $r (sort {$a <=> $b} keys %revs) {
2540 my ($paths, $logged) = @{$revs{$r}};
2542 foreach my $gs ($self->match_globs(\%exists, $paths,
2544 if ($gs->rev_db_max >= $r) {
2547 next unless $gs->match_paths($paths, $r);
2548 $gs->{logged_rev_props} = $logged;
2549 my $log_entry = $gs->do_fetch($paths, $r);
2551 $gs->do_git_commit($log_entry);
2554 foreach my $g (@$globs) {
2555 my $f = "$ENV{GIT_DIR}/svn/." .
2556 $self->uuid . ".$g->{t}";
2557 open my $fh, '>', "$f.tmp" or
2558 die "Can't open $f.tmp for writing: $!";
2560 die "Couldn't write to $f: $!\n";
2561 close $fh or die "Error closing $f: $!\n";
2562 rename "$f.tmp", $f or
2563 die "Couldn't rename ",
2564 "$f.tmp => $f: $!\n";
2567 # pre-fill the .rev_db since it'll eventually get filled in
2568 # with '0' x40 if something new gets committed
2569 foreach my $gs (@$gsv) {
2570 next if defined $gs->rev_db_get($max);
2571 $gs->rev_db_set($max, 0 x40);
2573 last if $max >= $head;
2576 $max = $head if ($max > $head);
2581 my ($self, $exists, $paths, $globs, $r) = @_;
2584 my ($self, $exists, $g, $r) = @_;
2585 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2586 return unless scalar @x == 3;
2587 my $dirents = $x[0];
2588 foreach my $de (keys %$dirents) {
2589 next if $dirents->{$de}->kind != $SVN::Node::dir;
2590 my $p = $g->{path}->full_path($de);
2591 next if $exists->{$p};
2592 next if (length $g->{path}->{right} &&
2593 ($self->check_path($p, $r) !=
2595 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
2596 $g->{ref}->full_path($de), 1);
2599 foreach my $g (@$globs) {
2600 if (my $path = $paths->{"/$g->{path}->{left}"}) {
2601 if ($path->{action} =~ /^[AR]$/) {
2602 get_dir_check($self, $exists, $g, $r);
2605 foreach (keys %$paths) {
2606 if (/$g->{path}->{left_regex}/) {
2607 next if $paths->{$_}->{action} !~ /^[AR]$/;
2608 get_dir_check($self, $exists, $g, $r);
2610 next unless /$g->{path}->{regex}/;
2612 my $pathname = $g->{path}->full_path($p);
2613 next if $exists->{$pathname};
2614 $exists->{$pathname} = Git::SVN->init(
2615 $self->{url}, $pathname, undef,
2616 $g->{ref}->full_path($p), 1);
2619 foreach (split m#/#, $g->{path}->{left}) {
2621 next unless ($paths->{$c} &&
2622 ($paths->{$c}->{action} =~ /^[AR]$/));
2623 get_dir_check($self, $exists, $g, $r);
2631 return $self->{url} if ($self->{url} eq $self->{repos_root});
2632 my $url = $self->{repos_root};
2633 my @components = split(m!/!, $self->{svn_path});
2636 $url .= "/$c" if length $c;
2637 eval { (ref $self)->new($url)->get_latest_revnum };
2638 } while ($@ && ($c = shift @components));
2644 unless (defined $can_do_switch) {
2645 my $pool = SVN::Pool->new;
2647 $self->do_switch(1, '', 0, $self->{url},
2648 SVN::Delta::Editor->new, $pool);
2653 $rep->abort_report($pool);
2661 sub skip_unknown_revs {
2663 my $errno = $err->apr_err();
2664 # Maybe the branch we're tracking didn't
2665 # exist when the repo started, so it's
2666 # not an error if it doesn't, just continue
2668 # Wonderfully consistent library, eh?
2669 # 160013 - svn:// and file://
2670 # 175002 - http(s)://
2671 # 175007 - http(s):// (this repo required authorization, too...)
2672 # More codes may be discovered later...
2673 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2676 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2679 # svn_log_changed_path_t objects passed to get_log are likely to be
2680 # overwritten even if only the refs are copied to an external variable,
2681 # so we should dup the structures in their entirety. Using an externally
2682 # passed pool (instead of our temporary and quickly cleared pool in
2683 # Git::SVN::Ra) does not help matters at all...
2684 sub dup_changed_paths {
2686 return undef unless $paths;
2688 foreach my $p (keys %$paths) {
2689 my $i = $paths->{$p};
2690 my %s = map { $_ => $i->$_ }
2691 qw/copyfrom_path copyfrom_rev action/;
2697 package Git::SVN::Log;
2700 use POSIX qw/strftime/;
2701 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2702 %rusers $show_commit $incremental/;
2707 return 1 if defined $c->{r};
2708 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2709 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
2710 my @log = command(qw/cat-file commit/, $c->{c});
2711 shift @log while ($log[0] ne "\n");
2713 @{$c->{l}} = grep !/^git-svn-id: /, @log;
2715 (undef, $c->{r}, undef) = ::extract_metadata(
2716 (grep(/^git-svn-id: /, @log))[-1]);
2718 return defined $c->{r};
2724 $dcvar = 'color.diff';
2725 $dc = `git-config --get $dcvar`;
2727 # nothing at all; fallback to "diff.color"
2728 $dcvar = 'diff.color';
2729 $dc = `git-config --get $dcvar`;
2732 if ($dc eq 'auto') {
2734 $pc = `git-config --get color.pager`;
2736 # does not have it -- fallback to pager.color
2737 $pc = `git-config --bool --get pager.color`;
2740 $pc = `git-config --bool --get color.pager`;
2746 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2747 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2751 return 0 if $dc eq 'never';
2752 return 1 if $dc eq 'always';
2753 chomp($dc = `git-config --bool --get $dcvar`);
2754 return ($dc eq 'true');
2757 sub git_svn_log_cmd {
2758 my ($r_min, $r_max) = @_;
2759 my $gs = Git::SVN->_new;
2760 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2762 push @cmd, '-r' unless $non_recursive;
2763 push @cmd, qw/--raw --name-status/ if $verbose;
2764 push @cmd, '--color' if log_use_color();
2765 return @cmd unless defined $r_max;
2766 if ($r_max == $r_min) {
2767 push @cmd, '--max-count=1';
2768 if (my $c = $gs->rev_db_get($r_max)) {
2772 my ($c_min, $c_max);
2773 $c_max = $gs->rev_db_get($r_max);
2774 $c_min = $gs->rev_db_get($r_min);
2775 if (defined $c_min && defined $c_max) {
2776 if ($r_max > $r_max) {
2777 push @cmd, "$c_min..$c_max";
2779 push @cmd, "$c_max..$c_min";
2781 } elsif ($r_max > $r_min) {
2790 # adapted from pager.c
2792 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2793 if (!defined $pager) {
2795 } elsif (length $pager == 0 || $pager eq 'cat') {
2801 return unless -t *STDOUT;
2802 pipe my $rfd, my $wfd or return;
2803 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2805 open STDOUT, '>&', $wfd or
2806 ::fatal "Can't redirect to stdout: $!\n";
2809 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2810 $ENV{LESS} ||= 'FRSX';
2811 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2814 sub tz_to_s_offset {
2817 return ($1 * 60) + ($tz * 3600);
2820 sub get_author_info {
2821 my ($dest, $author, $t, $tz) = @_;
2822 $author =~ s/(?:^\s*|\s*$)//g;
2823 $dest->{a_raw} = $author;
2826 $au = $rusers{$author} || undef;
2829 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2834 # Date::Parse isn't in the standard Perl distro :(
2835 if ($tz =~ s/^\+//) {
2836 $t += tz_to_s_offset($tz);
2837 } elsif ($tz =~ s/^\-//) {
2838 $t -= tz_to_s_offset($tz);
2840 $dest->{t_utc} = $t;
2843 sub process_commit {
2844 my ($c, $r_min, $r_max, $defer) = @_;
2845 if (defined $r_min && defined $r_max) {
2846 if ($r_min == $c->{r} && $r_min == $r_max) {
2850 return 1 if $r_min == $r_max;
2851 if ($r_min < $r_max) {
2852 # we need to reverse the print order
2853 return 0 if (defined $limit && --$limit < 0);
2857 if ($r_min != $r_max) {
2858 return 1 if ($r_min < $c->{r});
2859 return 1 if ($r_max > $c->{r});
2862 return 0 if (defined $limit && --$limit < 0);
2871 if (my $l = $c->{l}) {
2872 while ($l->[0] =~ /^\s*$/) { shift @$l }
2875 $l_fmt ||= 'A' . length($c->{r});
2876 print 'r',pack($l_fmt, $c->{r}),' | ';
2877 print "$c->{c} | " if $show_commit;
2880 show_commit_normal($c);
2884 sub show_commit_changed_paths {
2886 return unless $c->{changed};
2887 print "Changed paths:\n", @{$c->{changed}};
2890 sub show_commit_normal {
2892 print '-' x72, "\nr$c->{r} | ";
2893 print "$c->{c} | " if $show_commit;
2894 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2895 localtime($c->{t_utc})), ' | ';
2898 if (my $l = $c->{l}) {
2899 while ($l->[$#$l] eq "\n" && $#$l > 0
2900 && $l->[($#$l - 1)] eq "\n") {
2903 $nr_line = scalar @$l;
2905 print "1 line\n\n\n";
2907 if ($nr_line == 1) {
2908 $nr_line = '1 line';
2910 $nr_line .= ' lines';
2912 print $nr_line, "\n";
2913 show_commit_changed_paths($c);
2915 print $_ foreach @$l;
2919 show_commit_changed_paths($c);
2923 foreach my $x (qw/raw diff/) {
2926 print $_ foreach @{$c->{$x}}
2933 my ($r_min, $r_max);
2934 my $r_last = -1; # prevent dupes
2940 if (defined $::_revision) {
2941 if ($::_revision =~ /^(\d+):(\d+)$/) {
2942 ($r_min, $r_max) = ($1, $2);
2943 } elsif ($::_revision =~ /^\d+$/) {
2944 $r_min = $r_max = $::_revision;
2946 ::fatal "-r$::_revision is not supported, use ",
2947 "standard \'git log\' arguments instead\n";
2952 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2953 my $log = command_output_pipe(@args);
2956 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2958 if (/^${esc_color}commit ($::sha1_short)/o) {
2960 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2962 process_commit($c, $r_min, $r_max, \@k) or
2967 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2968 get_author_info($c, $1, $2, $3);
2969 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2971 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2972 push @{$c->{raw}}, $_;
2973 } elsif (/^${esc_color}[ACRMDT]\t/) {
2974 # we could add $SVN->{svn_path} here, but that requires
2975 # remote access at the moment (repo_path_split)...
2976 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2977 push @{$c->{changed}}, $_;
2978 } elsif (/^${esc_color}diff /o) {
2980 push @{$c->{diff}}, $_;
2982 push @{$c->{diff}}, $_;
2983 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2984 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2985 } elsif (s/^${esc_color} //o) {
2986 push @{$c->{l}}, $_;
2989 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2991 process_commit($c, $r_min, $r_max, \@k);
2997 process_commit($_, $r_min, $r_max) foreach reverse @k;
3001 print '-' x72,"\n" unless $incremental || $oneline;
3004 package Git::SVN::Migration;
3005 # these version numbers do NOT correspond to actual version numbers
3006 # of git nor git-svn. They are just relative.
3008 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3010 # v1 layout: .git/$id/info/url, refs/remotes/$id
3012 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3014 # v3 layout: .git/svn/$id, refs/remotes/$id
3015 # - info/url may remain for backwards compatibility
3016 # - this is what we migrate up to this layout automatically,
3017 # - this will be used by git svn init on single branches
3019 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3020 # - this is only created for newly multi-init-ed
3021 # repositories. Similar in spirit to the
3022 # --use-separate-remotes option in git-clone (now default)
3023 # - we do not automatically migrate to this (following
3024 # the example set by core git)
3028 use File::Path qw/mkpath/;
3029 use File::Basename qw/dirname basename/;
3030 use vars qw/$_minimize/;
3032 sub migrate_from_v0 {
3033 my $git_dir = $ENV{GIT_DIR};
3034 return undef unless -d $git_dir;
3035 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3039 my ($id, $orig_ref) = ($_, $_);
3040 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3041 next unless -f "$git_dir/$id/info/url";
3042 my $new_ref = "refs/remotes/$id";
3043 if (::verify_ref("$new_ref^0")) {
3044 print STDERR "W: $orig_ref is probably an old ",
3045 "branch used by an ancient version of ",
3047 "However, $new_ref also exists.\n",
3048 "We will not be able ",
3049 "to use this branch until this ",
3050 "ambiguity is resolved.\n";
3053 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3054 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3055 command_noisy('update-ref', $new_ref, $orig_ref);
3056 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3059 command_close_pipe($fh, $ctx);
3060 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3064 sub migrate_from_v1 {
3065 my $git_dir = $ENV{GIT_DIR};
3067 return $migrated unless -d $git_dir;
3068 my $svn_dir = "$git_dir/svn";
3070 # just in case somebody used 'svn' as their $id at some point...
3071 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3073 print STDERR "Migrating from a git-svn v1 layout...\n";
3075 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3076 "$svn_dir\n\t(required for this version ",
3077 "($::VERSION) of git-svn) does not. exist\n";
3078 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3081 next unless $x =~ s#^refs/remotes/##;
3083 next unless -f "$git_dir/$x/info/url";
3084 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3086 my $dn = dirname("$git_dir/svn/$x");
3087 mkpath([$dn]) unless -d $dn;
3088 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3089 mkpath(["$git_dir/svn/svn"]);
3090 print STDERR " - $git_dir/$x/info => ",
3091 "$git_dir/svn/$x/info\n";
3092 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3094 # don't worry too much about these, they probably
3095 # don't exist with repos this old (save for index,
3096 # and we can easily regenerate that)
3097 foreach my $f (qw/unhandled.log index .rev_db/) {
3098 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3101 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3102 rename "$git_dir/$x", "$git_dir/svn/$x" or
3107 command_close_pipe($fh, $ctx);
3108 print STDERR "Done migrating from a git-svn v1 layout\n";
3113 my ($l_map, $pfx, $path) = @_;
3115 foreach (<$path/*>) {
3116 if (-r "$_/info/url") {
3117 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3118 my $ref_id = $pfx . basename $_;
3119 my $url = ::file_to_s("$_/info/url");
3120 $l_map->{$ref_id} = $url;
3127 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3128 read_old_urls($l_map, $x, $_);
3132 sub migrate_from_v2 {
3133 my @cfg = command(qw/config -l/);
3134 return if grep /^svn-remote\..+\.url=/, @cfg;
3136 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3139 foreach my $ref_id (sort keys %l_map) {
3140 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3142 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3149 sub minimize_connections {
3150 my $r = Git::SVN::read_all_remotes();
3152 my $root_repos = {};
3153 foreach my $repo_id (keys %$r) {
3154 my $url = $r->{$repo_id}->{url} or next;
3155 my $fetch = $r->{$repo_id}->{fetch} or next;
3156 my $ra = Git::SVN::Ra->new($url);
3158 # skip existing cases where we already connect to the root
3159 if (($ra->{url} eq $ra->{repos_root}) ||
3160 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3162 $root_repos->{$ra->{url}} = $repo_id;
3166 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3167 my $root_path = $ra->{url};
3168 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3169 foreach my $path (keys %$fetch) {
3170 my $ref_id = $fetch->{$path};
3171 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3173 # make sure we can read when connecting to
3174 # a higher level of a repository
3175 my ($last_rev, undef) = $gs->last_rev_commit;
3176 if (!defined $last_rev) {
3178 $root_ra->get_latest_revnum;
3182 my $new = $root_path;
3183 $new .= length $path ? "/$path" : '';
3185 $root_ra->get_log([$new], $last_rev, $last_rev,
3189 $new_urls->{$ra->{repos_root}}->{$new} =
3190 { ref_id => $ref_id,
3191 old_repo_id => $repo_id,
3192 old_path => $path };
3197 foreach my $url (keys %$new_urls) {
3198 # see if we can re-use an existing [svn-remote "repo_id"]
3199 # instead of creating a(n ugly) new section:
3200 my $repo_id = $root_repos->{$url} ||
3201 Git::SVN::sanitize_remote_name($url);
3203 my $fetch = $new_urls->{$url};
3204 foreach my $path (keys %$fetch) {
3205 my $x = $fetch->{$path};
3206 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3207 my $pfx = "svn-remote.$x->{old_repo_id}";
3209 my $old_fetch = quotemeta("$x->{old_path}:".
3210 "refs/remotes/$x->{ref_id}");
3211 command_noisy(qw/config --unset/,
3212 "$pfx.fetch", '^'. $old_fetch . '$');
3213 delete $r->{$x->{old_repo_id}}->
3214 {fetch}->{$x->{old_path}};
3215 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3216 command_noisy(qw/config --unset/,
3218 push @emptied, $x->{old_repo_id}
3223 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3224 "$ENV{GIT_DIR}/config";
3226 The following [svn-remote] sections in your config file ($file) are empty
3227 and can be safely removed:
3229 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3233 sub migration_check {
3237 minimize_connections() if $_minimize;
3240 package Git::IndexInfo;
3243 use Git qw/command_input_pipe command_close_pipe/;
3247 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3248 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3252 my ($self, $path) = @_;
3253 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3254 return ++$self->{nr};
3260 my ($self, $mode, $hash, $path) = @_;
3261 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3262 return ++$self->{nr};
3269 command_close_pipe($self->{gui}, $self->{ctx});
3272 package Git::SVN::GlobSpec;
3277 my ($class, $glob) = @_;
3279 $re =~ s!/+$!!g; # no need for trailing slashes
3280 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3281 my ($left, $right) = ($1, $2);
3283 die "Only one '*' wildcard expansion ",
3284 "is supported (got $nr): '$glob'\n";
3285 } elsif ($nr == 0) {
3286 die "One '*' is needed for glob: '$glob'\n";
3288 $re = quotemeta($left) . $re . quotemeta($right);
3289 if (length $left && !($left =~ s!/+$!!g)) {
3290 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3292 if (length $right && !($right =~ s!^/+!!g)) {
3293 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3295 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3296 bless { left => $left, right => $right, left_regex => $left_re,
3297 regex => qr/$re/, glob => $glob }, $class;
3301 my ($self, $path) = @_;
3302 return (length $self->{left} ? "$self->{left}/" : '') .
3303 $path . (length $self->{right} ? "/$self->{right}" : '');
3311 $remotes = { # returned by read_all_remotes()
3313 # svn-remote.svn.url=https://svn.musicpd.org
3314 url => 'https://svn.musicpd.org',
3315 # svn-remote.svn.fetch=mpd/trunk:trunk
3317 'mpd/trunk' => 'trunk',
3319 # svn-remote.svn.tags=mpd/tags/*:tags/*
3324 regex => qr!mpd/tags/([^/]+)$!,
3330 regex => qr!tags/([^/]+)$!,
3337 $log_entry hashref as returned by libsvn_log_entry()
3339 log => 'whitespace-formatted log entry
3340 ', # trailing newline is preserved
3341 revision => '8', # integer
3342 date => '2004-02-24T17:01:44.108345Z', # commit date
3343 author => 'committer name'
3347 # this is generated by generate_diff();
3348 @mods = array of diff-index line hashes, each element represents one line
3349 of diff-index output
3351 diff-index line ($m hash)
3353 mode_a => first column of diff-index output, no leading ':',
3354 mode_b => second column of diff-index output,
3355 sha1_b => sha1sum of the final blob,
3356 chg => change type [MCRADT],
3357 file_a => original file name of a file (iff chg is 'C' or 'R')
3358 file_b => new/current file name of a file (any chg)
3362 # retval of read_url_paths{,_all}();
3364 # repository root url
3365 'https://svn.musicpd.org' => {
3366 # repository path # GIT_SVN_ID
3367 'mpd/trunk' => 'trunk',
3368 'mpd/tags/0.11.5' => 'tags/0.11.5',
3373 I don't trust the each() function on unless I created %hash myself
3374 because the internal iterator may not have started at base.