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 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
13 $ENV{GIT_DIR} ||= '.git';
14 $Git::SVN::default_repo_id = 'svn';
15 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
16 $Git::SVN::Ra::_log_window_size = 100;
18 $Git::SVN::Log::TZ = $ENV{TZ};
20 $| = 1; # unbuffer STDOUT
22 sub fatal (@) { print STDERR @_; exit 1 }
23 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
26 if ($SVN::Core::VERSION lt '1.1.0') {
27 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
29 push @Git::SVN::Ra::ISA, 'SVN::Ra';
30 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
31 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
34 use File::Basename qw/dirname basename/;
35 use File::Path qw/mkpath/;
36 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
42 foreach (qw/command command_oneline command_noisy command_output_pipe
43 command_input_pipe command_close_pipe/) {
44 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
45 "*Git::SVN::Migration::$_ = ".
46 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
53 $sha1 = qr/[a-f\d]{40}/;
54 $sha1_short = qr/[a-f\d]{4,40}/;
55 my ($_stdin, $_help, $_edit,
58 $_version, $_fetch_all, $_no_rebase,
59 $_merge, $_strategy, $_dry_run, $_local,
60 $_prefix, $_no_checkout, $_verbose);
61 $Git::SVN::_follow_parent = 1;
62 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
63 'config-dir=s' => \$Git::SVN::Ra::config_dir,
64 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
65 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
66 'authors-file|A=s' => \$_authors,
67 'repack:i' => \$Git::SVN::_repack,
68 'noMetadata' => \$Git::SVN::_no_metadata,
69 'useSvmProps' => \$Git::SVN::_use_svm_props,
70 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
71 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
72 'no-checkout' => \$_no_checkout,
74 'repack-flags|repack-args|repack-opts=s' =>
75 \$Git::SVN::_repack_flags,
78 my ($_trunk, $_tags, $_branches);
80 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
81 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
82 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
83 'minimize-url|m' => \$Git::SVN::_minimize_url,
84 'no-metadata' => sub { $icv{noMetadata} = 1 },
85 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
86 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
87 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
89 my %cmt_opts = ( 'edit|e' => \$_edit,
90 'rmdir' => \$SVN::Git::Editor::_rmdir,
91 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
92 'l=i' => \$SVN::Git::Editor::_rename_limit,
93 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
97 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
98 { 'revision|r=s' => \$_revision,
99 'fetch-all|all' => \$_fetch_all,
101 clone => [ \&cmd_clone, "Initialize and fetch revisions",
102 { 'revision|r=s' => \$_revision,
103 %fc_opts, %init_opts } ],
104 init => [ \&cmd_init, "Initialize a repo for tracking" .
105 " (requires URL argument)",
107 'multi-init' => [ \&cmd_multi_init,
108 "Deprecated alias for ".
109 "'$0 init -T<trunk> -b<branches> -t<tags>'",
111 dcommit => [ \&cmd_dcommit,
112 'Commit several diffs to merge with upstream',
113 { 'merge|m|M' => \$_merge,
114 'strategy|s=s' => \$_strategy,
115 'verbose|v' => \$_verbose,
116 'dry-run|n' => \$_dry_run,
117 'fetch-all|all' => \$_fetch_all,
118 'no-rebase' => \$_no_rebase,
119 %cmt_opts, %fc_opts } ],
120 'set-tree' => [ \&cmd_set_tree,
121 "Set an SVN repository to a git tree-ish",
122 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
123 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
124 { 'revision|r=i' => \$_revision } ],
125 'multi-fetch' => [ \&cmd_multi_fetch,
126 "Deprecated alias for $0 fetch --all",
127 { 'revision|r=s' => \$_revision, %fc_opts } ],
128 'migrate' => [ sub { },
129 # no-op, we automatically run this anyways,
130 'Migrate configuration/metadata/layout from
131 previous versions of git-svn',
132 { 'minimize' => \$Git::SVN::Migration::_minimize,
134 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
135 { 'limit=i' => \$Git::SVN::Log::limit,
136 'revision|r=s' => \$_revision,
137 'verbose|v' => \$Git::SVN::Log::verbose,
138 'incremental' => \$Git::SVN::Log::incremental,
139 'oneline' => \$Git::SVN::Log::oneline,
140 'show-commit' => \$Git::SVN::Log::show_commit,
141 'non-recursive' => \$Git::SVN::Log::non_recursive,
142 'authors-file|A=s' => \$_authors,
143 'color' => \$Git::SVN::Log::color,
144 'pager=s' => \$Git::SVN::Log::pager,
146 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
148 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
149 { 'merge|m|M' => \$_merge,
150 'verbose|v' => \$_verbose,
151 'strategy|s=s' => \$_strategy,
152 'local|l' => \$_local,
153 'fetch-all|all' => \$_fetch_all,
155 'commit-diff' => [ \&cmd_commit_diff,
156 'Commit a diff between two trees',
157 { 'message|m=s' => \$_message,
158 'file|F=s' => \$_file,
159 'revision|r=s' => \$_revision,
164 for (my $i = 0; $i < @ARGV; $i++) {
165 if (defined $cmd{$ARGV[$i]}) {
172 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
174 read_repo_config(\%opts);
175 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
176 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
177 'minimize-connections' => \$Git::SVN::Migration::_minimize,
178 'id|i=s' => \$Git::SVN::default_ref_id,
179 'svn-remote|remote|R=s' => sub {
180 $Git::SVN::no_reuse_existing = 1;
181 $Git::SVN::default_repo_id = $_[1] });
182 exit 1 if (!$rv && $cmd && $cmd ne 'log');
185 version() if $_version;
186 usage(1) unless defined $cmd;
187 load_authors() if $_authors;
189 # make sure we're always running
190 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
191 unless (-d $ENV{GIT_DIR}) {
192 if ($git_dir_user_set) {
193 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
194 "but it is not a directory\n";
196 my $git_dir = delete $ENV{GIT_DIR};
197 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
198 unless (length $cdup) {
199 die "Already at toplevel, but $git_dir ",
200 "not found '$cdup'\n";
202 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
203 unless (-d $git_dir) {
204 die "$git_dir still not found after going to ",
207 $ENV{GIT_DIR} = $git_dir;
210 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
211 Git::SVN::Migration::migration_check();
213 Git::SVN::init_vars();
215 Git::SVN::verify_remotes_sanity();
216 $cmd{$cmd}->[0]->(@ARGV);
219 post_fetch_checkout();
222 ####################### primary functions ######################
224 my $exit = shift || 0;
225 my $fd = $exit ? \*STDERR : \*STDOUT;
227 git-svn - bidirectional operations between a single Subversion tree and git
228 Usage: $0 <command> [options] [arguments]\n
230 print $fd "Available commands:\n" unless $cmd;
232 foreach (sort keys %cmd) {
233 next if $cmd && $cmd ne $_;
234 next if /^multi-/; # don't show deprecated commands
235 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
236 foreach (keys %{$cmd{$_}->[2]}) {
237 # mixed-case options are for .git/config only
238 next if /[A-Z]/ && /^[a-z]+$/i;
239 # prints out arguments as they should be passed:
240 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
241 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
243 split /\|/,$_)," $x\n";
247 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
248 arbitrary identifier if you're tracking multiple SVN branches/repositories in
249 one git repository and want to keep them separate. See git-svn(1) for more
256 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
261 unless (-d $ENV{GIT_DIR}) {
262 my @init_db = ('init');
263 push @init_db, "--template=$_template" if defined $_template;
264 if (defined $_shared) {
265 if ($_shared =~ /[a-z]/) {
266 push @init_db, "--shared=$_shared";
268 push @init_db, "--shared";
271 command_noisy(@init_db);
274 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
275 foreach my $i (keys %icv) {
276 die "'$set' and '$i' cannot both be set\n" if $set;
277 next unless defined $icv{$i};
278 command_noisy('config', "$pfx.$i", $icv{$i});
284 my $repo_path = shift or return;
285 mkpath([$repo_path]) unless -d $repo_path;
286 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
287 $ENV{GIT_DIR} = '.git';
291 my ($url, $path) = @_;
292 if (!defined $path &&
293 (defined $_trunk || defined $_branches || defined $_tags) &&
294 $url !~ m#^[a-z\+]+://#) {
297 $path = basename($url) if !defined $path || !length $path;
298 cmd_init($url, $path);
299 Git::SVN::fetch_all($Git::SVN::default_repo_id);
303 if (defined $_trunk || defined $_branches || defined $_tags) {
304 return cmd_multi_init(@_);
306 my $url = shift or die "SVN repository location required ",
307 "as a command-line argument\n";
311 Git::SVN->init($url);
315 if (grep /^\d+=./, @_) {
316 die "'<rev>=<commit>' fetch arguments are ",
317 "no longer supported.\n";
321 die "Usage: $0 fetch [--all] [svn-remote]\n";
323 $remote ||= $Git::SVN::default_repo_id;
327 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
333 if ($_stdin || !@commits) {
334 print "Reading from stdin...\n";
337 if (/\b($sha1_short)\b/o) {
338 unshift @commits, $1;
343 foreach my $c (@commits) {
344 my @tmp = command('rev-parse',$c);
345 if (scalar @tmp == 1) {
347 } elsif (scalar @tmp > 1) {
348 push @revs, reverse(command('rev-list',@tmp));
350 fatal "Failed to rev-parse $c\n";
353 my $gs = Git::SVN->new;
354 my ($r_last, $cmt_last) = $gs->last_rev_commit;
356 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
357 fatal "There are new revisions that were fetched ",
358 "and need to be merged (or acknowledged) ",
359 "before committing.\nlast rev: $r_last\n",
360 " current: $gs->{last_rev}\n";
362 $gs->set_tree($_) foreach @revs;
363 print "Done committing ",scalar @revs," revisions to SVN\n";
370 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
372 die "Unable to determine upstream SVN information from ",
376 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
377 foreach my $d (@$linear_refs) {
378 unless (defined $last_rev) {
379 (undef, $last_rev, undef) = cmt_metadata("$d~1");
380 unless (defined $last_rev) {
381 fatal "Unable to extract revision information ",
382 "from commit $d~1\n";
386 print "diff-tree $d~1 $d\n";
388 my %ed_opts = ( r => $last_rev,
389 log => get_commit_entry($d)->{log},
390 ra => Git::SVN::Ra->new($gs->full_url),
394 print "Committed r$_[0]\n";
395 $last_rev = $_[0]; },
397 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
398 print "No changes\n$d~1 == $d\n";
399 } elsif ($parents->{$d} && @{$parents->{$d}}) {
400 $gs->{inject_parents_dcommit}->{$last_rev} =
407 warn "Could not determine fetch information for $url\n",
408 "Will not attempt to fetch and rebase commits.\n",
409 "This probably means you have useSvmProps and should\n",
410 "now resync your SVN::Mirror repository.\n";
413 $_fetch_all ? $gs->fetch_all : $gs->fetch;
414 unless ($_no_rebase) {
415 # we always want to rebase against the current HEAD, not any
416 # head that was passed to us
417 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
420 @finish = rebase_cmd();
421 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
422 "using @finish:\n", "@diff";
424 print "No changes between current HEAD and ",
425 $gs->refname, "\nResetting to the latest ",
427 @finish = qw/reset --mixed/;
429 command_noisy(@finish, $gs->refname);
434 my $revision_or_hash = shift;
436 if ($revision_or_hash =~ /^r\d+$/) {
440 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
442 die "Unable to determine upstream SVN information from ",
445 my $desired_revision = substr($revision_or_hash, 1);
446 $result = $gs->rev_db_get($desired_revision);
448 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
451 print "$result\n" if $result;
455 command_noisy(qw/update-index --refresh/);
456 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
458 die "Unable to determine upstream SVN information from ",
459 "working tree history\n";
461 if (command(qw/diff-index HEAD --/)) {
462 print STDERR "Cannot rebase with uncommited changes:\n";
463 command_noisy('status');
467 $_fetch_all ? $gs->fetch_all : $gs->fetch;
469 command_noisy(rebase_cmd(), $gs->refname);
472 sub cmd_show_ignore {
473 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
474 $gs ||= Git::SVN->new;
475 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
476 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
481 unless (defined $_trunk || defined $_branches || defined $_tags) {
485 # there are currently some bugs that prevent multi-init/multi-fetch
486 # setups from working well without this.
487 $Git::SVN::_minimize_url = 1;
489 $_prefix = '' unless defined $_prefix;
495 if (defined $_trunk) {
496 my $trunk_ref = $_prefix . 'trunk';
497 # try both old-style and new-style lookups:
498 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
500 my ($trunk_url, $trunk_path) =
501 complete_svn_url($url, $_trunk);
502 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
506 return unless defined $_branches || defined $_tags;
507 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
508 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
509 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
512 sub cmd_multi_fetch {
513 my $remotes = Git::SVN::read_all_remotes();
514 foreach my $repo_id (sort keys %$remotes) {
515 if ($remotes->{$repo_id}->{url}) {
516 Git::SVN::fetch_all($repo_id, $remotes);
521 # this command is special because it requires no metadata
522 sub cmd_commit_diff {
523 my ($ta, $tb, $url) = @_;
524 my $usage = "Usage: $0 commit-diff -r<revision> ".
525 "<tree-ish> <tree-ish> [<URL>]\n";
526 fatal($usage) if (!defined $ta || !defined $tb);
529 my $gs = eval { Git::SVN->new };
531 fatal("Needed URL or usable git-svn --id in ",
532 "the command-line\n", $usage);
535 $svn_path = $gs->{path};
537 unless (defined $_revision) {
538 fatal("-r|--revision is a required argument\n", $usage);
540 if (defined $_message && defined $_file) {
541 fatal("Both --message/-m and --file/-F specified ",
542 "for the commit message.\n",
543 "I have no idea what you mean\n");
545 if (defined $_file) {
546 $_message = file_to_s($_file);
548 $_message ||= get_commit_entry($tb)->{log};
550 my $ra ||= Git::SVN::Ra->new($url);
551 $svn_path ||= $ra->{svn_path};
554 $r = $ra->get_latest_revnum;
555 } elsif ($r !~ /^\d+$/) {
556 die "revision argument: $r not understood by git-svn\n";
558 my %ed_opts = ( r => $r,
563 editor_cb => sub { print "Committed r$_[0]\n" },
564 svn_path => $svn_path );
565 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
566 print "No changes\n$ta == $tb\n";
570 ########################### utility functions #########################
573 my @cmd = qw/rebase/;
574 push @cmd, '-v' if $_verbose;
575 push @cmd, qw/--merge/ if $_merge;
576 push @cmd, "--strategy=$_strategy" if $_strategy;
580 sub post_fetch_checkout {
581 return if $_no_checkout;
582 my $gs = $Git::SVN::_head or return;
583 return if verify_ref('refs/heads/master^0');
585 my $valid_head = verify_ref('HEAD^0');
586 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
587 return if ($valid_head || !verify_ref('HEAD^0'));
589 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
590 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
593 chomp(my $bare = `git config --bool --get core.bare`);
594 return if $bare eq 'true';
595 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
596 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
597 print STDERR "Checked out HEAD:\n ",
598 $gs->full_url, " r", $gs->last_rev, "\n";
601 sub complete_svn_url {
602 my ($url, $path) = @_;
604 if ($path !~ m#^[a-z\+]+://#) {
605 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
606 fatal("E: '$path' is not a complete URL ",
607 "and a separate URL is not specified\n");
609 return ($url, $path);
614 sub complete_url_ls_init {
615 my ($ra, $repo_path, $switch, $pfx) = @_;
616 unless ($repo_path) {
617 print STDERR "W: $switch not specified\n";
620 $repo_path =~ s#/+$##;
621 if ($repo_path =~ m#^[a-z\+]+://#) {
622 $ra = Git::SVN::Ra->new($repo_path);
625 $repo_path =~ s#^/+##;
627 fatal("E: '$repo_path' is not a complete URL ",
628 "and a separate URL is not specified\n");
631 my $url = $ra->{url};
632 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
633 my $k = "svn-remote.$gs->{repo_id}.url";
634 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
635 if ($orig_url && ($orig_url ne $gs->{url})) {
636 die "$k already set: $orig_url\n",
637 "wanted to set to: $gs->{url}\n";
639 command_oneline('config', $k, $gs->{url}) unless $orig_url;
640 my $remote_path = "$ra->{svn_path}/$repo_path/*";
641 $remote_path =~ s#/+#/#g;
642 $remote_path =~ s#^/##g;
643 my ($n) = ($switch =~ /^--(\w+)/);
644 if (length $pfx && $pfx !~ m#/$#) {
645 die "--prefix='$pfx' must have a trailing slash '/'\n";
647 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
648 "$remote_path:refs/remotes/$pfx*");
653 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
657 sub get_tree_from_treeish {
659 # $treeish can be a symbolic ref, too:
660 my $type = command_oneline(qw/cat-file -t/, $treeish);
662 while ($type eq 'tag') {
663 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
665 if ($type eq 'commit') {
666 $expected = (grep /^tree /, command(qw/cat-file commit/,
668 ($expected) = ($expected =~ /^tree ($sha1)$/o);
669 die "Unable to get tree from $treeish\n" unless $expected;
670 } elsif ($type eq 'tree') {
671 $expected = $treeish;
673 die "$treeish is a $type, expected tree, tag or commit\n";
678 sub get_commit_entry {
679 my ($treeish) = shift;
680 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
681 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
682 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
683 open my $log_fh, '>', $commit_editmsg or croak $!;
685 my $type = command_oneline(qw/cat-file -t/, $treeish);
686 if ($type eq 'commit' || $type eq 'tag') {
687 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
692 $in_msg = 1 if (/^\s*$/);
693 } elsif (/^git-svn-id: /) {
694 # skip this for now, we regenerate the
695 # correct one on re-fetch anyways
696 # TODO: set *:merge properties or like...
698 print $log_fh $_ or croak $!;
701 command_close_pipe($msg_fh, $ctx);
703 close $log_fh or croak $!;
705 if ($_edit || ($type eq 'tree')) {
706 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
707 # TODO: strip out spaces, comments, like git-commit.sh
708 system($editor, $commit_editmsg);
710 rename $commit_editmsg, $commit_msg or croak $!;
711 open $log_fh, '<', $commit_msg or croak $!;
712 { local $/; chomp($log_entry{log} = <$log_fh>); }
713 close $log_fh or croak $!;
719 my ($str, $file, $mode) = @_;
720 open my $fd,'>',$file or croak $!;
721 print $fd $str,"\n" or croak $!;
722 close $fd or croak $!;
723 chmod ($mode &~ umask, $file) if (defined $mode);
728 open my $fd,'<',$file or croak "$!: file: $file\n";
731 close $fd or croak $!;
736 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
738 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
739 my $log = $cmd eq 'log';
742 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
743 my ($user, $name, $email) = ($1, $2, $3);
745 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
747 $users{$user} = [$name, $email];
750 close $authors or croak $!;
753 # convert GetOpt::Long specs for use by git-config
754 sub read_repo_config {
755 return unless -d $ENV{GIT_DIR};
758 foreach my $o (keys %$opts) {
759 # if we have mixedCase and a long option-only, then
760 # it's a config-only variable that we don't need for
762 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
764 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
766 my $arg = 'git-config';
767 $arg .= ' --int' if ($o =~ /[:=]i$/);
768 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
769 if (ref $v eq 'ARRAY') {
770 chomp(my @tmp = `$arg --get-all svn.$key`);
773 chomp(my $tmp = `$arg --get svn.$key`);
774 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
779 delete @$opts{@config_only} if @config_only;
782 sub extract_metadata {
783 my $id = shift or return (undef, undef, undef);
784 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
786 if (!defined $rev || !$uuid || !$url) {
787 # some of the original repositories I made had
788 # identifiers like this:
789 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
791 return ($url, $rev, $uuid);
795 return extract_metadata((grep(/^git-svn-id: /,
796 command(qw/cat-file commit/, shift)))[-1]);
799 sub working_head_info {
800 my ($head, $refs) = @_;
801 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
802 while (my $hash = <$fh>) {
804 my ($url, $rev, $uuid) = cmt_metadata($hash);
805 if (defined $url && defined $rev) {
806 if (my $gs = Git::SVN->find_by_url($url)) {
807 my $c = $gs->rev_db_get($rev);
808 if ($c && $c eq $hash) {
809 close $fh; # break the pipe
810 return ($url, $rev, $uuid, $gs);
814 unshift @$refs, $hash if $refs;
816 command_close_pipe($fh, $ctx);
817 (undef, undef, undef, undef);
820 sub read_commit_parents {
821 my ($parents, $c) = @_;
822 my ($fh, $ctx) = command_output_pipe(qw/cat-file commit/, $c);
826 /^parent ($sha1)/ or next;
827 push @{$parents->{$c}}, $1;
829 close $fh; # break the pipe
832 sub linearize_history {
833 my ($gs, $refs) = @_;
835 foreach my $c (@$refs) {
836 read_commit_parents(\%parents, $c);
841 my $last_svn_commit = $gs->last_commit;
842 foreach my $c (reverse @$refs) {
843 next if $c eq $last_svn_commit;
846 unshift @linear_refs, $c;
849 # we only want the first parent to diff against for linear
850 # history, we save the rest to inject when we finalize the
852 my $fp_a = verify_ref("$c~1");
853 my $fp_b = shift @{$parents{$c}} if $parents{$c};
854 if (!$fp_a || !$fp_b) {
856 "has no parent commit, and therefore ",
857 "nothing to diff against.\n",
858 "You should be working from a repository ",
859 "originally created by git-svn\n";
861 if ($fp_a ne $fp_b) {
862 die "$c~1 = $fp_a, however parsing commit $c ",
863 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
866 foreach my $p (@{$parents{$c}}) {
870 (\@linear_refs, \%parents);
876 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
877 $_repack $_repack_flags $_use_svm_props $_head
878 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
880 use File::Path qw/mkpath/;
881 use File::Copy qw/copy/;
885 # properties that we do not log:
888 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
889 svn:special svn:executable
890 svn:entry:committed-rev
891 svn:entry:last-author
893 svn:entry:committed-date/;
895 # some options are read globally, but can be overridden locally
896 # per [svn-remote "..."] section. Command-line options will *NOT*
897 # override options set in an [svn-remote "..."] section
899 foreach (qw/follow_parent no_metadata use_svm_props
900 use_svnsync_props/) {
905 return \$self->{-$_} if exists \$self->{-$_};
906 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
907 eval { command_oneline(qw/config --get/, \$k) };
909 \$self->{-$_} = \$Git::SVN::_$_;
911 my \$v = command_oneline(qw/config --bool/,\$k);
912 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
914 return \$self->{-$_} }\n";
921 END { unlink keys %LOCKFILES if %LOCKFILES }
923 sub resolve_local_globs {
924 my ($url, $fetch, $glob_spec) = @_;
925 return unless defined $glob_spec;
926 my $ref = $glob_spec->{ref};
927 my $path = $glob_spec->{path};
928 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
929 next unless m#^refs/remotes/$ref->{regex}$#;
931 my $pathname = $path->full_path($p);
932 my $refname = $ref->full_path($p);
933 if (my $existing = $fetch->{$pathname}) {
934 if ($existing ne $refname) {
935 die "Refspec conflict:\n",
936 "existing: refs/remotes/$existing\n",
937 " globbed: refs/remotes/$refname\n";
939 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
940 $u =~ s!^\Q$url\E(/|$)!! or die
941 "refs/remotes/$refname: '$url' not found in '$u'\n";
942 if ($pathname ne $u) {
943 warn "W: Refspec glob conflict ",
944 "(ref: refs/remotes/$refname):\n",
945 "expected path: $pathname\n",
947 "Continuing ahead with $u\n";
951 $fetch->{$pathname} = $refname;
956 sub parse_revision_argument {
957 my ($base, $head) = @_;
958 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
959 return ($base, $head);
961 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
962 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
963 return ($head, $head) if ($::_revision eq 'HEAD');
964 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
965 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
966 die "revision argument: $::_revision not understood by git-svn\n";
970 my ($repo_id, $remotes) = @_;
974 $repo_id = $gs->{repo_id};
976 $remotes ||= read_all_remotes();
977 my $remote = $remotes->{$repo_id} or
978 die "[svn-remote \"$repo_id\"] unknown\n";
979 my $fetch = $remote->{fetch};
980 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
982 my $ra = Git::SVN::Ra->new($url);
983 my $uuid = $ra->get_uuid;
984 my $head = $ra->get_latest_revnum;
985 my $base = defined $fetch ? $head : 0;
987 # read the max revs for wildcard expansion (branches/*, tags/*)
988 foreach my $t (qw/branches tags/) {
989 defined $remote->{$t} or next;
990 push @globs, $remote->{$t};
991 my $max_rev = eval { tmp_config(qw/--int --get/,
992 "svn-remote.$repo_id.${t}-maxRev") };
993 if (defined $max_rev && ($max_rev < $base)) {
995 } elsif (!defined $max_rev) {
1001 foreach my $p (sort keys %$fetch) {
1002 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1003 my $lr = $gs->rev_db_max;
1005 $base = $lr if ($lr < $base);
1011 ($base, $head) = parse_revision_argument($base, $head);
1012 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1015 sub read_all_remotes {
1017 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1018 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1019 $r->{$1}->{fetch}->{$2} = $3;
1020 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1021 $r->{$1}->{url} = $2;
1022 } elsif (m!^(.+)\.(branches|tags)=
1023 (.*):refs/remotes/(.+)\s*$/!x) {
1024 my ($p, $g) = ($3, $4);
1025 my $rs = $r->{$1}->{$2} = {
1028 path => Git::SVN::GlobSpec->new($p),
1029 ref => Git::SVN::GlobSpec->new($g) };
1030 if (length($rs->{ref}->{right}) != 0) {
1031 die "The '*' glob character must be the last ",
1032 "character of '$g'\n";
1040 if (defined $_repack) {
1041 $_repack = 1000 if ($_repack <= 0);
1042 $_repack_nr = $_repack;
1043 $_repack_flags ||= '-d';
1047 sub verify_remotes_sanity {
1048 return unless -d $ENV{GIT_DIR};
1050 foreach (command(qw/config -l/)) {
1051 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1053 die "Remote ref refs/remote/$1 is tracked by",
1054 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1055 "Please resolve this ambiguity in ",
1056 "your git configuration file before ",
1064 # we allow more chars than remotes2config.sh...
1065 sub sanitize_remote_name {
1067 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1071 sub find_existing_remote {
1072 my ($url, $remotes) = @_;
1073 return undef if $no_reuse_existing;
1075 foreach my $repo_id (keys %$remotes) {
1076 my $u = $remotes->{$repo_id}->{url} or next;
1078 $existing = $repo_id;
1084 sub init_remote_config {
1085 my ($self, $url, $no_write) = @_;
1086 $url =~ s!/+$!!; # strip trailing slash
1087 my $r = read_all_remotes();
1088 my $existing = find_existing_remote($url, $r);
1090 unless ($no_write) {
1091 print STDERR "Using existing ",
1092 "[svn-remote \"$existing\"]\n";
1094 $self->{repo_id} = $existing;
1095 } elsif ($_minimize_url) {
1096 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1097 $existing = find_existing_remote($min_url, $r);
1099 unless ($no_write) {
1100 print STDERR "Using existing ",
1101 "[svn-remote \"$existing\"]\n";
1103 $self->{repo_id} = $existing;
1105 if ($min_url ne $url) {
1106 unless ($no_write) {
1107 print STDERR "Using higher level of URL: ",
1108 "$url => $min_url\n";
1110 my $old_path = $self->{path};
1111 $self->{path} = $url;
1112 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1113 if (length $old_path) {
1114 $self->{path} .= "/$old_path";
1121 # verify that we aren't overwriting anything:
1123 command_oneline('config', '--get',
1124 "svn-remote.$self->{repo_id}.url")
1126 if ($orig_url && ($orig_url ne $url)) {
1127 die "svn-remote.$self->{repo_id}.url already set: ",
1128 "$orig_url\nwanted to set to: $url\n";
1131 my ($xrepo_id, $xpath) = find_ref($self->refname);
1132 if (defined $xpath) {
1133 die "svn-remote.$xrepo_id.fetch already set to track ",
1134 "$xpath:refs/remotes/", $self->refname, "\n";
1136 unless ($no_write) {
1137 command_noisy('config',
1138 "svn-remote.$self->{repo_id}.url", $url);
1139 command_noisy('config', '--add',
1140 "svn-remote.$self->{repo_id}.fetch",
1141 "$self->{path}:".$self->refname);
1143 $self->{url} = $url;
1146 sub find_by_url { # repos_root and, path are optional
1147 my ($class, $full_url, $repos_root, $path) = @_;
1149 return undef unless defined $full_url;
1150 remove_username($full_url);
1151 remove_username($repos_root) if defined $repos_root;
1152 my $remotes = read_all_remotes();
1153 if (defined $full_url && defined $repos_root && !defined $path) {
1155 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1157 foreach my $repo_id (keys %$remotes) {
1158 my $u = $remotes->{$repo_id}->{url} or next;
1159 remove_username($u);
1160 next if defined $repos_root && $repos_root ne $u;
1162 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1163 foreach (qw/branches tags/) {
1164 resolve_local_globs($u, $fetch,
1165 $remotes->{$repo_id}->{$_});
1168 unless (defined $p) {
1170 $p =~ s#^\Q$u\E(?:/|$)## or next;
1172 foreach my $f (keys %$fetch) {
1174 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1181 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1182 my $self = _new($class, $repo_id, $ref_id, $path);
1184 $self->init_remote_config($url, $no_write);
1191 foreach (command(qw/config -l/)) {
1192 next unless m!^svn-remote\.(.+)\.fetch=
1193 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1194 my ($repo_id, $path, $ref) = ($1, $2, $3);
1195 if ($ref eq $ref_id) {
1196 $path = '' if ($path =~ m#^\./?#);
1197 return ($repo_id, $path);
1200 (undef, undef, undef);
1204 my ($class, $ref_id, $repo_id, $path) = @_;
1205 if (defined $ref_id && !defined $repo_id && !defined $path) {
1206 ($repo_id, $path) = find_ref($ref_id);
1207 if (!defined $repo_id) {
1208 die "Could not find a \"svn-remote.*.fetch\" key ",
1209 "in the repository configuration matching: ",
1210 "refs/remotes/$ref_id\n";
1213 my $self = _new($class, $repo_id, $ref_id, $path);
1214 if (!defined $self->{path} || !length $self->{path}) {
1215 my $fetch = command_oneline('config', '--get',
1216 "svn-remote.$repo_id.fetch",
1217 ":refs/remotes/$ref_id\$") or
1218 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1219 "\":refs/remotes/$ref_id\$\" in config\n";
1220 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1222 $self->{url} = command_oneline('config', '--get',
1223 "svn-remote.$repo_id.url") or
1224 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1229 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1233 return $self->{svm}->{uuid} if $self->svm;
1235 unless ($self->{svm}) {
1236 die "SVM UUID not cached, and reading remotely failed\n";
1238 $self->{svm}->{uuid};
1243 return $self->{svm} if $self->{svm};
1245 # see if we have it in our config, first:
1247 my $section = "svn-remote.$self->{repo_id}";
1249 source => tmp_config('--get', "$section.svm-source"),
1250 uuid => tmp_config('--get', "$section.svm-uuid"),
1251 replace => tmp_config('--get', "$section.svm-replace"),
1254 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1255 $self->{svm} = $svm;
1261 my ($self, $ra) = @_;
1262 return $ra if $self->svm;
1264 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1265 "(svm:source, svm:uuid) ",
1266 "from the following URLs:\n" );
1267 sub read_svm_props {
1268 my ($self, $ra, $path, $r) = @_;
1269 my $props = ($ra->get_dir($path, $r))[2];
1270 my $src = $props->{'svm:source'};
1271 my $uuid = $props->{'svm:uuid'};
1272 return undef if (!$src || !$uuid);
1276 $uuid =~ m{^[0-9a-f\-]{30,}$}
1277 or die "doesn't look right - svm:uuid is '$uuid'\n";
1279 # the '!' is used to mark the repos_root!/relative/path
1280 $src =~ s{/?!/?}{/};
1281 $src =~ s{/+$}{}; # no trailing slashes please
1282 # username is of no interest
1283 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1285 my $replace = $ra->{url};
1286 $replace .= "/$path" if length $path;
1288 my $section = "svn-remote.$self->{repo_id}";
1289 tmp_config("$section.svm-source", $src);
1290 tmp_config("$section.svm-replace", $replace);
1291 tmp_config("$section.svm-uuid", $uuid);
1299 my $r = $ra->get_latest_revnum;
1300 my $path = $self->{path};
1302 while (length $path) {
1303 unless ($tried{"$self->{url}/$path"}) {
1304 return $ra if $self->read_svm_props($ra, $path, $r);
1305 $tried{"$self->{url}/$path"} = 1;
1307 $path =~ s#/?[^/]+$##;
1309 die "Path: '$path' should be ''\n" if $path ne '';
1310 return $ra if $self->read_svm_props($ra, $path, $r);
1311 $tried{"$self->{url}/$path"} = 1;
1313 if ($ra->{repos_root} eq $self->{url}) {
1314 die @err, (map { " $_\n" } keys %tried), "\n";
1317 # nope, make sure we're connected to the repository root:
1320 $path = $ra->{svn_path};
1321 $ra = Git::SVN::Ra->new($ra->{repos_root});
1322 while (length $path) {
1323 unless ($tried{"$ra->{url}/$path"}) {
1324 $ok = $self->read_svm_props($ra, $path, $r);
1326 $tried{"$ra->{url}/$path"} = 1;
1328 $path =~ s#/?[^/]+$##;
1330 die "Path: '$path' should be ''\n" if $path ne '';
1331 $ok ||= $self->read_svm_props($ra, $path, $r);
1332 $tried{"$ra->{url}/$path"} = 1;
1334 die @err, (map { " $_\n" } keys %tried), "\n";
1336 Git::SVN::Ra->new($self->{url});
1341 return $self->{svnsync} if $self->{svnsync};
1343 if ($self->no_metadata) {
1344 die "Can't have both 'noMetadata' and ",
1345 "'useSvnsyncProps' options set!\n";
1347 if ($self->rewrite_root) {
1348 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1353 # see if we have it in our config, first:
1355 my $section = "svn-remote.$self->{repo_id}";
1357 url => tmp_config('--get', "$section.svnsync-url"),
1358 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1361 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1362 return $self->{svnsync} = $svnsync;
1365 my $err = "useSvnsyncProps set, but failed to read " .
1366 "svnsync property: svn:sync-from-";
1367 my $rp = $self->ra->rev_proplist(0);
1369 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1370 $url =~ m{^[a-z\+]+://} or
1371 die "doesn't look right - svn:sync-from-url is '$url'\n";
1373 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1374 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1375 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1377 my $section = "svn-remote.$self->{repo_id}";
1378 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1379 tmp_config('--add', "$section.svnsync-url", $url);
1380 return $self->{svnsync} = { url => $url, uuid => $uuid };
1383 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1384 # remote lookup (useful for 'git svn log').
1387 unless ($self->{ra_uuid}) {
1388 my $key = "svn-remote.$self->{repo_id}.uuid";
1389 my $uuid = eval { tmp_config('--get', $key) };
1390 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1391 $self->{ra_uuid} = $uuid;
1393 die "ra_uuid called without URL\n" unless $self->{url};
1394 $self->{ra_uuid} = $self->ra->get_uuid;
1395 tmp_config('--add', $key, $self->{ra_uuid});
1403 my $ra = Git::SVN::Ra->new($self->{url});
1404 if ($self->use_svm_props && !$self->{svm}) {
1405 if ($self->no_metadata) {
1406 die "Can't have both 'noMetadata' and ",
1407 "'useSvmProps' options set!\n";
1408 } elsif ($self->use_svnsync_props) {
1409 die "Can't have both 'useSvnsyncProps' and ",
1410 "'useSvmProps' options set!\n";
1412 $ra = $self->_set_svm_vars($ra);
1413 $self->{-want_revprops} = 1;
1420 my $repos_root = $self->ra->{repos_root};
1421 return $self->{path} if ($self->{url} eq $repos_root);
1422 my $url = $self->{url} .
1423 (length $self->{path} ? "/$self->{path}" : $self->{path});
1424 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1428 sub traverse_ignore {
1429 my ($self, $fh, $path, $r) = @_;
1432 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1434 $p =~ s#^\Q$self->{path}\E(/|$)##;
1435 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1436 if (my $s = $props->{'svn:ignore'}) {
1437 $s =~ s/[\r\n]+/\n/g;
1439 if (length $p == 0) {
1443 $s =~ s#\n#\n/$p/#g;
1444 print $fh "/$p/$s\n";
1447 foreach (sort keys %$dirent) {
1448 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1449 $self->traverse_ignore($fh, "$path/$_", $r);
1453 sub last_rev { ($_[0]->last_rev_commit)[0] }
1454 sub last_commit { ($_[0]->last_rev_commit)[1] }
1456 # returns the newest SVN revision number and newest commit SHA1
1457 sub last_rev_commit {
1459 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1460 return ($self->{last_rev}, $self->{last_commit});
1462 my $c = ::verify_ref($self->refname.'^0');
1463 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1464 my $rev = (::cmt_metadata($c))[1];
1466 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1470 my $db_path = $self->db_path;
1471 unless (-e $db_path) {
1472 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1473 return (undef, undef);
1475 my $offset = -41; # from tail
1477 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1478 sysseek($fh, $offset, 2); # don't care for errors
1479 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1481 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1483 sysseek($fh, $offset, 2); # don't care for errors
1484 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1487 if ($c && $c ne $rl) {
1488 die "$db_path and ", $self->refname,
1489 " inconsistent!:\n$c != $rl\n";
1491 my $rev = sysseek($fh, 0, 1) or croak $!;
1492 $rev = ($rev - 41) / 41;
1493 close $fh or croak $!;
1494 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1498 sub get_fetch_range {
1499 my ($self, $min, $max) = @_;
1500 $max ||= $self->ra->get_latest_revnum;
1501 $min ||= $self->rev_db_max;
1507 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1508 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1509 if (! -f $config && -f $old_def_config) {
1510 rename $old_def_config, $config or
1511 die "Failed rename $old_def_config => $config: $!\n";
1513 my $old_config = $ENV{GIT_CONFIG};
1514 $ENV{GIT_CONFIG} = $config;
1517 unless (-f $config) {
1519 open my $fh, '>', $config or
1520 die "Can't open $config: $!\n";
1521 print $fh "; This file is used internally by ",
1523 "Couldn't write to $config: $!\n";
1524 print $fh "; You should not have to edit it\n" or
1525 die "Couldn't write to $config: $!\n";
1526 close $fh or die "Couldn't close $config: $!\n";
1528 command('config', @args);
1531 if (defined $old_config) {
1532 $ENV{GIT_CONFIG} = $old_config;
1534 delete $ENV{GIT_CONFIG};
1537 wantarray ? @ret : $ret[0];
1541 my ($self, $sub) = @_;
1542 my $old_index = $ENV{GIT_INDEX_FILE};
1543 $ENV{GIT_INDEX_FILE} = $self->{index};
1546 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1547 mkpath([$dir]) unless -d $dir;
1551 if (defined $old_index) {
1552 $ENV{GIT_INDEX_FILE} = $old_index;
1554 delete $ENV{GIT_INDEX_FILE};
1557 wantarray ? @ret : $ret[0];
1560 sub assert_index_clean {
1561 my ($self, $treeish) = @_;
1563 $self->tmp_index_do(sub {
1564 command_noisy('read-tree', $treeish) unless -e $self->{index};
1565 my $x = command_oneline('write-tree');
1566 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1567 /^tree ($::sha1)/mo);
1570 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1571 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1572 command_noisy('read-tree', $treeish);
1573 $x = command_oneline('write-tree');
1575 ::fatal "trees ($treeish) $y != $x\n",
1576 "Something is seriously wrong...\n";
1581 sub get_commit_parents {
1582 my ($self, $log_entry) = @_;
1583 my (%seen, @ret, @tmp);
1584 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1585 if (my $ip = $self->{inject_parents}) {
1586 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1590 if (my $cur = ::verify_ref($self->refname.'^0')) {
1593 if (my $ipd = $self->{inject_parents_dcommit}) {
1594 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1595 push @tmp, @$commit;
1598 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1599 while (my $p = shift @tmp) {
1603 # MAXPARENT is defined to 16 in commit-tree.c:
1607 die "r$log_entry->{revision}: No room for parents:\n\t",
1608 join("\n\t", @tmp), "\n";
1615 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1616 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1617 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1620 if ($rwr !~ m#^[a-z\+]+://#) {
1621 die "$rwr is not a valid URL (key: $k)\n";
1624 $self->{-rewrite_root} = $rwr;
1629 ($self->rewrite_root || $self->{url}) .
1630 (length $self->{path} ? '/' . $self->{path} : '');
1635 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1639 my ($self, $log_entry) = @_;
1640 my $lr = $self->last_rev;
1641 if (defined $lr && $lr >= $log_entry->{revision}) {
1642 die "Last fetched revision of ", $self->refname,
1643 " was r$lr, but we are about to fetch: ",
1644 "r$log_entry->{revision}!\n";
1646 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1647 croak "$log_entry->{revision} = $c already exists! ",
1648 "Why are we refetching it?\n";
1650 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1651 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1652 $log_entry->{email};
1653 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1655 my $tree = $log_entry->{tree};
1656 if (!defined $tree) {
1657 $tree = $self->tmp_index_do(sub {
1658 command_oneline('write-tree') });
1660 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1662 my @exec = ('git-commit-tree', $tree);
1663 foreach ($self->get_commit_parents($log_entry)) {
1664 push @exec, '-p', $_;
1666 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1668 print $msg_fh $log_entry->{log} or croak $!;
1669 unless ($self->no_metadata) {
1670 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1673 $msg_fh->flush == 0 or croak $!;
1674 close $msg_fh or croak $!;
1675 chomp(my $commit = do { local $/; <$out_fh> });
1676 close $out_fh or croak $!;
1679 if ($commit !~ /^$::sha1$/o) {
1680 die "Failed to commit, invalid sha1: $commit\n";
1683 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1685 $self->{last_rev} = $log_entry->{revision};
1686 $self->{last_commit} = $commit;
1687 print "r$log_entry->{revision}";
1688 if (defined $log_entry->{svm_revision}) {
1689 print " (\@$log_entry->{svm_revision})";
1690 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1691 0, $self->svm_uuid);
1693 print " = $commit ($self->{ref_id})\n";
1694 if (defined $_repack && (--$_repack_nr == 0)) {
1695 $_repack_nr = $_repack;
1696 # repack doesn't use any arguments with spaces in them, does it?
1697 print "Running git repack $_repack_flags ...\n";
1698 command_noisy('repack', split(/\s+/, $_repack_flags));
1699 print "Done repacking\n";
1705 my ($self, $paths, $r) = @_;
1706 return 1 if $self->{path} eq '';
1707 if (my $path = $paths->{"/$self->{path}"}) {
1708 return ($path->{action} eq 'D') ? 0 : 1;
1710 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1711 if (grep /$self->{path_regex}/, keys %$paths) {
1715 foreach (split m#/#, $self->{path}) {
1717 next unless ($paths->{$c} &&
1718 ($paths->{$c}->{action} =~ /^[AR]$/));
1719 if ($self->ra->check_path($self->{path}, $r) ==
1727 sub find_parent_branch {
1728 my ($self, $paths, $rev) = @_;
1729 return undef unless $self->follow_parent;
1730 unless (defined $paths) {
1731 my $err_handler = $SVN::Error::handler;
1732 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1733 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1735 Git::SVN::Ra::dup_changed_paths($_[0]) });
1736 $SVN::Error::handler = $err_handler;
1738 return undef unless defined $paths;
1740 # look for a parent from another branch:
1741 my @b_path_components = split m#/#, $self->rel_path;
1742 my @a_path_components;
1744 while (@b_path_components) {
1745 $i = $paths->{'/'.join('/', @b_path_components)};
1746 last if $i && defined $i->{copyfrom_path};
1747 unshift(@a_path_components, pop(@b_path_components));
1749 return undef unless defined $i && defined $i->{copyfrom_path};
1750 my $branch_from = $i->{copyfrom_path};
1751 if (@a_path_components) {
1752 print STDERR "branch_from: $branch_from => ";
1753 $branch_from .= '/'.join('/', @a_path_components);
1754 print STDERR $branch_from, "\n";
1756 my $r = $i->{copyfrom_rev};
1757 my $repos_root = $self->ra->{repos_root};
1758 my $url = $self->ra->{url};
1759 my $new_url = $repos_root . $branch_from;
1760 print STDERR "Found possible branch point: ",
1761 "$new_url => ", $self->full_url, ", $r\n";
1762 $branch_from =~ s#^/##;
1763 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1765 my $ref_id = $self->{ref_id};
1766 $ref_id =~ s/\@\d+$//;
1768 # just grow a tail if we're not unique enough :x
1769 $ref_id .= '-' while find_ref($ref_id);
1770 print STDERR "Initializing parent: $ref_id\n";
1771 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1773 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1774 if (!defined $r0 || !defined $parent) {
1775 my ($base, $head) = parse_revision_argument(0, $r);
1777 $gs->fetch($base, $r);
1779 ($r0, $parent) = $gs->last_rev_commit;
1781 if (defined $r0 && defined $parent) {
1782 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1784 if ($self->ra->can_do_switch) {
1785 $self->assert_index_clean($parent);
1786 print STDERR "Following parent with do_switch\n";
1787 # do_switch works with svn/trunk >= r22312, but that
1788 # is not included with SVN 1.4.3 (the latest version
1789 # at the moment), so we can't rely on it
1790 $self->{last_commit} = $parent;
1791 $ed = SVN::Git::Fetcher->new($self);
1792 $gs->ra->gs_do_switch($r0, $rev, $gs,
1793 $self->full_url, $ed)
1794 or die "SVN connection failed somewhere...\n";
1796 print STDERR "Following parent with do_update\n";
1797 $ed = SVN::Git::Fetcher->new($self);
1798 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1799 or die "SVN connection failed somewhere...\n";
1801 print STDERR "Successfully followed parent\n";
1802 return $self->make_log_entry($rev, [$parent], $ed);
1808 my ($self, $paths, $rev) = @_;
1810 my ($last_rev, @parents);
1811 if (my $lc = $self->last_commit) {
1812 # we can have a branch that was deleted, then re-added
1813 # under the same name but copied from another path, in
1814 # which case we'll have multiple parents (we don't
1815 # want to break the original ref, nor lose copypath info):
1816 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1817 push @{$log_entry->{parents}}, $lc;
1820 $ed = SVN::Git::Fetcher->new($self);
1821 $last_rev = $self->{last_rev};
1826 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1829 $ed = SVN::Git::Fetcher->new($self);
1831 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1832 die "SVN connection failed somewhere...\n";
1834 $self->make_log_entry($rev, \@parents, $ed);
1838 my ($self, $ed) = @_;
1840 my $h = $ed->{empty};
1841 foreach (sort keys %$h) {
1842 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1843 push @out, " $act: " . uri_encode($_);
1844 warn "W: $act: $_\n";
1846 foreach my $t (qw/dir_prop file_prop/) {
1847 $h = $ed->{$t} or next;
1848 foreach my $path (sort keys %$h) {
1849 my $ppath = $path eq '' ? '.' : $path;
1850 foreach my $prop (sort keys %{$h->{$path}}) {
1851 next if $SKIP_PROP{$prop};
1852 my $v = $h->{$path}->{$prop};
1853 my $t_ppath_prop = "$t: " .
1854 uri_encode($ppath) . ' ' .
1857 push @out, " +$t_ppath_prop " .
1860 push @out, " -$t_ppath_prop";
1865 foreach my $t (qw/absent_file absent_directory/) {
1866 $h = $ed->{$t} or next;
1867 foreach my $parent (sort keys %$h) {
1868 foreach my $path (sort @{$h->{$parent}}) {
1869 push @out, " $t: " .
1870 uri_encode("$parent/$path");
1871 warn "W: $t: $parent/$path ",
1872 "Insufficient permissions?\n";
1879 sub parse_svn_date {
1880 my $date = shift || return '+0000 1970-01-01 00:00:00';
1881 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1882 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1883 croak "Unable to parse date: $date\n";
1884 "+0000 $Y-$m-$d $H:$M:$S";
1889 if (!defined $author || length $author == 0) {
1890 $author = '(no author)';
1892 if (defined $::_authors && ! defined $::users{$author}) {
1893 die "Author: $author not defined in $::_authors file\n";
1898 sub make_log_entry {
1899 my ($self, $rev, $parents, $ed) = @_;
1900 my $untracked = $self->get_untracked($ed);
1902 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1903 print $un "r$rev\n" or croak $!;
1904 print $un $_, "\n" foreach @$untracked;
1905 my %log_entry = ( parents => $parents || [], revision => $rev,
1909 my $logged = delete $self->{logged_rev_props};
1910 if (!$logged || $self->{-want_revprops}) {
1911 my $rp = $self->ra->rev_proplist($rev);
1912 foreach (sort keys %$rp) {
1914 if (/^svn:(author|date|log)$/) {
1915 $log_entry{$1} = $v;
1916 } elsif ($_ eq 'svm:headrev') {
1919 print $un " rev_prop: ", uri_encode($_), ' ',
1920 uri_encode($v), "\n";
1924 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1926 close $un or croak $!;
1928 $log_entry{date} = parse_svn_date($log_entry{date});
1929 $log_entry{log} .= "\n";
1930 my $author = $log_entry{author} = check_author($log_entry{author});
1931 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1933 if (defined $headrev && $self->use_svm_props) {
1934 if ($self->rewrite_root) {
1935 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1938 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1939 # we don't want "SVM: initializing mirror for junk" ...
1940 return undef if $r == 0;
1941 my $svm = $self->svm;
1942 if ($uuid ne $svm->{uuid}) {
1943 die "UUID mismatch on SVM path:\n",
1944 "expected: $svm->{uuid}\n",
1947 my $full_url = $self->full_url;
1948 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
1949 die "Failed to replace '$svm->{replace}' with ",
1950 "'$svm->{source}' in $full_url\n";
1951 # throw away username for storing in records
1952 remove_username($full_url);
1953 $log_entry{metadata} = "$full_url\@$r $uuid";
1954 $log_entry{svm_revision} = $r;
1955 $email ||= "$author\@$uuid"
1956 } elsif ($self->use_svnsync_props) {
1957 my $full_url = $self->svnsync->{url};
1958 $full_url .= "/$self->{path}" if length $self->{path};
1959 remove_username($full_url);
1960 my $uuid = $self->svnsync->{uuid};
1961 $log_entry{metadata} = "$full_url\@$rev $uuid";
1962 $email ||= "$author\@$uuid"
1964 my $url = $self->metadata_url;
1965 remove_username($url);
1966 $log_entry{metadata} = "$url\@$rev " .
1967 $self->ra->get_uuid;
1968 $email ||= "$author\@" . $self->ra->get_uuid;
1970 $log_entry{name} = $name;
1971 $log_entry{email} = $email;
1976 my ($self, $min_rev, $max_rev, @parents) = @_;
1977 my ($last_rev, $last_commit) = $self->last_rev_commit;
1978 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1979 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1983 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1984 $self->{inject_parents} = { $rev => $tree };
1985 $self->fetch(undef, undef);
1989 my ($self, $tree) = (shift, shift);
1990 my $log_entry = ::get_commit_entry($tree);
1991 unless ($self->{last_rev}) {
1992 fatal("Must have an existing revision to commit\n");
1994 my %ed_opts = ( r => $self->{last_rev},
1995 log => $log_entry->{log},
1997 tree_a => $self->{last_commit},
2000 $self->set_tree_cb($log_entry, $tree, @_) },
2001 svn_path => $self->{path} );
2002 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2003 print "No changes\nr$self->{last_rev} = $tree\n";
2009 my $db_path = $self->db_path;
2010 return if (-e $db_path && ! -z $db_path);
2011 return unless ::verify_ref($self->refname.'^0');
2012 if (-f $self->{db_root}) {
2013 rename $self->{db_root}, $db_path or die
2014 "rename $self->{db_root} => $db_path failed: $!\n";
2015 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2016 symlink $base, $self->{db_root} or die
2017 "symlink $base => $self->{db_root} failed: $!\n";
2020 print "Rebuilding $db_path ...\n";
2021 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
2023 my $full_url = $self->full_url;
2024 remove_username($full_url);
2026 while (<$rev_list>) {
2029 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
2030 my ($url, $rev, $uuid) = ::cmt_metadata($c);
2031 remove_username($url);
2033 # ignore merges (from set-tree)
2034 next if (!defined $rev || !$uuid);
2036 # if we merged or otherwise started elsewhere, this is
2037 # how we break out of it
2038 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2039 ($full_url && $url && ($url ne $full_url))) {
2043 $svn_uuid ||= $uuid;
2045 $self->rev_db_set($rev, $c);
2046 print "r$rev = $c\n";
2048 command_close_pipe($rev_list, $ctx);
2049 print "Done rebuilding $db_path\n";
2053 # Tie::File seems to be prone to offset errors if revisions get sparse,
2054 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2055 # one of my favorite modules is out :< Next up would be one of the DBM
2056 # modules, but I'm not sure which is most portable... So I'll just
2057 # go with something that's plain-text, but still capable of
2058 # being randomly accessed. So here's my ultra-simple fixed-width
2059 # database. All records are 40 characters + "\n", so it's easy to seek
2060 # to a revision: (41 * rev) is the byte offset.
2061 # A record of 40 0s denotes an empty revision.
2062 # And yes, it's still pretty fast (faster than Tie::File).
2063 # These files are disposable unless noMetadata or useSvmProps is set
2066 my ($fh, $rev, $commit) = @_;
2067 my $offset = $rev * 41;
2068 # assume that append is the common case:
2069 seek $fh, 0, 2 or croak $!;
2071 if ($pos < $offset) {
2072 for (1 .. (($offset - $pos) / 41)) {
2073 print $fh (('0' x 40),"\n") or croak $!;
2076 seek $fh, $offset, 0 or croak $!;
2077 print $fh $commit,"\n" or croak $!;
2083 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2084 mkpath([$dir]) unless -d $dir;
2085 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2086 close $fh or die "Couldn't close (create) $path: $!\n";
2091 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2092 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2093 my $db = $self->db_path($uuid);
2094 my $db_lock = "$db.lock";
2097 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2098 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2102 $LOCKFILES{$db_lock} = 1;
2104 # both of these options make our .rev_db file very, very important
2105 # and we can't afford to lose it because rebuild() won't work
2106 if ($self->use_svm_props || $self->no_metadata) {
2108 copy($db, $db_lock) or die "rev_db_set(@_): ",
2110 "$db => $db_lock ($!)\n";
2112 rename $db, $db_lock or die "rev_db_set(@_): ",
2113 "Failed to rename: ",
2114 "$db => $db_lock ($!)\n";
2116 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2117 _rev_db_set($fh, $rev, $commit);
2119 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2120 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2122 close $fh or croak $!;
2125 command_noisy('update-ref', '-m', "r$rev",
2126 $self->refname, $commit);
2128 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2129 "$db_lock => $db ($!)\n";
2130 delete $LOCKFILES{$db_lock};
2132 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2133 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2134 kill $sig, $$ if defined $sig;
2141 my $db_path = $self->db_path;
2142 my @stat = stat $db_path or return 0;
2143 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2144 my $max = $stat[7] / 41;
2145 (($max > 0) ? $max - 1 : 0);
2149 my ($self, $rev, $uuid) = @_;
2151 my $offset = $rev * 41;
2152 my $db_path = $self->db_path($uuid);
2153 return undef unless -e $db_path;
2154 open my $fh, '<', $db_path or croak $!;
2155 if (sysseek($fh, $offset, 0) == $offset) {
2156 my $read = sysread($fh, $ret, 40);
2157 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2159 close $fh or croak $!;
2163 sub find_rev_before {
2164 my ($self, $rev, $eq_ok) = @_;
2165 --$rev unless $eq_ok;
2167 if (my $c = $self->rev_db_get($rev)) {
2172 return (undef, undef);
2176 my ($class, $repo_id, $ref_id, $path) = @_;
2177 unless (defined $repo_id && length $repo_id) {
2178 $repo_id = $Git::SVN::default_repo_id;
2180 unless (defined $ref_id && length $ref_id) {
2181 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2183 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2184 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2185 $_[3] = $path = '' unless (defined $path);
2186 mkpath(["$ENV{GIT_DIR}/svn"]);
2188 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2189 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2190 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2194 my ($self, $uuid) = @_;
2195 $uuid ||= $self->ra_uuid;
2196 "$self->{db_root}.$uuid";
2201 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2205 sub remove_username {
2206 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2209 package Git::SVN::Prompt;
2213 use vars qw/$_no_auth_cache $_username/;
2216 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2217 $may_save = undef if $_no_auth_cache;
2218 $default_username = $_username if defined $_username;
2219 if (defined $default_username && length $default_username) {
2220 if (defined $realm && length $realm) {
2221 print STDERR "Authentication realm: $realm\n";
2224 $cred->username($default_username);
2226 username($cred, $realm, $may_save, $pool);
2228 $cred->password(_read_password("Password for '" .
2229 $cred->username . "': ", $realm));
2230 $cred->may_save($may_save);
2231 $SVN::_Core::SVN_NO_ERROR;
2234 sub ssl_server_trust {
2235 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2236 $may_save = undef if $_no_auth_cache;
2237 print STDERR "Error validating server certificate for '$realm':\n";
2238 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2239 print STDERR " - The certificate is not issued by a trusted ",
2240 "authority. Use the\n",
2241 " fingerprint to validate the certificate manually!\n";
2243 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2244 print STDERR " - The certificate hostname does not match.\n";
2246 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2247 print STDERR " - The certificate is not yet valid.\n";
2249 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2250 print STDERR " - The certificate has expired.\n";
2252 if ($failures & $SVN::Auth::SSL::OTHER) {
2253 print STDERR " - The certificate has an unknown error.\n";
2256 "Certificate information:\n".
2257 " - Hostname: %s\n".
2258 " - Valid: from %s until %s\n".
2260 " - Fingerprint: %s\n",
2261 map $cert_info->$_, qw(hostname valid_from valid_until
2262 issuer_dname fingerprint);
2265 print STDERR $may_save ?
2266 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2267 "(R)eject or accept (t)emporarily? ";
2269 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2270 if ($choice =~ /^t$/i) {
2271 $cred->may_save(undef);
2272 } elsif ($choice =~ /^r$/i) {
2274 } elsif ($may_save && $choice =~ /^p$/i) {
2275 $cred->may_save($may_save);
2279 $cred->accepted_failures($failures);
2280 $SVN::_Core::SVN_NO_ERROR;
2283 sub ssl_client_cert {
2284 my ($cred, $realm, $may_save, $pool) = @_;
2285 $may_save = undef if $_no_auth_cache;
2286 print STDERR "Client certificate filename: ";
2288 chomp(my $filename = <STDIN>);
2289 $cred->cert_file($filename);
2290 $cred->may_save($may_save);
2291 $SVN::_Core::SVN_NO_ERROR;
2294 sub ssl_client_cert_pw {
2295 my ($cred, $realm, $may_save, $pool) = @_;
2296 $may_save = undef if $_no_auth_cache;
2297 $cred->password(_read_password("Password: ", $realm));
2298 $cred->may_save($may_save);
2299 $SVN::_Core::SVN_NO_ERROR;
2303 my ($cred, $realm, $may_save, $pool) = @_;
2304 $may_save = undef if $_no_auth_cache;
2305 if (defined $realm && length $realm) {
2306 print STDERR "Authentication realm: $realm\n";
2309 if (defined $_username) {
2310 $username = $_username;
2312 print STDERR "Username: ";
2314 chomp($username = <STDIN>);
2316 $cred->username($username);
2317 $cred->may_save($may_save);
2318 $SVN::_Core::SVN_NO_ERROR;
2321 sub _read_password {
2322 my ($prompt, $realm) = @_;
2323 print STDERR $prompt;
2325 require Term::ReadKey;
2326 Term::ReadKey::ReadMode('noecho');
2328 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2329 last if $key =~ /[\012\015]/; # \n\r
2332 Term::ReadKey::ReadMode('restore');
2341 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2342 $SVN::Node::dir.$SVN::Node::unknown.
2343 $SVN::Node::none.$SVN::Node::file.
2344 $SVN::Node::dir.$SVN::Node::unknown.
2345 $SVN::Auth::SSL::CNMISMATCH.
2346 $SVN::Auth::SSL::NOTYETVALID.
2347 $SVN::Auth::SSL::EXPIRED.
2348 $SVN::Auth::SSL::UNKNOWNCA.
2349 $SVN::Auth::SSL::OTHER;
2352 package SVN::Git::Fetcher;
2360 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2362 my ($class, $git_svn) = @_;
2363 my $self = SVN::Delta::Editor->new;
2364 bless $self, $class;
2365 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2366 $self->{empty} = {};
2367 $self->{dir_prop} = {};
2368 $self->{file_prop} = {};
2369 $self->{absent_dir} = {};
2370 $self->{absent_file} = {};
2371 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2375 sub set_path_strip {
2376 my ($self, $path) = @_;
2377 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2384 sub open_directory {
2385 my ($self, $path, $pb, $rev) = @_;
2390 my ($self, $path) = @_;
2391 if ($self->{path_strip}) {
2392 $path =~ s!$self->{path_strip}!! or
2393 die "Failed to strip path '$path' ($self->{path_strip})\n";
2399 my ($self, $path, $rev, $pb) = @_;
2401 my $gpath = $self->git_path($path);
2402 return undef if ($gpath eq '');
2404 # remove entire directories.
2405 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2406 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2408 $self->{c}, '--', $gpath);
2412 $self->{gii}->remove($_);
2413 print "\tD\t$_\n" unless $::_q;
2415 print "\tD\t$gpath/\n" unless $::_q;
2416 command_close_pipe($ls, $ctx);
2417 $self->{empty}->{$path} = 0
2419 $self->{gii}->remove($gpath);
2420 print "\tD\t$gpath\n" unless $::_q;
2426 my ($self, $path, $pb, $rev) = @_;
2427 my $gpath = $self->git_path($path);
2428 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2429 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2430 unless (defined $mode && defined $blob) {
2431 die "$path was not found in commit $self->{c} (r$rev)\n";
2433 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2434 pool => SVN::Pool->new, action => 'M' };
2438 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2439 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2440 delete $self->{empty}->{$dir};
2441 { path => $path, mode_a => 100644, mode_b => 100644,
2442 pool => SVN::Pool->new, action => 'A' };
2446 my ($self, $path, $cp_path, $cp_rev) = @_;
2447 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2448 delete $self->{empty}->{$dir};
2449 $self->{empty}->{$path} = 1;
2453 sub change_dir_prop {
2454 my ($self, $db, $prop, $value) = @_;
2455 $self->{dir_prop}->{$db->{path}} ||= {};
2456 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2460 sub absent_directory {
2461 my ($self, $path, $pb) = @_;
2462 $self->{absent_dir}->{$pb->{path}} ||= [];
2463 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2468 my ($self, $path, $pb) = @_;
2469 $self->{absent_file}->{$pb->{path}} ||= [];
2470 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2474 sub change_file_prop {
2475 my ($self, $fb, $prop, $value) = @_;
2476 if ($prop eq 'svn:executable') {
2477 if ($fb->{mode_b} != 120000) {
2478 $fb->{mode_b} = defined $value ? 100755 : 100644;
2480 } elsif ($prop eq 'svn:special') {
2481 $fb->{mode_b} = defined $value ? 120000 : 100644;
2483 $self->{file_prop}->{$fb->{path}} ||= {};
2484 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2489 sub apply_textdelta {
2490 my ($self, $fb, $exp) = @_;
2491 my $fh = IO::File->new_tmpfile;
2493 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2494 # (but $base does not,) so dup() it for reading in close_file
2495 open my $dup, '<&', $fh or croak $!;
2496 my $base = IO::File->new_tmpfile;
2497 $base->autoflush(1);
2499 defined (my $pid = fork) or croak $!;
2501 open STDOUT, '>&', $base or croak $!;
2502 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2503 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2509 seek $base, 0, 0 or croak $!;
2510 my $md5 = Digest::MD5->new;
2511 $md5->addfile($base);
2512 my $got = $md5->hexdigest;
2513 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2515 " got: $got\n" if ($got ne $exp);
2518 seek $base, 0, 0 or croak $!;
2520 $fb->{base} = $base;
2521 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2525 my ($self, $fb, $exp) = @_;
2527 my $path = $self->git_path($fb->{path});
2528 if (my $fh = $fb->{fh}) {
2530 seek($fh, 0, 0) or croak $!;
2531 my $md5 = Digest::MD5->new;
2533 my $got = $md5->hexdigest;
2535 die "Checksum mismatch: $path\n",
2536 "expected: $exp\n got: $got\n";
2539 sysseek($fh, 0, 0) or croak $!;
2540 if ($fb->{mode_b} == 120000) {
2541 sysread($fh, my $buf, 5) == 5 or croak $!;
2542 $buf eq 'link ' or die "$path has mode 120000",
2543 "but is not a link\n";
2545 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2547 open STDIN, '<&', $fh or croak $!;
2548 exec qw/git-hash-object -w --stdin/ or croak $!;
2550 chomp($hash = do { local $/; <$out> });
2551 close $out or croak $!;
2552 close $fh or croak $!;
2553 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2554 close $fb->{base} or croak $!;
2556 $hash = $fb->{blob} or die "no blob information\n";
2559 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2560 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2566 $self->{nr} = $self->{gii}->{nr};
2567 delete $self->{gii};
2568 $self->SUPER::abort_edit(@_);
2573 $self->{git_commit_ok} = 1;
2574 $self->{nr} = $self->{gii}->{nr};
2575 delete $self->{gii};
2576 $self->SUPER::close_edit(@_);
2579 package SVN::Git::Editor;
2580 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2588 my ($class, $opts) = @_;
2589 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2590 die "$_ required!\n" unless (defined $opts->{$_});
2593 my $pool = SVN::Pool->new;
2594 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2595 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2598 # $opts->{ra} functions should not be used after this:
2599 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2600 $opts->{editor_cb}, $pool);
2601 my $self = SVN::Delta::Editor->new(@ce, $pool);
2602 bless $self, $class;
2603 foreach (qw/svn_path r tree_a tree_b/) {
2604 $self->{$_} = $opts->{$_};
2606 $self->{url} = $opts->{ra}->{url};
2607 $self->{mods} = $mods;
2608 $self->{types} = $types;
2609 $self->{pool} = $pool;
2610 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2612 $self->{path_prefix} = length $self->{svn_path} ?
2613 "$self->{svn_path}/" : '';
2618 my ($tree_a, $tree_b) = @_;
2619 my @diff_tree = qw(diff-tree -z -r);
2620 if ($_cp_similarity) {
2621 push @diff_tree, "-C$_cp_similarity";
2623 push @diff_tree, '-C';
2625 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2626 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2627 push @diff_tree, $tree_a, $tree_b;
2628 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2632 while (<$diff_fh>) {
2633 chomp $_; # this gets rid of the trailing "\0"
2634 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2635 $::sha1\s($::sha1)\s
2636 ([MTCRAD])\d*$/xo) {
2637 push @mods, { mode_a => $1, mode_b => $2,
2638 sha1_b => $3, chg => $4 };
2639 if ($4 =~ /^(?:C|R)$/) {
2644 } elsif ($state eq 'file_a') {
2645 my $x = $mods[$#mods] or croak "Empty array\n";
2646 if ($x->{chg} !~ /^(?:C|R)$/) {
2647 croak "Error parsing $_, $x->{chg}\n";
2651 } elsif ($state eq 'file_b') {
2652 my $x = $mods[$#mods] or croak "Empty array\n";
2653 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2654 croak "Error parsing $_, $x->{chg}\n";
2656 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2657 croak "Error parsing $_, $x->{chg}\n";
2662 croak "Error parsing $_\n";
2665 command_close_pipe($diff_fh, $ctx);
2669 sub check_diff_paths {
2670 my ($ra, $pfx, $rev, $mods) = @_;
2672 $pfx .= '/' if length $pfx;
2674 sub type_diff_paths {
2675 my ($ra, $types, $path, $rev) = @_;
2676 my @p = split m#/+#, $path;
2678 unless (defined $types->{$c}) {
2679 $types->{$c} = $ra->check_path($c, $rev);
2682 $c .= '/' . shift @p;
2683 next if defined $types->{$c};
2684 $types->{$c} = $ra->check_path($c, $rev);
2688 foreach my $m (@$mods) {
2689 foreach my $f (qw/file_a file_b/) {
2690 next unless defined $m->{$f};
2691 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2692 if (length $pfx.$dir && ! defined $types{$dir}) {
2693 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2701 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2705 my ($self, $path) = @_;
2706 $self->{path_prefix}.(defined $path ? $path : '');
2710 my ($self, $path) = @_;
2711 $self->{url} . '/' . $self->repo_path($path);
2716 my $rm = $self->{rm};
2717 delete $rm->{''}; # we never delete the url we're tracking
2720 foreach (keys %$rm) {
2721 my @d = split m#/#, $_;
2725 $c .= '/' . shift @d;
2729 delete $rm->{$self->{svn_path}};
2730 delete $rm->{''}; # we never delete the url we're tracking
2733 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2738 my @dn = split m#/#, $_;
2740 delete $rm->{join '/', @dn};
2747 command_close_pipe($fh, $ctx);
2749 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2750 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2751 $self->close_directory($bat->{$d}, $p);
2752 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2753 print "\tD+\t$d/\n" unless $::_q;
2754 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2759 sub open_or_add_dir {
2760 my ($self, $full_path, $baton) = @_;
2761 my $t = $self->{types}->{$full_path};
2763 die "$full_path not known in r$self->{r} or we have a bug!\n";
2765 if ($t == $SVN::Node::none) {
2766 return $self->add_directory($full_path, $baton,
2767 undef, -1, $self->{pool});
2768 } elsif ($t == $SVN::Node::dir) {
2769 return $self->open_directory($full_path, $baton,
2770 $self->{r}, $self->{pool});
2772 print STDERR "$full_path already exists in repository at ",
2773 "r$self->{r} and it is not a directory (",
2774 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2779 my ($self, $path) = @_;
2780 my $bat = $self->{bat};
2781 my $repo_path = $self->repo_path($path);
2782 return $bat->{''} unless (length $repo_path);
2783 my @p = split m#/+#, $repo_path;
2785 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2788 $c .= '/' . shift @p;
2789 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2795 my ($self, $m) = @_;
2796 my ($dir, $file) = split_path($m->{file_b});
2797 my $pbat = $self->ensure_path($dir);
2798 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2800 print "\tA\t$m->{file_b}\n" unless $::_q;
2801 $self->chg_file($fbat, $m);
2802 $self->close_file($fbat,undef,$self->{pool});
2806 my ($self, $m) = @_;
2807 my ($dir, $file) = split_path($m->{file_b});
2808 my $pbat = $self->ensure_path($dir);
2809 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2810 $self->url_path($m->{file_a}), $self->{r});
2811 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2812 $self->chg_file($fbat, $m);
2813 $self->close_file($fbat,undef,$self->{pool});
2817 my ($self, $path, $pbat) = @_;
2818 my $rpath = $self->repo_path($path);
2819 my ($dir, $file) = split_path($rpath);
2820 $self->{rm}->{$dir} = 1;
2821 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2825 my ($self, $m) = @_;
2826 my ($dir, $file) = split_path($m->{file_b});
2827 my $pbat = $self->ensure_path($dir);
2828 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2829 $self->url_path($m->{file_a}), $self->{r});
2830 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2831 $self->chg_file($fbat, $m);
2832 $self->close_file($fbat,undef,$self->{pool});
2834 ($dir, $file) = split_path($m->{file_a});
2835 $pbat = $self->ensure_path($dir);
2836 $self->delete_entry($m->{file_a}, $pbat);
2840 my ($self, $m) = @_;
2841 my ($dir, $file) = split_path($m->{file_b});
2842 my $pbat = $self->ensure_path($dir);
2843 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2844 $pbat,$self->{r},$self->{pool});
2845 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2846 $self->chg_file($fbat, $m);
2847 $self->close_file($fbat,undef,$self->{pool});
2850 sub T { shift->M(@_) }
2852 sub change_file_prop {
2853 my ($self, $fbat, $pname, $pval) = @_;
2854 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2858 my ($self, $fbat, $m) = @_;
2859 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2860 $self->change_file_prop($fbat,'svn:executable','*');
2861 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2862 $self->change_file_prop($fbat,'svn:executable',undef);
2864 my $fh = IO::File->new_tmpfile or croak $!;
2865 if ($m->{mode_b} =~ /^120/) {
2866 print $fh 'link ' or croak $!;
2867 $self->change_file_prop($fbat,'svn:special','*');
2868 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2869 $self->change_file_prop($fbat,'svn:special',undef);
2871 defined(my $pid = fork) or croak $!;
2873 open STDOUT, '>&', $fh or croak $!;
2874 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2878 $fh->flush == 0 or croak $!;
2879 seek $fh, 0, 0 or croak $!;
2881 my $md5 = Digest::MD5->new;
2882 $md5->addfile($fh) or croak $!;
2883 seek $fh, 0, 0 or croak $!;
2885 my $exp = $md5->hexdigest;
2886 my $pool = SVN::Pool->new;
2887 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2888 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2889 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2892 close $fh or croak $!;
2896 my ($self, $m) = @_;
2897 my ($dir, $file) = split_path($m->{file_b});
2898 my $pbat = $self->ensure_path($dir);
2899 print "\tD\t$m->{file_b}\n" unless $::_q;
2900 $self->delete_entry($m->{file_b}, $pbat);
2905 my ($p,$bat) = ($self->{pool}, $self->{bat});
2906 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2908 $self->close_directory($bat->{$_}, $p);
2910 $self->close_directory($bat->{''}, $p);
2911 $self->SUPER::close_edit($p);
2917 $self->SUPER::abort_edit($self->{pool});
2922 $self->SUPER::DESTROY(@_);
2923 $self->{pool}->clear;
2926 # this drives the editor
2929 my $mods = $self->{mods};
2930 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2931 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2933 if (defined $o{$f}) {
2936 fatal("Invalid change type: $f\n");
2939 $self->rmdirs if $_rmdir;
2945 return scalar @$mods;
2948 package Git::SVN::Ra;
2949 use vars qw/@ISA $config_dir $_log_window_size/;
2952 my ($can_do_switch, %ignored_err, $RA);
2955 # enforce temporary pool usage for some simple functions
2957 foreach (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
2960 my \$pool = SVN::Pool->new;
2961 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2963 wantarray ? \@ret : \$ret[0]; }\n";
2966 eval "$e; 1;" or die $@;
2970 my ($class, $url) = @_;
2972 return $RA if ($RA && $RA->{url} eq $url);
2974 SVN::_Core::svn_config_ensure($config_dir, undef);
2975 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2976 SVN::Client::get_simple_provider(),
2977 SVN::Client::get_ssl_server_trust_file_provider(),
2978 SVN::Client::get_simple_prompt_provider(
2979 \&Git::SVN::Prompt::simple, 2),
2980 SVN::Client::get_ssl_client_cert_prompt_provider(
2981 \&Git::SVN::Prompt::ssl_client_cert, 2),
2982 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2983 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2984 SVN::Client::get_username_provider(),
2985 SVN::Client::get_ssl_server_trust_prompt_provider(
2986 \&Git::SVN::Prompt::ssl_server_trust),
2987 SVN::Client::get_username_prompt_provider(
2988 \&Git::SVN::Prompt::username, 2),
2990 my $config = SVN::Core::config_get_config($config_dir);
2991 my $self = SVN::Ra->new(url => $url, auth => $baton,
2993 pool => SVN::Pool->new,
2994 auth_provider_callbacks => $callbacks);
2995 $self->{svn_path} = $url;
2996 $self->{repos_root} = $self->get_repos_root;
2997 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2998 $self->{cache} = { check_path => { r => 0, data => {} },
2999 get_dir => { r => 0, data => {} } };
3000 $RA = bless $self, $class;
3004 my ($self, $path, $r) = @_;
3005 my $cache = $self->{cache}->{check_path};
3006 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3007 return $cache->{data}->{$path};
3009 my $pool = SVN::Pool->new;
3010 my $t = $self->SUPER::check_path($path, $r, $pool);
3012 if ($r != $cache->{r}) {
3013 %{$cache->{data}} = ();
3016 $cache->{data}->{$path} = $t;
3020 my ($self, $dir, $r) = @_;
3021 my $cache = $self->{cache}->{get_dir};
3022 if ($r == $cache->{r}) {
3023 if (my $x = $cache->{data}->{$dir}) {
3024 return wantarray ? @$x : $x->[0];
3027 my $pool = SVN::Pool->new;
3028 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3029 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3031 if ($r != $cache->{r}) {
3032 %{$cache->{data}} = ();
3035 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3036 wantarray ? (\%dirents, $r, $props) : \%dirents;
3040 # do not call the real DESTROY since we store ourselves in $RA
3044 my ($self, @args) = @_;
3045 my $pool = SVN::Pool->new;
3046 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3047 my $ret = $self->SUPER::get_log(@args, $pool);
3052 sub get_commit_editor {
3053 my ($self, $log, $cb, $pool) = @_;
3054 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3055 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3059 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3060 my $new = ($rev_a == $rev_b);
3061 my $path = $gs->{path};
3063 if ($new && -e $gs->{index}) {
3064 unlink $gs->{index} or die
3065 "Couldn't unlink index: $gs->{index}: $!\n";
3067 my $pool = SVN::Pool->new;
3068 $editor->set_path_strip($path);
3069 my (@pc) = split m#/#, $path;
3070 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3072 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3074 # Since we can't rely on svn_ra_reparent being available, we'll
3075 # just have to do some magic with set_path to make it so
3076 # we only want a partial path.
3078 my $final = join('/', @pc);
3080 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3081 $sp .= '/' if length $sp;
3084 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3086 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3088 $reporter->finish_report($pool);
3090 $editor->{git_commit_ok};
3093 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3094 # svn_ra_reparent didn't work before 1.4)
3096 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3097 my $path = $gs->{path};
3098 my $pool = SVN::Pool->new;
3100 my $full_url = $self->{url};
3101 my $old_url = $full_url;
3102 $full_url .= "/$path" if length $path;
3103 my ($ra, $reparented);
3104 if ($old_url ne $full_url) {
3105 if ($old_url !~ m#^svn(\+ssh)?://#) {
3106 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3108 $self->{url} = $full_url;
3111 $ra = Git::SVN::Ra->new($full_url);
3115 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3116 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3117 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3118 $reporter->finish_report($pool);
3121 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3122 $self->{url} = $old_url;
3126 $editor->{git_commit_ok};
3129 sub longest_common_path {
3130 my ($gsv, $globs) = @_;
3132 my $common_max = scalar @$gsv;
3134 foreach my $gs (@$gsv) {
3135 my @tmp = split m#/#, $gs->{path};
3138 $p .= length($p) ? "/$_" : $_;
3144 $common_max += scalar @$globs;
3145 foreach my $glob (@$globs) {
3146 my @tmp = split m#/#, $glob->{path}->{left};
3149 $p .= length($p) ? "/$_" : $_;
3155 my $longest_path = '';
3156 foreach (sort {length $b <=> length $a} keys %common) {
3157 if ($common{$_} == $common_max) {
3165 sub gs_fetch_loop_common {
3166 my ($self, $base, $head, $gsv, $globs) = @_;
3167 return if ($base > $head);
3168 my $inc = $_log_window_size;
3169 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3170 my $longest_path = longest_common_path($gsv, $globs);
3174 my $err_handler = $SVN::Error::handler;
3175 $SVN::Error::handler = sub {
3177 skip_unknown_revs($err);
3180 my ($paths, $r, $author, $date, $log) = @_;
3181 [ dup_changed_paths($paths),
3182 { author => $author, date => $date, log => $log } ];
3184 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3185 sub { $revs{$_[1]} = _cb(@_) });
3186 if ($err && $max >= $head) {
3187 print STDERR "Path '$longest_path' ",
3188 "was probably deleted:\n",
3189 $err->expanded_message,
3190 "\nWill attempt to follow ",
3191 "revisions r$min .. r$max ",
3192 "committed before the deletion\n";
3194 while (--$hi >= $min) {
3196 $self->get_log([$longest_path], $min, $hi,
3199 $revs{$_[1]} = _cb(@_) });
3201 print STDERR "r$min .. r$ok OK\n";
3206 $SVN::Error::handler = $err_handler;
3208 my %exists = map { $_->{path} => $_ } @$gsv;
3209 foreach my $r (sort {$a <=> $b} keys %revs) {
3210 my ($paths, $logged) = @{$revs{$r}};
3212 foreach my $gs ($self->match_globs(\%exists, $paths,
3214 if ($gs->rev_db_max >= $r) {
3217 next unless $gs->match_paths($paths, $r);
3218 $gs->{logged_rev_props} = $logged;
3219 if (my $last_commit = $gs->last_commit) {
3220 $gs->assert_index_clean($last_commit);
3222 my $log_entry = $gs->do_fetch($paths, $r);
3224 $gs->do_git_commit($log_entry);
3227 foreach my $g (@$globs) {
3228 my $k = "svn-remote.$g->{remote}." .
3230 Git::SVN::tmp_config($k, $r);
3233 # pre-fill the .rev_db since it'll eventually get filled in
3234 # with '0' x40 if something new gets committed
3235 foreach my $gs (@$gsv) {
3236 next if defined $gs->rev_db_get($max);
3237 $gs->rev_db_set($max, 0 x40);
3239 foreach my $g (@$globs) {
3240 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3241 Git::SVN::tmp_config($k, $max);
3243 last if $max >= $head;
3246 $max = $head if ($max > $head);
3251 my ($self, $exists, $paths, $globs, $r) = @_;
3254 my ($self, $exists, $g, $r) = @_;
3255 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3256 return unless scalar @x == 3;
3257 my $dirents = $x[0];
3258 foreach my $de (keys %$dirents) {
3259 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3260 my $p = $g->{path}->full_path($de);
3261 next if $exists->{$p};
3262 next if (length $g->{path}->{right} &&
3263 ($self->check_path($p, $r) !=
3265 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3266 $g->{ref}->full_path($de), 1);
3269 foreach my $g (@$globs) {
3270 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3271 if ($path->{action} =~ /^[AR]$/) {
3272 get_dir_check($self, $exists, $g, $r);
3275 foreach (keys %$paths) {
3276 if (/$g->{path}->{left_regex}/ &&
3277 !/$g->{path}->{regex}/) {
3278 next if $paths->{$_}->{action} !~ /^[AR]$/;
3279 get_dir_check($self, $exists, $g, $r);
3281 next unless /$g->{path}->{regex}/;
3283 my $pathname = $g->{path}->full_path($p);
3284 next if $exists->{$pathname};
3285 next if ($self->check_path($pathname, $r) !=
3287 $exists->{$pathname} = Git::SVN->init(
3288 $self->{url}, $pathname, undef,
3289 $g->{ref}->full_path($p), 1);
3292 foreach (split m#/#, $g->{path}->{left}) {
3294 next unless ($paths->{$c} &&
3295 ($paths->{$c}->{action} =~ /^[AR]$/));
3296 get_dir_check($self, $exists, $g, $r);
3304 return $self->{url} if ($self->{url} eq $self->{repos_root});
3305 my $url = $self->{repos_root};
3306 my @components = split(m!/!, $self->{svn_path});
3309 $url .= "/$c" if length $c;
3310 eval { (ref $self)->new($url)->get_latest_revnum };
3311 } while ($@ && ($c = shift @components));
3317 unless (defined $can_do_switch) {
3318 my $pool = SVN::Pool->new;
3320 $self->do_switch(1, '', 0, $self->{url},
3321 SVN::Delta::Editor->new, $pool);
3326 $rep->abort_report($pool);
3334 sub skip_unknown_revs {
3336 my $errno = $err->apr_err();
3337 # Maybe the branch we're tracking didn't
3338 # exist when the repo started, so it's
3339 # not an error if it doesn't, just continue
3341 # Wonderfully consistent library, eh?
3342 # 160013 - svn:// and file://
3343 # 175002 - http(s)://
3344 # 175007 - http(s):// (this repo required authorization, too...)
3345 # More codes may be discovered later...
3346 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3347 my $err_key = $err->expanded_message;
3348 # revision numbers change every time, filter them out
3349 $err_key =~ s/\d+/\0/g;
3350 $err_key = "$errno\0$err_key";
3351 unless ($ignored_err{$err_key}) {
3352 warn "W: Ignoring error from SVN, path probably ",
3353 "does not exist: ($errno): ",
3354 $err->expanded_message,"\n";
3355 $ignored_err{$err_key} = 1;
3359 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3362 # svn_log_changed_path_t objects passed to get_log are likely to be
3363 # overwritten even if only the refs are copied to an external variable,
3364 # so we should dup the structures in their entirety. Using an externally
3365 # passed pool (instead of our temporary and quickly cleared pool in
3366 # Git::SVN::Ra) does not help matters at all...
3367 sub dup_changed_paths {
3369 return undef unless $paths;
3371 foreach my $p (keys %$paths) {
3372 my $i = $paths->{$p};
3373 my %s = map { $_ => $i->$_ }
3374 qw/copyfrom_path copyfrom_rev action/;
3380 package Git::SVN::Log;
3383 use POSIX qw/strftime/;
3384 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3385 %rusers $show_commit $incremental/;
3390 return 1 if defined $c->{r};
3392 # big commit message got truncated by the 16k pretty buffer in rev-list
3393 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3394 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3396 my @log = command(qw/cat-file commit/, $c->{c});
3398 # shift off the headers
3399 shift @log while ($log[0] ne '');
3402 # TODO: make $c->{l} not have a trailing newline in the future
3403 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3405 (undef, $c->{r}, undef) = ::extract_metadata(
3406 (grep(/^git-svn-id: /, @log))[-1]);
3408 return defined $c->{r};
3414 $dcvar = 'color.diff';
3415 $dc = `git-config --get $dcvar`;
3417 # nothing at all; fallback to "diff.color"
3418 $dcvar = 'diff.color';
3419 $dc = `git-config --get $dcvar`;
3422 if ($dc eq 'auto') {
3424 $pc = `git-config --get color.pager`;
3426 # does not have it -- fallback to pager.color
3427 $pc = `git-config --bool --get pager.color`;
3430 $pc = `git-config --bool --get color.pager`;
3436 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3437 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3441 return 0 if $dc eq 'never';
3442 return 1 if $dc eq 'always';
3443 chomp($dc = `git-config --bool --get $dcvar`);
3444 return ($dc eq 'true');
3447 sub git_svn_log_cmd {
3448 my ($r_min, $r_max, @args) = @_;
3450 foreach my $x (@args) {
3452 next unless ::verify_ref("$x^0");
3457 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3458 $gs ||= Git::SVN->_new;
3459 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3461 push @cmd, '-r' unless $non_recursive;
3462 push @cmd, qw/--raw --name-status/ if $verbose;
3463 push @cmd, '--color' if log_use_color();
3464 return @cmd unless defined $r_max;
3465 if ($r_max == $r_min) {
3466 push @cmd, '--max-count=1';
3467 if (my $c = $gs->rev_db_get($r_max)) {
3471 my ($c_min, $c_max);
3472 $c_max = $gs->rev_db_get($r_max);
3473 $c_min = $gs->rev_db_get($r_min);
3474 if (defined $c_min && defined $c_max) {
3475 if ($r_max > $r_max) {
3476 push @cmd, "$c_min..$c_max";
3478 push @cmd, "$c_max..$c_min";
3480 } elsif ($r_max > $r_min) {
3489 # adapted from pager.c
3491 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3492 if (!defined $pager) {
3494 } elsif (length $pager == 0 || $pager eq 'cat') {
3500 return unless -t *STDOUT;
3501 pipe my $rfd, my $wfd or return;
3502 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3504 open STDOUT, '>&', $wfd or
3505 ::fatal "Can't redirect to stdout: $!\n";
3508 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3509 $ENV{LESS} ||= 'FRSX';
3510 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3513 sub tz_to_s_offset {
3516 return ($1 * 60) + ($tz * 3600);
3519 sub get_author_info {
3520 my ($dest, $author, $t, $tz) = @_;
3521 $author =~ s/(?:^\s*|\s*$)//g;
3522 $dest->{a_raw} = $author;
3525 $au = $rusers{$author} || undef;
3528 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3533 # Date::Parse isn't in the standard Perl distro :(
3534 if ($tz =~ s/^\+//) {
3535 $t += tz_to_s_offset($tz);
3536 } elsif ($tz =~ s/^\-//) {
3537 $t -= tz_to_s_offset($tz);
3539 $dest->{t_utc} = $t;
3542 sub process_commit {
3543 my ($c, $r_min, $r_max, $defer) = @_;
3544 if (defined $r_min && defined $r_max) {
3545 if ($r_min == $c->{r} && $r_min == $r_max) {
3549 return 1 if $r_min == $r_max;
3550 if ($r_min < $r_max) {
3551 # we need to reverse the print order
3552 return 0 if (defined $limit && --$limit < 0);
3556 if ($r_min != $r_max) {
3557 return 1 if ($r_min < $c->{r});
3558 return 1 if ($r_max > $c->{r});
3561 return 0 if (defined $limit && --$limit < 0);
3570 if (my $l = $c->{l}) {
3571 while ($l->[0] =~ /^\s*$/) { shift @$l }
3574 $l_fmt ||= 'A' . length($c->{r});
3575 print 'r',pack($l_fmt, $c->{r}),' | ';
3576 print "$c->{c} | " if $show_commit;
3579 show_commit_normal($c);
3583 sub show_commit_changed_paths {
3585 return unless $c->{changed};
3586 print "Changed paths:\n", @{$c->{changed}};
3589 sub show_commit_normal {
3591 print '-' x72, "\nr$c->{r} | ";
3592 print "$c->{c} | " if $show_commit;
3593 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3594 localtime($c->{t_utc})), ' | ';
3597 if (my $l = $c->{l}) {
3598 while ($l->[$#$l] eq "\n" && $#$l > 0
3599 && $l->[($#$l - 1)] eq "\n") {
3602 $nr_line = scalar @$l;
3604 print "1 line\n\n\n";
3606 if ($nr_line == 1) {
3607 $nr_line = '1 line';
3609 $nr_line .= ' lines';
3611 print $nr_line, "\n";
3612 show_commit_changed_paths($c);
3614 print $_ foreach @$l;
3618 show_commit_changed_paths($c);
3622 foreach my $x (qw/raw stat diff/) {
3625 print $_ foreach @{$c->{$x}}
3632 my ($r_min, $r_max);
3633 my $r_last = -1; # prevent dupes
3639 if (defined $::_revision) {
3640 if ($::_revision =~ /^(\d+):(\d+)$/) {
3641 ($r_min, $r_max) = ($1, $2);
3642 } elsif ($::_revision =~ /^\d+$/) {
3643 $r_min = $r_max = $::_revision;
3645 ::fatal "-r$::_revision is not supported, use ",
3646 "standard \'git log\' arguments instead\n";
3651 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3652 my $log = command_output_pipe(@args);
3654 my (@k, $c, $d, $stat);
3655 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3657 if (/^${esc_color}commit ($::sha1_short)/o) {
3659 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3661 process_commit($c, $r_min, $r_max, \@k) or
3666 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3667 get_author_info($c, $1, $2, $3);
3668 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3670 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3671 push @{$c->{raw}}, $_;
3672 } elsif (/^${esc_color}[ACRMDT]\t/) {
3673 # we could add $SVN->{svn_path} here, but that requires
3674 # remote access at the moment (repo_path_split)...
3675 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3676 push @{$c->{changed}}, $_;
3677 } elsif (/^${esc_color}diff /o) {
3679 push @{$c->{diff}}, $_;
3681 push @{$c->{diff}}, $_;
3682 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3683 $esc_color*[\+\-]*$esc_color$/x) {
3685 push @{$c->{stat}}, $_;
3686 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3687 push @{$c->{stat}}, $_;
3689 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3690 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3691 } elsif (s/^${esc_color} //o) {
3692 push @{$c->{l}}, $_;
3695 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3697 process_commit($c, $r_min, $r_max, \@k);
3703 process_commit($_, $r_min, $r_max) foreach reverse @k;
3707 print '-' x72,"\n" unless $incremental || $oneline;
3710 package Git::SVN::Migration;
3711 # these version numbers do NOT correspond to actual version numbers
3712 # of git nor git-svn. They are just relative.
3714 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3716 # v1 layout: .git/$id/info/url, refs/remotes/$id
3718 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3720 # v3 layout: .git/svn/$id, refs/remotes/$id
3721 # - info/url may remain for backwards compatibility
3722 # - this is what we migrate up to this layout automatically,
3723 # - this will be used by git svn init on single branches
3724 # v3.1 layout (auto migrated):
3725 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3726 # for backwards compatibility
3728 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3729 # - this is only created for newly multi-init-ed
3730 # repositories. Similar in spirit to the
3731 # --use-separate-remotes option in git-clone (now default)
3732 # - we do not automatically migrate to this (following
3733 # the example set by core git)
3737 use File::Path qw/mkpath/;
3738 use File::Basename qw/dirname basename/;
3739 use vars qw/$_minimize/;
3741 sub migrate_from_v0 {
3742 my $git_dir = $ENV{GIT_DIR};
3743 return undef unless -d $git_dir;
3744 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3748 my ($id, $orig_ref) = ($_, $_);
3749 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3750 next unless -f "$git_dir/$id/info/url";
3751 my $new_ref = "refs/remotes/$id";
3752 if (::verify_ref("$new_ref^0")) {
3753 print STDERR "W: $orig_ref is probably an old ",
3754 "branch used by an ancient version of ",
3756 "However, $new_ref also exists.\n",
3757 "We will not be able ",
3758 "to use this branch until this ",
3759 "ambiguity is resolved.\n";
3762 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3763 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3764 command_noisy('update-ref', $new_ref, $orig_ref);
3765 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3768 command_close_pipe($fh, $ctx);
3769 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3773 sub migrate_from_v1 {
3774 my $git_dir = $ENV{GIT_DIR};
3776 return $migrated unless -d $git_dir;
3777 my $svn_dir = "$git_dir/svn";
3779 # just in case somebody used 'svn' as their $id at some point...
3780 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3782 print STDERR "Migrating from a git-svn v1 layout...\n";
3784 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3785 "$svn_dir\n\t(required for this version ",
3786 "($::VERSION) of git-svn) does not. exist\n";
3787 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3790 next unless $x =~ s#^refs/remotes/##;
3792 next unless -f "$git_dir/$x/info/url";
3793 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3795 my $dn = dirname("$git_dir/svn/$x");
3796 mkpath([$dn]) unless -d $dn;
3797 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3798 mkpath(["$git_dir/svn/svn"]);
3799 print STDERR " - $git_dir/$x/info => ",
3800 "$git_dir/svn/$x/info\n";
3801 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3803 # don't worry too much about these, they probably
3804 # don't exist with repos this old (save for index,
3805 # and we can easily regenerate that)
3806 foreach my $f (qw/unhandled.log index .rev_db/) {
3807 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3810 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3811 rename "$git_dir/$x", "$git_dir/svn/$x" or
3816 command_close_pipe($fh, $ctx);
3817 print STDERR "Done migrating from a git-svn v1 layout\n";
3822 my ($l_map, $pfx, $path) = @_;
3824 foreach (<$path/*>) {
3825 if (-r "$_/info/url") {
3826 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3827 my $ref_id = $pfx . basename $_;
3828 my $url = ::file_to_s("$_/info/url");
3829 $l_map->{$ref_id} = $url;
3836 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3837 read_old_urls($l_map, $x, $_);
3841 sub migrate_from_v2 {
3842 my @cfg = command(qw/config -l/);
3843 return if grep /^svn-remote\..+\.url=/, @cfg;
3845 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3848 foreach my $ref_id (sort keys %l_map) {
3849 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3851 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3858 sub minimize_connections {
3859 my $r = Git::SVN::read_all_remotes();
3861 my $root_repos = {};
3862 foreach my $repo_id (keys %$r) {
3863 my $url = $r->{$repo_id}->{url} or next;
3864 my $fetch = $r->{$repo_id}->{fetch} or next;
3865 my $ra = Git::SVN::Ra->new($url);
3867 # skip existing cases where we already connect to the root
3868 if (($ra->{url} eq $ra->{repos_root}) ||
3869 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3871 $root_repos->{$ra->{url}} = $repo_id;
3875 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3876 my $root_path = $ra->{url};
3877 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3878 foreach my $path (keys %$fetch) {
3879 my $ref_id = $fetch->{$path};
3880 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3882 # make sure we can read when connecting to
3883 # a higher level of a repository
3884 my ($last_rev, undef) = $gs->last_rev_commit;
3885 if (!defined $last_rev) {
3887 $root_ra->get_latest_revnum;
3891 my $new = $root_path;
3892 $new .= length $path ? "/$path" : '';
3894 $root_ra->get_log([$new], $last_rev, $last_rev,
3898 $new_urls->{$ra->{repos_root}}->{$new} =
3899 { ref_id => $ref_id,
3900 old_repo_id => $repo_id,
3901 old_path => $path };
3906 foreach my $url (keys %$new_urls) {
3907 # see if we can re-use an existing [svn-remote "repo_id"]
3908 # instead of creating a(n ugly) new section:
3909 my $repo_id = $root_repos->{$url} ||
3910 Git::SVN::sanitize_remote_name($url);
3912 my $fetch = $new_urls->{$url};
3913 foreach my $path (keys %$fetch) {
3914 my $x = $fetch->{$path};
3915 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3916 my $pfx = "svn-remote.$x->{old_repo_id}";
3918 my $old_fetch = quotemeta("$x->{old_path}:".
3919 "refs/remotes/$x->{ref_id}");
3920 command_noisy(qw/config --unset/,
3921 "$pfx.fetch", '^'. $old_fetch . '$');
3922 delete $r->{$x->{old_repo_id}}->
3923 {fetch}->{$x->{old_path}};
3924 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3925 command_noisy(qw/config --unset/,
3927 push @emptied, $x->{old_repo_id}
3932 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3933 "$ENV{GIT_DIR}/config";
3935 The following [svn-remote] sections in your config file ($file) are empty
3936 and can be safely removed:
3938 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3942 sub migration_check {
3946 minimize_connections() if $_minimize;
3949 package Git::IndexInfo;
3952 use Git qw/command_input_pipe command_close_pipe/;
3956 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3957 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3961 my ($self, $path) = @_;
3962 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3963 return ++$self->{nr};
3969 my ($self, $mode, $hash, $path) = @_;
3970 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3971 return ++$self->{nr};
3978 command_close_pipe($self->{gui}, $self->{ctx});
3981 package Git::SVN::GlobSpec;
3986 my ($class, $glob) = @_;
3988 $re =~ s!/+$!!g; # no need for trailing slashes
3989 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3990 my ($left, $right) = ($1, $2);
3992 die "Only one '*' wildcard expansion ",
3993 "is supported (got $nr): '$glob'\n";
3994 } elsif ($nr == 0) {
3995 die "One '*' is needed for glob: '$glob'\n";
3997 $re = quotemeta($left) . $re . quotemeta($right);
3998 if (length $left && !($left =~ s!/+$!!g)) {
3999 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4001 if (length $right && !($right =~ s!^/+!!g)) {
4002 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4004 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4005 bless { left => $left, right => $right, left_regex => $left_re,
4006 regex => qr/$re/, glob => $glob }, $class;
4010 my ($self, $path) = @_;
4011 return (length $self->{left} ? "$self->{left}/" : '') .
4012 $path . (length $self->{right} ? "/$self->{right}" : '');
4020 $remotes = { # returned by read_all_remotes()
4022 # svn-remote.svn.url=https://svn.musicpd.org
4023 url => 'https://svn.musicpd.org',
4024 # svn-remote.svn.fetch=mpd/trunk:trunk
4026 'mpd/trunk' => 'trunk',
4028 # svn-remote.svn.tags=mpd/tags/*:tags/*
4033 regex => qr!mpd/tags/([^/]+)$!,
4039 regex => qr!tags/([^/]+)$!,
4046 $log_entry hashref as returned by libsvn_log_entry()
4048 log => 'whitespace-formatted log entry
4049 ', # trailing newline is preserved
4050 revision => '8', # integer
4051 date => '2004-02-24T17:01:44.108345Z', # commit date
4052 author => 'committer name'
4056 # this is generated by generate_diff();
4057 @mods = array of diff-index line hashes, each element represents one line
4058 of diff-index output
4060 diff-index line ($m hash)
4062 mode_a => first column of diff-index output, no leading ':',
4063 mode_b => second column of diff-index output,
4064 sha1_b => sha1sum of the final blob,
4065 chg => change type [MCRADT],
4066 file_a => original file name of a file (iff chg is 'C' or 'R')
4067 file_b => new/current file name of a file (any chg)
4071 # retval of read_url_paths{,_all}();
4073 # repository root url
4074 'https://svn.musicpd.org' => {
4075 # repository path # GIT_SVN_ID
4076 'mpd/trunk' => 'trunk',
4077 'mpd/tags/0.11.5' => 'tags/0.11.5',
4082 I don't trust the each() function on unless I created %hash myself
4083 because the internal iterator may not have started at base.