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/;
41 # import functions from Git into our packages, en masse
43 foreach (qw/command command_oneline command_noisy command_output_pipe
44 command_input_pipe command_close_pipe/) {
45 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
46 Git::SVN::Migration Git::SVN::Log Git::SVN),
48 *{"${package}::$_"} = \&{"Git::$_"};
55 $sha1 = qr/[a-f\d]{40}/;
56 $sha1_short = qr/[a-f\d]{4,40}/;
57 my ($_stdin, $_help, $_edit,
60 $_version, $_fetch_all, $_no_rebase,
61 $_merge, $_strategy, $_dry_run, $_local,
62 $_prefix, $_no_checkout, $_verbose);
63 $Git::SVN::_follow_parent = 1;
64 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
65 'config-dir=s' => \$Git::SVN::Ra::config_dir,
66 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
67 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
68 'authors-file|A=s' => \$_authors,
69 'repack:i' => \$Git::SVN::_repack,
70 'noMetadata' => \$Git::SVN::_no_metadata,
71 'useSvmProps' => \$Git::SVN::_use_svm_props,
72 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
73 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
74 'no-checkout' => \$_no_checkout,
76 'repack-flags|repack-args|repack-opts=s' =>
77 \$Git::SVN::_repack_flags,
80 my ($_trunk, $_tags, $_branches, $_stdlayout);
82 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
83 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
84 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
85 'stdlayout|s' => \$_stdlayout,
86 'minimize-url|m' => \$Git::SVN::_minimize_url,
87 'no-metadata' => sub { $icv{noMetadata} = 1 },
88 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
89 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
90 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
92 my %cmt_opts = ( 'edit|e' => \$_edit,
93 'rmdir' => \$SVN::Git::Editor::_rmdir,
94 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
95 'l=i' => \$SVN::Git::Editor::_rename_limit,
96 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
100 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
101 { 'revision|r=s' => \$_revision,
102 'fetch-all|all' => \$_fetch_all,
104 clone => [ \&cmd_clone, "Initialize and fetch revisions",
105 { 'revision|r=s' => \$_revision,
106 %fc_opts, %init_opts } ],
107 init => [ \&cmd_init, "Initialize a repo for tracking" .
108 " (requires URL argument)",
110 'multi-init' => [ \&cmd_multi_init,
111 "Deprecated alias for ".
112 "'$0 init -T<trunk> -b<branches> -t<tags>'",
114 dcommit => [ \&cmd_dcommit,
115 'Commit several diffs to merge with upstream',
116 { 'merge|m|M' => \$_merge,
117 'strategy|s=s' => \$_strategy,
118 'verbose|v' => \$_verbose,
119 'dry-run|n' => \$_dry_run,
120 'fetch-all|all' => \$_fetch_all,
121 'no-rebase' => \$_no_rebase,
122 %cmt_opts, %fc_opts } ],
123 'set-tree' => [ \&cmd_set_tree,
124 "Set an SVN repository to a git tree-ish",
125 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
126 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
127 { 'revision|r=i' => \$_revision } ],
128 'multi-fetch' => [ \&cmd_multi_fetch,
129 "Deprecated alias for $0 fetch --all",
130 { 'revision|r=s' => \$_revision, %fc_opts } ],
131 'migrate' => [ sub { },
132 # no-op, we automatically run this anyways,
133 'Migrate configuration/metadata/layout from
134 previous versions of git-svn',
135 { 'minimize' => \$Git::SVN::Migration::_minimize,
137 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
138 { 'limit=i' => \$Git::SVN::Log::limit,
139 'revision|r=s' => \$_revision,
140 'verbose|v' => \$Git::SVN::Log::verbose,
141 'incremental' => \$Git::SVN::Log::incremental,
142 'oneline' => \$Git::SVN::Log::oneline,
143 'show-commit' => \$Git::SVN::Log::show_commit,
144 'non-recursive' => \$Git::SVN::Log::non_recursive,
145 'authors-file|A=s' => \$_authors,
146 'color' => \$Git::SVN::Log::color,
147 'pager=s' => \$Git::SVN::Log::pager,
149 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
151 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
152 { 'merge|m|M' => \$_merge,
153 'verbose|v' => \$_verbose,
154 'strategy|s=s' => \$_strategy,
155 'local|l' => \$_local,
156 'fetch-all|all' => \$_fetch_all,
158 'commit-diff' => [ \&cmd_commit_diff,
159 'Commit a diff between two trees',
160 { 'message|m=s' => \$_message,
161 'file|F=s' => \$_file,
162 'revision|r=s' => \$_revision,
167 for (my $i = 0; $i < @ARGV; $i++) {
168 if (defined $cmd{$ARGV[$i]}) {
175 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
177 read_repo_config(\%opts);
178 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
179 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
180 'minimize-connections' => \$Git::SVN::Migration::_minimize,
181 'id|i=s' => \$Git::SVN::default_ref_id,
182 'svn-remote|remote|R=s' => sub {
183 $Git::SVN::no_reuse_existing = 1;
184 $Git::SVN::default_repo_id = $_[1] });
185 exit 1 if (!$rv && $cmd && $cmd ne 'log');
188 version() if $_version;
189 usage(1) unless defined $cmd;
190 load_authors() if $_authors;
192 # make sure we're always running
193 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
194 unless (-d $ENV{GIT_DIR}) {
195 if ($git_dir_user_set) {
196 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
197 "but it is not a directory\n";
199 my $git_dir = delete $ENV{GIT_DIR};
200 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
201 unless (length $cdup) {
202 die "Already at toplevel, but $git_dir ",
203 "not found '$cdup'\n";
205 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
206 unless (-d $git_dir) {
207 die "$git_dir still not found after going to ",
210 $ENV{GIT_DIR} = $git_dir;
213 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
214 Git::SVN::Migration::migration_check();
216 Git::SVN::init_vars();
218 Git::SVN::verify_remotes_sanity();
219 $cmd{$cmd}->[0]->(@ARGV);
222 post_fetch_checkout();
225 ####################### primary functions ######################
227 my $exit = shift || 0;
228 my $fd = $exit ? \*STDERR : \*STDOUT;
230 git-svn - bidirectional operations between a single Subversion tree and git
231 Usage: $0 <command> [options] [arguments]\n
233 print $fd "Available commands:\n" unless $cmd;
235 foreach (sort keys %cmd) {
236 next if $cmd && $cmd ne $_;
237 next if /^multi-/; # don't show deprecated commands
238 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
239 foreach (keys %{$cmd{$_}->[2]}) {
240 # mixed-case options are for .git/config only
241 next if /[A-Z]/ && /^[a-z]+$/i;
242 # prints out arguments as they should be passed:
243 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
244 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
246 split /\|/,$_)," $x\n";
250 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
251 arbitrary identifier if you're tracking multiple SVN branches/repositories in
252 one git repository and want to keep them separate. See git-svn(1) for more
259 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
264 unless (-d $ENV{GIT_DIR}) {
265 my @init_db = ('init');
266 push @init_db, "--template=$_template" if defined $_template;
267 if (defined $_shared) {
268 if ($_shared =~ /[a-z]/) {
269 push @init_db, "--shared=$_shared";
271 push @init_db, "--shared";
274 command_noisy(@init_db);
277 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
278 foreach my $i (keys %icv) {
279 die "'$set' and '$i' cannot both be set\n" if $set;
280 next unless defined $icv{$i};
281 command_noisy('config', "$pfx.$i", $icv{$i});
287 my $repo_path = shift or return;
288 mkpath([$repo_path]) unless -d $repo_path;
289 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
290 $ENV{GIT_DIR} = '.git';
294 my ($url, $path) = @_;
295 if (!defined $path &&
296 (defined $_trunk || defined $_branches || defined $_tags ||
297 defined $_stdlayout) &&
298 $url !~ m#^[a-z\+]+://#) {
301 $path = basename($url) if !defined $path || !length $path;
302 cmd_init($url, $path);
303 Git::SVN::fetch_all($Git::SVN::default_repo_id);
307 if (defined $_stdlayout) {
308 $_trunk = 'trunk' if (!defined $_trunk);
309 $_tags = 'tags' if (!defined $_tags);
310 $_branches = 'branches' if (!defined $_branches);
312 if (defined $_trunk || defined $_branches || defined $_tags) {
313 return cmd_multi_init(@_);
315 my $url = shift or die "SVN repository location required ",
316 "as a command-line argument\n";
320 Git::SVN->init($url);
324 if (grep /^\d+=./, @_) {
325 die "'<rev>=<commit>' fetch arguments are ",
326 "no longer supported.\n";
330 die "Usage: $0 fetch [--all] [svn-remote]\n";
332 $remote ||= $Git::SVN::default_repo_id;
336 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
342 if ($_stdin || !@commits) {
343 print "Reading from stdin...\n";
346 if (/\b($sha1_short)\b/o) {
347 unshift @commits, $1;
352 foreach my $c (@commits) {
353 my @tmp = command('rev-parse',$c);
354 if (scalar @tmp == 1) {
356 } elsif (scalar @tmp > 1) {
357 push @revs, reverse(command('rev-list',@tmp));
359 fatal "Failed to rev-parse $c\n";
362 my $gs = Git::SVN->new;
363 my ($r_last, $cmt_last) = $gs->last_rev_commit;
365 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
366 fatal "There are new revisions that were fetched ",
367 "and need to be merged (or acknowledged) ",
368 "before committing.\nlast rev: $r_last\n",
369 " current: $gs->{last_rev}\n";
371 $gs->set_tree($_) foreach @revs;
372 print "Done committing ",scalar @revs," revisions to SVN\n";
379 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
380 print "Committing to $url ...\n";
382 die "Unable to determine upstream SVN information from ",
386 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
387 if ($_no_rebase && scalar(@$linear_refs) > 1) {
388 warn "Attempting to commit more than one change while ",
389 "--no-rebase is enabled.\n",
390 "If these changes depend on each other, re-running ",
391 "without --no-rebase will be required."
393 foreach my $d (@$linear_refs) {
394 unless (defined $last_rev) {
395 (undef, $last_rev, undef) = cmt_metadata("$d~1");
396 unless (defined $last_rev) {
397 fatal "Unable to extract revision information ",
398 "from commit $d~1\n";
402 print "diff-tree $d~1 $d\n";
405 my %ed_opts = ( r => $last_rev,
406 log => get_commit_entry($d)->{log},
407 ra => Git::SVN::Ra->new($gs->full_url),
411 print "Committed r$_[0]\n";
415 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
416 print "No changes\n$d~1 == $d\n";
417 } elsif ($parents->{$d} && @{$parents->{$d}}) {
418 $gs->{inject_parents_dcommit}->{$cmt_rev} =
421 $_fetch_all ? $gs->fetch_all : $gs->fetch;
424 # we always want to rebase against the current HEAD,
425 # not any head that was passed to us
426 my @diff = command('diff-tree', 'HEAD',
430 @finish = rebase_cmd();
431 print STDERR "W: HEAD and ", $gs->refname,
432 " differ, using @finish:\n",
435 print "No changes between current HEAD and ",
437 "\nResetting to the latest ",
439 @finish = qw/reset --mixed/;
441 command_noisy(@finish, $gs->refname);
442 $last_rev = $cmt_rev;
448 my $revision_or_hash = shift;
450 if ($revision_or_hash =~ /^r\d+$/) {
454 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
456 die "Unable to determine upstream SVN information from ",
459 my $desired_revision = substr($revision_or_hash, 1);
460 $result = $gs->rev_db_get($desired_revision);
462 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
465 print "$result\n" if $result;
469 command_noisy(qw/update-index --refresh/);
470 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
472 die "Unable to determine upstream SVN information from ",
473 "working tree history\n";
475 if (command(qw/diff-index HEAD --/)) {
476 print STDERR "Cannot rebase with uncommited changes:\n";
477 command_noisy('status');
481 $_fetch_all ? $gs->fetch_all : $gs->fetch;
483 command_noisy(rebase_cmd(), $gs->refname);
486 sub cmd_show_ignore {
487 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
488 $gs ||= Git::SVN->new;
489 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
490 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
495 unless (defined $_trunk || defined $_branches || defined $_tags) {
499 # there are currently some bugs that prevent multi-init/multi-fetch
500 # setups from working well without this.
501 $Git::SVN::_minimize_url = 1;
503 $_prefix = '' unless defined $_prefix;
509 if (defined $_trunk) {
510 my $trunk_ref = $_prefix . 'trunk';
511 # try both old-style and new-style lookups:
512 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
514 my ($trunk_url, $trunk_path) =
515 complete_svn_url($url, $_trunk);
516 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
520 return unless defined $_branches || defined $_tags;
521 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
522 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
523 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
526 sub cmd_multi_fetch {
527 my $remotes = Git::SVN::read_all_remotes();
528 foreach my $repo_id (sort keys %$remotes) {
529 if ($remotes->{$repo_id}->{url}) {
530 Git::SVN::fetch_all($repo_id, $remotes);
535 # this command is special because it requires no metadata
536 sub cmd_commit_diff {
537 my ($ta, $tb, $url) = @_;
538 my $usage = "Usage: $0 commit-diff -r<revision> ".
539 "<tree-ish> <tree-ish> [<URL>]\n";
540 fatal($usage) if (!defined $ta || !defined $tb);
543 my $gs = eval { Git::SVN->new };
545 fatal("Needed URL or usable git-svn --id in ",
546 "the command-line\n", $usage);
549 $svn_path = $gs->{path};
551 unless (defined $_revision) {
552 fatal("-r|--revision is a required argument\n", $usage);
554 if (defined $_message && defined $_file) {
555 fatal("Both --message/-m and --file/-F specified ",
556 "for the commit message.\n",
557 "I have no idea what you mean\n");
559 if (defined $_file) {
560 $_message = file_to_s($_file);
562 $_message ||= get_commit_entry($tb)->{log};
564 my $ra ||= Git::SVN::Ra->new($url);
565 $svn_path ||= $ra->{svn_path};
568 $r = $ra->get_latest_revnum;
569 } elsif ($r !~ /^\d+$/) {
570 die "revision argument: $r not understood by git-svn\n";
572 my %ed_opts = ( r => $r,
577 editor_cb => sub { print "Committed r$_[0]\n" },
578 svn_path => $svn_path );
579 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
580 print "No changes\n$ta == $tb\n";
584 ########################### utility functions #########################
587 my @cmd = qw/rebase/;
588 push @cmd, '-v' if $_verbose;
589 push @cmd, qw/--merge/ if $_merge;
590 push @cmd, "--strategy=$_strategy" if $_strategy;
594 sub post_fetch_checkout {
595 return if $_no_checkout;
596 my $gs = $Git::SVN::_head or return;
597 return if verify_ref('refs/heads/master^0');
599 my $valid_head = verify_ref('HEAD^0');
600 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
601 return if ($valid_head || !verify_ref('HEAD^0'));
603 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
604 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
607 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
608 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
609 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
610 print STDERR "Checked out HEAD:\n ",
611 $gs->full_url, " r", $gs->last_rev, "\n";
614 sub complete_svn_url {
615 my ($url, $path) = @_;
617 if ($path !~ m#^[a-z\+]+://#) {
618 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
619 fatal("E: '$path' is not a complete URL ",
620 "and a separate URL is not specified\n");
622 return ($url, $path);
627 sub complete_url_ls_init {
628 my ($ra, $repo_path, $switch, $pfx) = @_;
629 unless ($repo_path) {
630 print STDERR "W: $switch not specified\n";
633 $repo_path =~ s#/+$##;
634 if ($repo_path =~ m#^[a-z\+]+://#) {
635 $ra = Git::SVN::Ra->new($repo_path);
638 $repo_path =~ s#^/+##;
640 fatal("E: '$repo_path' is not a complete URL ",
641 "and a separate URL is not specified\n");
644 my $url = $ra->{url};
645 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
646 my $k = "svn-remote.$gs->{repo_id}.url";
647 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
648 if ($orig_url && ($orig_url ne $gs->{url})) {
649 die "$k already set: $orig_url\n",
650 "wanted to set to: $gs->{url}\n";
652 command_oneline('config', $k, $gs->{url}) unless $orig_url;
653 my $remote_path = "$ra->{svn_path}/$repo_path/*";
654 $remote_path =~ s#/+#/#g;
655 $remote_path =~ s#^/##g;
656 my ($n) = ($switch =~ /^--(\w+)/);
657 if (length $pfx && $pfx !~ m#/$#) {
658 die "--prefix='$pfx' must have a trailing slash '/'\n";
660 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
661 "$remote_path:refs/remotes/$pfx*");
666 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
670 sub get_tree_from_treeish {
672 # $treeish can be a symbolic ref, too:
673 my $type = command_oneline(qw/cat-file -t/, $treeish);
675 while ($type eq 'tag') {
676 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
678 if ($type eq 'commit') {
679 $expected = (grep /^tree /, command(qw/cat-file commit/,
681 ($expected) = ($expected =~ /^tree ($sha1)$/o);
682 die "Unable to get tree from $treeish\n" unless $expected;
683 } elsif ($type eq 'tree') {
684 $expected = $treeish;
686 die "$treeish is a $type, expected tree, tag or commit\n";
691 sub get_commit_entry {
692 my ($treeish) = shift;
693 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
694 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
695 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
696 open my $log_fh, '>', $commit_editmsg or croak $!;
698 my $type = command_oneline(qw/cat-file -t/, $treeish);
699 if ($type eq 'commit' || $type eq 'tag') {
700 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
705 $in_msg = 1 if (/^\s*$/);
706 } elsif (/^git-svn-id: /) {
707 # skip this for now, we regenerate the
708 # correct one on re-fetch anyways
709 # TODO: set *:merge properties or like...
711 print $log_fh $_ or croak $!;
714 command_close_pipe($msg_fh, $ctx);
716 close $log_fh or croak $!;
718 if ($_edit || ($type eq 'tree')) {
719 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
720 # TODO: strip out spaces, comments, like git-commit.sh
721 system($editor, $commit_editmsg);
723 rename $commit_editmsg, $commit_msg or croak $!;
724 open $log_fh, '<', $commit_msg or croak $!;
725 { local $/; chomp($log_entry{log} = <$log_fh>); }
726 close $log_fh or croak $!;
732 my ($str, $file, $mode) = @_;
733 open my $fd,'>',$file or croak $!;
734 print $fd $str,"\n" or croak $!;
735 close $fd or croak $!;
736 chmod ($mode &~ umask, $file) if (defined $mode);
741 open my $fd,'<',$file or croak "$!: file: $file\n";
744 close $fd or croak $!;
749 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
751 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
752 my $log = $cmd eq 'log';
755 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
756 my ($user, $name, $email) = ($1, $2, $3);
758 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
760 $users{$user} = [$name, $email];
763 close $authors or croak $!;
766 # convert GetOpt::Long specs for use by git-config
767 sub read_repo_config {
768 return unless -d $ENV{GIT_DIR};
771 foreach my $o (keys %$opts) {
772 # if we have mixedCase and a long option-only, then
773 # it's a config-only variable that we don't need for
775 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
777 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
779 my $arg = 'git-config';
780 $arg .= ' --int' if ($o =~ /[:=]i$/);
781 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
782 if (ref $v eq 'ARRAY') {
783 chomp(my @tmp = `$arg --get-all svn.$key`);
786 chomp(my $tmp = `$arg --get svn.$key`);
787 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
792 delete @$opts{@config_only} if @config_only;
795 sub extract_metadata {
796 my $id = shift or return (undef, undef, undef);
797 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
799 if (!defined $rev || !$uuid || !$url) {
800 # some of the original repositories I made had
801 # identifiers like this:
802 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
804 return ($url, $rev, $uuid);
808 return extract_metadata((grep(/^git-svn-id: /,
809 command(qw/cat-file commit/, shift)))[-1]);
812 sub working_head_info {
813 my ($head, $refs) = @_;
814 my ($fh, $ctx) = command_output_pipe('log', '--no-color', $head);
818 if ( m{^commit ($::sha1)$} ) {
819 unshift @$refs, $hash if $hash and $refs;
823 next unless s{^\s*(git-svn-id:)}{$1};
824 my ($url, $rev, $uuid) = extract_metadata($_);
825 if (defined $url && defined $rev) {
826 next if $max{$url} and $max{$url} < $rev;
827 if (my $gs = Git::SVN->find_by_url($url)) {
828 my $c = $gs->rev_db_get($rev);
829 if ($c && $c eq $hash) {
830 close $fh; # break the pipe
831 return ($url, $rev, $uuid, $gs);
833 $max{$url} ||= $gs->rev_db_max;
838 command_close_pipe($fh, $ctx);
839 (undef, undef, undef, undef);
842 sub read_commit_parents {
843 my ($parents, $c) = @_;
844 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
845 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
846 @{$parents->{$c}} = split(/ /, $p);
849 sub linearize_history {
850 my ($gs, $refs) = @_;
852 foreach my $c (@$refs) {
853 read_commit_parents(\%parents, $c);
858 my $last_svn_commit = $gs->last_commit;
859 foreach my $c (reverse @$refs) {
860 next if $c eq $last_svn_commit;
863 unshift @linear_refs, $c;
866 # we only want the first parent to diff against for linear
867 # history, we save the rest to inject when we finalize the
869 my $fp_a = verify_ref("$c~1");
870 my $fp_b = shift @{$parents{$c}} if $parents{$c};
871 if (!$fp_a || !$fp_b) {
873 "has no parent commit, and therefore ",
874 "nothing to diff against.\n",
875 "You should be working from a repository ",
876 "originally created by git-svn\n";
878 if ($fp_a ne $fp_b) {
879 die "$c~1 = $fp_a, however parsing commit $c ",
880 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
883 foreach my $p (@{$parents{$c}}) {
887 (\@linear_refs, \%parents);
893 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
894 $_repack $_repack_flags $_use_svm_props $_head
895 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
897 use File::Path qw/mkpath/;
898 use File::Copy qw/copy/;
902 # properties that we do not log:
905 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
906 svn:special svn:executable
907 svn:entry:committed-rev
908 svn:entry:last-author
910 svn:entry:committed-date/;
912 # some options are read globally, but can be overridden locally
913 # per [svn-remote "..."] section. Command-line options will *NOT*
914 # override options set in an [svn-remote "..."] section
916 for my $option (qw/follow_parent no_metadata use_svm_props
917 use_svnsync_props/) {
920 my $prop = "-$option";
923 return $self->{$prop} if exists $self->{$prop};
924 my $k = "svn-remote.$self->{repo_id}.$key";
925 eval { command_oneline(qw/config --get/, $k) };
927 $self->{$prop} = ${"Git::SVN::_$option"};
929 my $v = command_oneline(qw/config --bool/,$k);
930 $self->{$prop} = $v eq 'false' ? 0 : 1;
932 return $self->{$prop};
938 END { unlink keys %LOCKFILES if %LOCKFILES }
940 sub resolve_local_globs {
941 my ($url, $fetch, $glob_spec) = @_;
942 return unless defined $glob_spec;
943 my $ref = $glob_spec->{ref};
944 my $path = $glob_spec->{path};
945 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
946 next unless m#^refs/remotes/$ref->{regex}$#;
948 my $pathname = desanitize_refname($path->full_path($p));
949 my $refname = desanitize_refname($ref->full_path($p));
950 if (my $existing = $fetch->{$pathname}) {
951 if ($existing ne $refname) {
952 die "Refspec conflict:\n",
953 "existing: refs/remotes/$existing\n",
954 " globbed: refs/remotes/$refname\n";
956 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
957 $u =~ s!^\Q$url\E(/|$)!! or die
958 "refs/remotes/$refname: '$url' not found in '$u'\n";
959 if ($pathname ne $u) {
960 warn "W: Refspec glob conflict ",
961 "(ref: refs/remotes/$refname):\n",
962 "expected path: $pathname\n",
964 "Continuing ahead with $u\n";
968 $fetch->{$pathname} = $refname;
973 sub parse_revision_argument {
974 my ($base, $head) = @_;
975 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
976 return ($base, $head);
978 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
979 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
980 return ($head, $head) if ($::_revision eq 'HEAD');
981 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
982 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
983 die "revision argument: $::_revision not understood by git-svn\n";
987 my ($repo_id, $remotes) = @_;
991 $repo_id = $gs->{repo_id};
993 $remotes ||= read_all_remotes();
994 my $remote = $remotes->{$repo_id} or
995 die "[svn-remote \"$repo_id\"] unknown\n";
996 my $fetch = $remote->{fetch};
997 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
999 my $ra = Git::SVN::Ra->new($url);
1000 my $uuid = $ra->get_uuid;
1001 my $head = $ra->get_latest_revnum;
1002 my $base = defined $fetch ? $head : 0;
1004 # read the max revs for wildcard expansion (branches/*, tags/*)
1005 foreach my $t (qw/branches tags/) {
1006 defined $remote->{$t} or next;
1007 push @globs, $remote->{$t};
1008 my $max_rev = eval { tmp_config(qw/--int --get/,
1009 "svn-remote.$repo_id.${t}-maxRev") };
1010 if (defined $max_rev && ($max_rev < $base)) {
1012 } elsif (!defined $max_rev) {
1018 foreach my $p (sort keys %$fetch) {
1019 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1020 my $lr = $gs->rev_db_max;
1022 $base = $lr if ($lr < $base);
1028 ($base, $head) = parse_revision_argument($base, $head);
1029 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1032 sub read_all_remotes {
1034 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1035 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1036 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1037 $local_ref =~ s{^/}{};
1038 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1039 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1040 $r->{$1}->{url} = $2;
1041 } elsif (m!^(.+)\.(branches|tags)=
1042 (.*):refs/remotes/(.+)\s*$/!x) {
1043 my ($p, $g) = ($3, $4);
1044 my $rs = $r->{$1}->{$2} = {
1047 path => Git::SVN::GlobSpec->new($p),
1048 ref => Git::SVN::GlobSpec->new($g) };
1049 if (length($rs->{ref}->{right}) != 0) {
1050 die "The '*' glob character must be the last ",
1051 "character of '$g'\n";
1059 if (defined $_repack) {
1060 $_repack = 1000 if ($_repack <= 0);
1061 $_repack_nr = $_repack;
1062 $_repack_flags ||= '-d';
1066 sub verify_remotes_sanity {
1067 return unless -d $ENV{GIT_DIR};
1069 foreach (command(qw/config -l/)) {
1070 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1072 die "Remote ref refs/remote/$1 is tracked by",
1073 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1074 "Please resolve this ambiguity in ",
1075 "your git configuration file before ",
1083 # we allow more chars than remotes2config.sh...
1084 sub sanitize_remote_name {
1086 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1090 sub find_existing_remote {
1091 my ($url, $remotes) = @_;
1092 return undef if $no_reuse_existing;
1094 foreach my $repo_id (keys %$remotes) {
1095 my $u = $remotes->{$repo_id}->{url} or next;
1097 $existing = $repo_id;
1103 sub init_remote_config {
1104 my ($self, $url, $no_write) = @_;
1105 $url =~ s!/+$!!; # strip trailing slash
1106 my $r = read_all_remotes();
1107 my $existing = find_existing_remote($url, $r);
1109 unless ($no_write) {
1110 print STDERR "Using existing ",
1111 "[svn-remote \"$existing\"]\n";
1113 $self->{repo_id} = $existing;
1114 } elsif ($_minimize_url) {
1115 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1116 $existing = find_existing_remote($min_url, $r);
1118 unless ($no_write) {
1119 print STDERR "Using existing ",
1120 "[svn-remote \"$existing\"]\n";
1122 $self->{repo_id} = $existing;
1124 if ($min_url ne $url) {
1125 unless ($no_write) {
1126 print STDERR "Using higher level of URL: ",
1127 "$url => $min_url\n";
1129 my $old_path = $self->{path};
1130 $self->{path} = $url;
1131 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1132 if (length $old_path) {
1133 $self->{path} .= "/$old_path";
1140 # verify that we aren't overwriting anything:
1142 command_oneline('config', '--get',
1143 "svn-remote.$self->{repo_id}.url")
1145 if ($orig_url && ($orig_url ne $url)) {
1146 die "svn-remote.$self->{repo_id}.url already set: ",
1147 "$orig_url\nwanted to set to: $url\n";
1150 my ($xrepo_id, $xpath) = find_ref($self->refname);
1151 if (defined $xpath) {
1152 die "svn-remote.$xrepo_id.fetch already set to track ",
1153 "$xpath:refs/remotes/", $self->refname, "\n";
1155 unless ($no_write) {
1156 command_noisy('config',
1157 "svn-remote.$self->{repo_id}.url", $url);
1158 $self->{path} =~ s{^/}{};
1159 command_noisy('config', '--add',
1160 "svn-remote.$self->{repo_id}.fetch",
1161 "$self->{path}:".$self->refname);
1163 $self->{url} = $url;
1166 sub find_by_url { # repos_root and, path are optional
1167 my ($class, $full_url, $repos_root, $path) = @_;
1169 return undef unless defined $full_url;
1170 remove_username($full_url);
1171 remove_username($repos_root) if defined $repos_root;
1172 my $remotes = read_all_remotes();
1173 if (defined $full_url && defined $repos_root && !defined $path) {
1175 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1177 foreach my $repo_id (keys %$remotes) {
1178 my $u = $remotes->{$repo_id}->{url} or next;
1179 remove_username($u);
1180 next if defined $repos_root && $repos_root ne $u;
1182 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1183 foreach (qw/branches tags/) {
1184 resolve_local_globs($u, $fetch,
1185 $remotes->{$repo_id}->{$_});
1188 unless (defined $p) {
1190 $p =~ s#^\Q$u\E(?:/|$)## or next;
1192 foreach my $f (keys %$fetch) {
1194 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1201 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1202 my $self = _new($class, $repo_id, $ref_id, $path);
1204 $self->init_remote_config($url, $no_write);
1211 foreach (command(qw/config -l/)) {
1212 next unless m!^svn-remote\.(.+)\.fetch=
1213 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1214 my ($repo_id, $path, $ref) = ($1, $2, $3);
1215 if ($ref eq $ref_id) {
1216 $path = '' if ($path =~ m#^\./?#);
1217 return ($repo_id, $path);
1220 (undef, undef, undef);
1224 my ($class, $ref_id, $repo_id, $path) = @_;
1225 if (defined $ref_id && !defined $repo_id && !defined $path) {
1226 ($repo_id, $path) = find_ref($ref_id);
1227 if (!defined $repo_id) {
1228 die "Could not find a \"svn-remote.*.fetch\" key ",
1229 "in the repository configuration matching: ",
1230 "refs/remotes/$ref_id\n";
1233 my $self = _new($class, $repo_id, $ref_id, $path);
1234 if (!defined $self->{path} || !length $self->{path}) {
1235 my $fetch = command_oneline('config', '--get',
1236 "svn-remote.$repo_id.fetch",
1237 ":refs/remotes/$ref_id\$") or
1238 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1239 "\":refs/remotes/$ref_id\$\" in config\n";
1240 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1242 $self->{url} = command_oneline('config', '--get',
1243 "svn-remote.$repo_id.url") or
1244 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1250 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1252 # It cannot end with a slash /, we'll throw up on this because
1253 # SVN can't have directories with a slash in their name, either:
1254 if ($refname =~ m{/$}) {
1255 die "ref: '$refname' ends with a trailing slash, this is ",
1256 "not permitted by git nor Subversion\n";
1259 # It cannot have ASCII control character space, tilde ~, caret ^,
1260 # colon :, question-mark ?, asterisk *, space, or open bracket [
1263 # Additionally, % must be escaped because it is used for escaping
1264 # and we want our escaped refname to be reversible
1265 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1267 # no slash-separated component can begin with a dot .
1269 $refname =~ s{/\.}{/%2E}g;
1271 # It cannot have two consecutive dots .. anywhere
1273 $refname =~ s{\.\.}{%2E%2E}g;
1278 sub desanitize_refname {
1280 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1286 return $self->{svm}->{uuid} if $self->svm;
1288 unless ($self->{svm}) {
1289 die "SVM UUID not cached, and reading remotely failed\n";
1291 $self->{svm}->{uuid};
1296 return $self->{svm} if $self->{svm};
1298 # see if we have it in our config, first:
1300 my $section = "svn-remote.$self->{repo_id}";
1302 source => tmp_config('--get', "$section.svm-source"),
1303 uuid => tmp_config('--get', "$section.svm-uuid"),
1304 replace => tmp_config('--get', "$section.svm-replace"),
1307 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1308 $self->{svm} = $svm;
1314 my ($self, $ra) = @_;
1315 return $ra if $self->svm;
1317 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1318 "(svm:source, svm:uuid) ",
1319 "from the following URLs:\n" );
1320 sub read_svm_props {
1321 my ($self, $ra, $path, $r) = @_;
1322 my $props = ($ra->get_dir($path, $r))[2];
1323 my $src = $props->{'svm:source'};
1324 my $uuid = $props->{'svm:uuid'};
1325 return undef if (!$src || !$uuid);
1329 $uuid =~ m{^[0-9a-f\-]{30,}$}
1330 or die "doesn't look right - svm:uuid is '$uuid'\n";
1332 # the '!' is used to mark the repos_root!/relative/path
1333 $src =~ s{/?!/?}{/};
1334 $src =~ s{/+$}{}; # no trailing slashes please
1335 # username is of no interest
1336 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1338 my $replace = $ra->{url};
1339 $replace .= "/$path" if length $path;
1341 my $section = "svn-remote.$self->{repo_id}";
1342 tmp_config("$section.svm-source", $src);
1343 tmp_config("$section.svm-replace", $replace);
1344 tmp_config("$section.svm-uuid", $uuid);
1352 my $r = $ra->get_latest_revnum;
1353 my $path = $self->{path};
1355 while (length $path) {
1356 unless ($tried{"$self->{url}/$path"}) {
1357 return $ra if $self->read_svm_props($ra, $path, $r);
1358 $tried{"$self->{url}/$path"} = 1;
1360 $path =~ s#/?[^/]+$##;
1362 die "Path: '$path' should be ''\n" if $path ne '';
1363 return $ra if $self->read_svm_props($ra, $path, $r);
1364 $tried{"$self->{url}/$path"} = 1;
1366 if ($ra->{repos_root} eq $self->{url}) {
1367 die @err, (map { " $_\n" } keys %tried), "\n";
1370 # nope, make sure we're connected to the repository root:
1373 $path = $ra->{svn_path};
1374 $ra = Git::SVN::Ra->new($ra->{repos_root});
1375 while (length $path) {
1376 unless ($tried{"$ra->{url}/$path"}) {
1377 $ok = $self->read_svm_props($ra, $path, $r);
1379 $tried{"$ra->{url}/$path"} = 1;
1381 $path =~ s#/?[^/]+$##;
1383 die "Path: '$path' should be ''\n" if $path ne '';
1384 $ok ||= $self->read_svm_props($ra, $path, $r);
1385 $tried{"$ra->{url}/$path"} = 1;
1387 die @err, (map { " $_\n" } keys %tried), "\n";
1389 Git::SVN::Ra->new($self->{url});
1394 return $self->{svnsync} if $self->{svnsync};
1396 if ($self->no_metadata) {
1397 die "Can't have both 'noMetadata' and ",
1398 "'useSvnsyncProps' options set!\n";
1400 if ($self->rewrite_root) {
1401 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1406 # see if we have it in our config, first:
1408 my $section = "svn-remote.$self->{repo_id}";
1410 url => tmp_config('--get', "$section.svnsync-url"),
1411 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1414 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1415 return $self->{svnsync} = $svnsync;
1418 my $err = "useSvnsyncProps set, but failed to read " .
1419 "svnsync property: svn:sync-from-";
1420 my $rp = $self->ra->rev_proplist(0);
1422 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1423 $url =~ m{^[a-z\+]+://} or
1424 die "doesn't look right - svn:sync-from-url is '$url'\n";
1426 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1427 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1428 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1430 my $section = "svn-remote.$self->{repo_id}";
1431 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1432 tmp_config('--add', "$section.svnsync-url", $url);
1433 return $self->{svnsync} = { url => $url, uuid => $uuid };
1436 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1437 # remote lookup (useful for 'git svn log').
1440 unless ($self->{ra_uuid}) {
1441 my $key = "svn-remote.$self->{repo_id}.uuid";
1442 my $uuid = eval { tmp_config('--get', $key) };
1443 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1444 $self->{ra_uuid} = $uuid;
1446 die "ra_uuid called without URL\n" unless $self->{url};
1447 $self->{ra_uuid} = $self->ra->get_uuid;
1448 tmp_config('--add', $key, $self->{ra_uuid});
1456 my $ra = Git::SVN::Ra->new($self->{url});
1457 if ($self->use_svm_props && !$self->{svm}) {
1458 if ($self->no_metadata) {
1459 die "Can't have both 'noMetadata' and ",
1460 "'useSvmProps' options set!\n";
1461 } elsif ($self->use_svnsync_props) {
1462 die "Can't have both 'useSvnsyncProps' and ",
1463 "'useSvmProps' options set!\n";
1465 $ra = $self->_set_svm_vars($ra);
1466 $self->{-want_revprops} = 1;
1473 my $repos_root = $self->ra->{repos_root};
1474 return $self->{path} if ($self->{url} eq $repos_root);
1475 my $url = $self->{url} .
1476 (length $self->{path} ? "/$self->{path}" : $self->{path});
1477 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1481 sub traverse_ignore {
1482 my ($self, $fh, $path, $r) = @_;
1485 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1487 $p =~ s#^\Q$self->{path}\E(/|$)##;
1488 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1489 if (my $s = $props->{'svn:ignore'}) {
1490 $s =~ s/[\r\n]+/\n/g;
1492 if (length $p == 0) {
1496 $s =~ s#\n#\n/$p/#g;
1497 print $fh "/$p/$s\n";
1500 foreach (sort keys %$dirent) {
1501 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1502 $self->traverse_ignore($fh, "$path/$_", $r);
1506 sub last_rev { ($_[0]->last_rev_commit)[0] }
1507 sub last_commit { ($_[0]->last_rev_commit)[1] }
1509 # returns the newest SVN revision number and newest commit SHA1
1510 sub last_rev_commit {
1512 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1513 return ($self->{last_rev}, $self->{last_commit});
1515 my $c = ::verify_ref($self->refname.'^0');
1516 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1517 my $rev = (::cmt_metadata($c))[1];
1519 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1523 my $db_path = $self->db_path;
1524 unless (-e $db_path) {
1525 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1526 return (undef, undef);
1528 my $offset = -41; # from tail
1530 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1531 sysseek($fh, $offset, 2); # don't care for errors
1532 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1534 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1536 sysseek($fh, $offset, 2); # don't care for errors
1537 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1540 if ($c && $c ne $rl) {
1541 die "$db_path and ", $self->refname,
1542 " inconsistent!:\n$c != $rl\n";
1544 my $rev = sysseek($fh, 0, 1) or croak $!;
1545 $rev = ($rev - 41) / 41;
1546 close $fh or croak $!;
1547 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1551 sub get_fetch_range {
1552 my ($self, $min, $max) = @_;
1553 $max ||= $self->ra->get_latest_revnum;
1554 $min ||= $self->rev_db_max;
1560 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1561 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1562 if (! -f $config && -f $old_def_config) {
1563 rename $old_def_config, $config or
1564 die "Failed rename $old_def_config => $config: $!\n";
1566 my $old_config = $ENV{GIT_CONFIG};
1567 $ENV{GIT_CONFIG} = $config;
1570 unless (-f $config) {
1572 open my $fh, '>', $config or
1573 die "Can't open $config: $!\n";
1574 print $fh "; This file is used internally by ",
1576 "Couldn't write to $config: $!\n";
1577 print $fh "; You should not have to edit it\n" or
1578 die "Couldn't write to $config: $!\n";
1579 close $fh or die "Couldn't close $config: $!\n";
1581 command('config', @args);
1584 if (defined $old_config) {
1585 $ENV{GIT_CONFIG} = $old_config;
1587 delete $ENV{GIT_CONFIG};
1590 wantarray ? @ret : $ret[0];
1594 my ($self, $sub) = @_;
1595 my $old_index = $ENV{GIT_INDEX_FILE};
1596 $ENV{GIT_INDEX_FILE} = $self->{index};
1599 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1600 mkpath([$dir]) unless -d $dir;
1604 if (defined $old_index) {
1605 $ENV{GIT_INDEX_FILE} = $old_index;
1607 delete $ENV{GIT_INDEX_FILE};
1610 wantarray ? @ret : $ret[0];
1613 sub assert_index_clean {
1614 my ($self, $treeish) = @_;
1616 $self->tmp_index_do(sub {
1617 command_noisy('read-tree', $treeish) unless -e $self->{index};
1618 my $x = command_oneline('write-tree');
1619 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1620 /^tree ($::sha1)/mo);
1623 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1624 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1625 command_noisy('read-tree', $treeish);
1626 $x = command_oneline('write-tree');
1628 ::fatal "trees ($treeish) $y != $x\n",
1629 "Something is seriously wrong...\n";
1634 sub get_commit_parents {
1635 my ($self, $log_entry) = @_;
1636 my (%seen, @ret, @tmp);
1637 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1638 if (my $ip = $self->{inject_parents}) {
1639 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1643 if (my $cur = ::verify_ref($self->refname.'^0')) {
1646 if (my $ipd = $self->{inject_parents_dcommit}) {
1647 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1648 push @tmp, @$commit;
1651 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1652 while (my $p = shift @tmp) {
1656 # MAXPARENT is defined to 16 in commit-tree.c:
1660 die "r$log_entry->{revision}: No room for parents:\n\t",
1661 join("\n\t", @tmp), "\n";
1668 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1669 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1670 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1673 if ($rwr !~ m#^[a-z\+]+://#) {
1674 die "$rwr is not a valid URL (key: $k)\n";
1677 $self->{-rewrite_root} = $rwr;
1682 ($self->rewrite_root || $self->{url}) .
1683 (length $self->{path} ? '/' . $self->{path} : '');
1688 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1692 my ($self, $log_entry) = @_;
1693 my $lr = $self->last_rev;
1694 if (defined $lr && $lr >= $log_entry->{revision}) {
1695 die "Last fetched revision of ", $self->refname,
1696 " was r$lr, but we are about to fetch: ",
1697 "r$log_entry->{revision}!\n";
1699 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1700 croak "$log_entry->{revision} = $c already exists! ",
1701 "Why are we refetching it?\n";
1703 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1704 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1705 $log_entry->{email};
1706 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1708 my $tree = $log_entry->{tree};
1709 if (!defined $tree) {
1710 $tree = $self->tmp_index_do(sub {
1711 command_oneline('write-tree') });
1713 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1715 my @exec = ('git-commit-tree', $tree);
1716 foreach ($self->get_commit_parents($log_entry)) {
1717 push @exec, '-p', $_;
1719 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1721 print $msg_fh $log_entry->{log} or croak $!;
1722 unless ($self->no_metadata) {
1723 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1726 $msg_fh->flush == 0 or croak $!;
1727 close $msg_fh or croak $!;
1728 chomp(my $commit = do { local $/; <$out_fh> });
1729 close $out_fh or croak $!;
1732 if ($commit !~ /^$::sha1$/o) {
1733 die "Failed to commit, invalid sha1: $commit\n";
1736 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1738 $self->{last_rev} = $log_entry->{revision};
1739 $self->{last_commit} = $commit;
1740 print "r$log_entry->{revision}";
1741 if (defined $log_entry->{svm_revision}) {
1742 print " (\@$log_entry->{svm_revision})";
1743 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1744 0, $self->svm_uuid);
1746 print " = $commit ($self->{ref_id})\n";
1747 if (defined $_repack && (--$_repack_nr == 0)) {
1748 $_repack_nr = $_repack;
1749 # repack doesn't use any arguments with spaces in them, does it?
1750 print "Running git repack $_repack_flags ...\n";
1751 command_noisy('repack', split(/\s+/, $_repack_flags));
1752 print "Done repacking\n";
1758 my ($self, $paths, $r) = @_;
1759 return 1 if $self->{path} eq '';
1760 if (my $path = $paths->{"/$self->{path}"}) {
1761 return ($path->{action} eq 'D') ? 0 : 1;
1763 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1764 if (grep /$self->{path_regex}/, keys %$paths) {
1768 foreach (split m#/#, $self->{path}) {
1770 next unless ($paths->{$c} &&
1771 ($paths->{$c}->{action} =~ /^[AR]$/));
1772 if ($self->ra->check_path($self->{path}, $r) ==
1780 sub find_parent_branch {
1781 my ($self, $paths, $rev) = @_;
1782 return undef unless $self->follow_parent;
1783 unless (defined $paths) {
1784 my $err_handler = $SVN::Error::handler;
1785 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1786 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1788 Git::SVN::Ra::dup_changed_paths($_[0]) });
1789 $SVN::Error::handler = $err_handler;
1791 return undef unless defined $paths;
1793 # look for a parent from another branch:
1794 my @b_path_components = split m#/#, $self->rel_path;
1795 my @a_path_components;
1797 while (@b_path_components) {
1798 $i = $paths->{'/'.join('/', @b_path_components)};
1799 last if $i && defined $i->{copyfrom_path};
1800 unshift(@a_path_components, pop(@b_path_components));
1802 return undef unless defined $i && defined $i->{copyfrom_path};
1803 my $branch_from = $i->{copyfrom_path};
1804 if (@a_path_components) {
1805 print STDERR "branch_from: $branch_from => ";
1806 $branch_from .= '/'.join('/', @a_path_components);
1807 print STDERR $branch_from, "\n";
1809 my $r = $i->{copyfrom_rev};
1810 my $repos_root = $self->ra->{repos_root};
1811 my $url = $self->ra->{url};
1812 my $new_url = $repos_root . $branch_from;
1813 print STDERR "Found possible branch point: ",
1814 "$new_url => ", $self->full_url, ", $r\n";
1815 $branch_from =~ s#^/##;
1816 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1818 my $ref_id = $self->{ref_id};
1819 $ref_id =~ s/\@\d+$//;
1821 # just grow a tail if we're not unique enough :x
1822 $ref_id .= '-' while find_ref($ref_id);
1823 print STDERR "Initializing parent: $ref_id\n";
1824 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1826 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1827 if (!defined $r0 || !defined $parent) {
1828 my ($base, $head) = parse_revision_argument(0, $r);
1830 $gs->fetch($base, $r);
1832 ($r0, $parent) = $gs->last_rev_commit;
1834 if (defined $r0 && defined $parent) {
1835 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1837 if ($self->ra->can_do_switch) {
1838 $self->assert_index_clean($parent);
1839 print STDERR "Following parent with do_switch\n";
1840 # do_switch works with svn/trunk >= r22312, but that
1841 # is not included with SVN 1.4.3 (the latest version
1842 # at the moment), so we can't rely on it
1843 $self->{last_commit} = $parent;
1844 $ed = SVN::Git::Fetcher->new($self);
1845 $gs->ra->gs_do_switch($r0, $rev, $gs,
1846 $self->full_url, $ed)
1847 or die "SVN connection failed somewhere...\n";
1849 print STDERR "Following parent with do_update\n";
1850 $ed = SVN::Git::Fetcher->new($self);
1851 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1852 or die "SVN connection failed somewhere...\n";
1854 print STDERR "Successfully followed parent\n";
1855 return $self->make_log_entry($rev, [$parent], $ed);
1861 my ($self, $paths, $rev) = @_;
1863 my ($last_rev, @parents);
1864 if (my $lc = $self->last_commit) {
1865 # we can have a branch that was deleted, then re-added
1866 # under the same name but copied from another path, in
1867 # which case we'll have multiple parents (we don't
1868 # want to break the original ref, nor lose copypath info):
1869 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1870 push @{$log_entry->{parents}}, $lc;
1873 $ed = SVN::Git::Fetcher->new($self);
1874 $last_rev = $self->{last_rev};
1879 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1882 $ed = SVN::Git::Fetcher->new($self);
1884 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1885 die "SVN connection failed somewhere...\n";
1887 $self->make_log_entry($rev, \@parents, $ed);
1891 my ($self, $ed) = @_;
1893 my $h = $ed->{empty};
1894 foreach (sort keys %$h) {
1895 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1896 push @out, " $act: " . uri_encode($_);
1897 warn "W: $act: $_\n";
1899 foreach my $t (qw/dir_prop file_prop/) {
1900 $h = $ed->{$t} or next;
1901 foreach my $path (sort keys %$h) {
1902 my $ppath = $path eq '' ? '.' : $path;
1903 foreach my $prop (sort keys %{$h->{$path}}) {
1904 next if $SKIP_PROP{$prop};
1905 my $v = $h->{$path}->{$prop};
1906 my $t_ppath_prop = "$t: " .
1907 uri_encode($ppath) . ' ' .
1910 push @out, " +$t_ppath_prop " .
1913 push @out, " -$t_ppath_prop";
1918 foreach my $t (qw/absent_file absent_directory/) {
1919 $h = $ed->{$t} or next;
1920 foreach my $parent (sort keys %$h) {
1921 foreach my $path (sort @{$h->{$parent}}) {
1922 push @out, " $t: " .
1923 uri_encode("$parent/$path");
1924 warn "W: $t: $parent/$path ",
1925 "Insufficient permissions?\n";
1932 sub parse_svn_date {
1933 my $date = shift || return '+0000 1970-01-01 00:00:00';
1934 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1935 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1936 croak "Unable to parse date: $date\n";
1937 "+0000 $Y-$m-$d $H:$M:$S";
1942 if (!defined $author || length $author == 0) {
1943 $author = '(no author)';
1945 if (defined $::_authors && ! defined $::users{$author}) {
1946 die "Author: $author not defined in $::_authors file\n";
1951 sub make_log_entry {
1952 my ($self, $rev, $parents, $ed) = @_;
1953 my $untracked = $self->get_untracked($ed);
1955 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1956 print $un "r$rev\n" or croak $!;
1957 print $un $_, "\n" foreach @$untracked;
1958 my %log_entry = ( parents => $parents || [], revision => $rev,
1962 my $logged = delete $self->{logged_rev_props};
1963 if (!$logged || $self->{-want_revprops}) {
1964 my $rp = $self->ra->rev_proplist($rev);
1965 foreach (sort keys %$rp) {
1967 if (/^svn:(author|date|log)$/) {
1968 $log_entry{$1} = $v;
1969 } elsif ($_ eq 'svm:headrev') {
1972 print $un " rev_prop: ", uri_encode($_), ' ',
1973 uri_encode($v), "\n";
1977 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1979 close $un or croak $!;
1981 $log_entry{date} = parse_svn_date($log_entry{date});
1982 $log_entry{log} .= "\n";
1983 my $author = $log_entry{author} = check_author($log_entry{author});
1984 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1986 if (defined $headrev && $self->use_svm_props) {
1987 if ($self->rewrite_root) {
1988 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1991 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1992 # we don't want "SVM: initializing mirror for junk" ...
1993 return undef if $r == 0;
1994 my $svm = $self->svm;
1995 if ($uuid ne $svm->{uuid}) {
1996 die "UUID mismatch on SVM path:\n",
1997 "expected: $svm->{uuid}\n",
2000 my $full_url = $self->full_url;
2001 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2002 die "Failed to replace '$svm->{replace}' with ",
2003 "'$svm->{source}' in $full_url\n";
2004 # throw away username for storing in records
2005 remove_username($full_url);
2006 $log_entry{metadata} = "$full_url\@$r $uuid";
2007 $log_entry{svm_revision} = $r;
2008 $email ||= "$author\@$uuid"
2009 } elsif ($self->use_svnsync_props) {
2010 my $full_url = $self->svnsync->{url};
2011 $full_url .= "/$self->{path}" if length $self->{path};
2012 remove_username($full_url);
2013 my $uuid = $self->svnsync->{uuid};
2014 $log_entry{metadata} = "$full_url\@$rev $uuid";
2015 $email ||= "$author\@$uuid"
2017 my $url = $self->metadata_url;
2018 remove_username($url);
2019 $log_entry{metadata} = "$url\@$rev " .
2020 $self->ra->get_uuid;
2021 $email ||= "$author\@" . $self->ra->get_uuid;
2023 $log_entry{name} = $name;
2024 $log_entry{email} = $email;
2029 my ($self, $min_rev, $max_rev, @parents) = @_;
2030 my ($last_rev, $last_commit) = $self->last_rev_commit;
2031 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2032 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2036 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2037 $self->{inject_parents} = { $rev => $tree };
2038 $self->fetch(undef, undef);
2042 my ($self, $tree) = (shift, shift);
2043 my $log_entry = ::get_commit_entry($tree);
2044 unless ($self->{last_rev}) {
2045 fatal("Must have an existing revision to commit\n");
2047 my %ed_opts = ( r => $self->{last_rev},
2048 log => $log_entry->{log},
2050 tree_a => $self->{last_commit},
2053 $self->set_tree_cb($log_entry, $tree, @_) },
2054 svn_path => $self->{path} );
2055 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2056 print "No changes\nr$self->{last_rev} = $tree\n";
2062 my $db_path = $self->db_path;
2063 return if (-e $db_path && ! -z $db_path);
2064 return unless ::verify_ref($self->refname.'^0');
2065 if (-f $self->{db_root}) {
2066 rename $self->{db_root}, $db_path or die
2067 "rename $self->{db_root} => $db_path failed: $!\n";
2068 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2069 symlink $base, $self->{db_root} or die
2070 "symlink $base => $self->{db_root} failed: $!\n";
2073 print "Rebuilding $db_path ...\n";
2074 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2076 my $full_url = $self->full_url;
2077 remove_username($full_url);
2081 if ( m{^commit ($::sha1)$} ) {
2085 next unless s{^\s*(git-svn-id:)}{$1};
2086 my ($url, $rev, $uuid) = ::extract_metadata($_);
2087 remove_username($url);
2089 # ignore merges (from set-tree)
2090 next if (!defined $rev || !$uuid);
2092 # if we merged or otherwise started elsewhere, this is
2093 # how we break out of it
2094 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2095 ($full_url && $url && ($url ne $full_url))) {
2099 $svn_uuid ||= $uuid;
2101 $self->rev_db_set($rev, $c);
2102 print "r$rev = $c\n";
2104 command_close_pipe($log, $ctx);
2105 print "Done rebuilding $db_path\n";
2109 # Tie::File seems to be prone to offset errors if revisions get sparse,
2110 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2111 # one of my favorite modules is out :< Next up would be one of the DBM
2112 # modules, but I'm not sure which is most portable... So I'll just
2113 # go with something that's plain-text, but still capable of
2114 # being randomly accessed. So here's my ultra-simple fixed-width
2115 # database. All records are 40 characters + "\n", so it's easy to seek
2116 # to a revision: (41 * rev) is the byte offset.
2117 # A record of 40 0s denotes an empty revision.
2118 # And yes, it's still pretty fast (faster than Tie::File).
2119 # These files are disposable unless noMetadata or useSvmProps is set
2122 my ($fh, $rev, $commit) = @_;
2123 my $offset = $rev * 41;
2124 # assume that append is the common case:
2125 seek $fh, 0, 2 or croak $!;
2127 if ($pos < $offset) {
2128 for (1 .. (($offset - $pos) / 41)) {
2129 print $fh (('0' x 40),"\n") or croak $!;
2132 seek $fh, $offset, 0 or croak $!;
2133 print $fh $commit,"\n" or croak $!;
2139 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2140 mkpath([$dir]) unless -d $dir;
2141 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2142 close $fh or die "Couldn't close (create) $path: $!\n";
2147 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2148 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2149 my $db = $self->db_path($uuid);
2150 my $db_lock = "$db.lock";
2153 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2154 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2158 $LOCKFILES{$db_lock} = 1;
2160 # both of these options make our .rev_db file very, very important
2161 # and we can't afford to lose it because rebuild() won't work
2162 if ($self->use_svm_props || $self->no_metadata) {
2164 copy($db, $db_lock) or die "rev_db_set(@_): ",
2166 "$db => $db_lock ($!)\n";
2168 rename $db, $db_lock or die "rev_db_set(@_): ",
2169 "Failed to rename: ",
2170 "$db => $db_lock ($!)\n";
2172 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2173 _rev_db_set($fh, $rev, $commit);
2175 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2176 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2178 close $fh or croak $!;
2181 command_noisy('update-ref', '-m', "r$rev",
2182 $self->refname, $commit);
2184 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2185 "$db_lock => $db ($!)\n";
2186 delete $LOCKFILES{$db_lock};
2188 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2189 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2190 kill $sig, $$ if defined $sig;
2197 my $db_path = $self->db_path;
2198 my @stat = stat $db_path or return 0;
2199 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2200 my $max = $stat[7] / 41;
2201 (($max > 0) ? $max - 1 : 0);
2205 my ($self, $rev, $uuid) = @_;
2207 my $offset = $rev * 41;
2208 my $db_path = $self->db_path($uuid);
2209 return undef unless -e $db_path;
2210 open my $fh, '<', $db_path or croak $!;
2211 if (sysseek($fh, $offset, 0) == $offset) {
2212 my $read = sysread($fh, $ret, 40);
2213 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2215 close $fh or croak $!;
2219 sub find_rev_before {
2220 my ($self, $rev, $eq_ok) = @_;
2221 --$rev unless $eq_ok;
2223 if (my $c = $self->rev_db_get($rev)) {
2228 return (undef, undef);
2232 my ($class, $repo_id, $ref_id, $path) = @_;
2233 unless (defined $repo_id && length $repo_id) {
2234 $repo_id = $Git::SVN::default_repo_id;
2236 unless (defined $ref_id && length $ref_id) {
2237 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2239 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2240 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2241 $_[3] = $path = '' unless (defined $path);
2242 mkpath(["$ENV{GIT_DIR}/svn"]);
2244 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2245 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2246 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2250 my ($self, $uuid) = @_;
2251 $uuid ||= $self->ra_uuid;
2252 "$self->{db_root}.$uuid";
2257 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2261 sub remove_username {
2262 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2265 package Git::SVN::Prompt;
2269 use vars qw/$_no_auth_cache $_username/;
2272 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2273 $may_save = undef if $_no_auth_cache;
2274 $default_username = $_username if defined $_username;
2275 if (defined $default_username && length $default_username) {
2276 if (defined $realm && length $realm) {
2277 print STDERR "Authentication realm: $realm\n";
2280 $cred->username($default_username);
2282 username($cred, $realm, $may_save, $pool);
2284 $cred->password(_read_password("Password for '" .
2285 $cred->username . "': ", $realm));
2286 $cred->may_save($may_save);
2287 $SVN::_Core::SVN_NO_ERROR;
2290 sub ssl_server_trust {
2291 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2292 $may_save = undef if $_no_auth_cache;
2293 print STDERR "Error validating server certificate for '$realm':\n";
2294 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2295 print STDERR " - The certificate is not issued by a trusted ",
2296 "authority. Use the\n",
2297 " fingerprint to validate the certificate manually!\n";
2299 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2300 print STDERR " - The certificate hostname does not match.\n";
2302 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2303 print STDERR " - The certificate is not yet valid.\n";
2305 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2306 print STDERR " - The certificate has expired.\n";
2308 if ($failures & $SVN::Auth::SSL::OTHER) {
2309 print STDERR " - The certificate has an unknown error.\n";
2312 "Certificate information:\n".
2313 " - Hostname: %s\n".
2314 " - Valid: from %s until %s\n".
2316 " - Fingerprint: %s\n",
2317 map $cert_info->$_, qw(hostname valid_from valid_until
2318 issuer_dname fingerprint);
2321 print STDERR $may_save ?
2322 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2323 "(R)eject or accept (t)emporarily? ";
2325 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2326 if ($choice =~ /^t$/i) {
2327 $cred->may_save(undef);
2328 } elsif ($choice =~ /^r$/i) {
2330 } elsif ($may_save && $choice =~ /^p$/i) {
2331 $cred->may_save($may_save);
2335 $cred->accepted_failures($failures);
2336 $SVN::_Core::SVN_NO_ERROR;
2339 sub ssl_client_cert {
2340 my ($cred, $realm, $may_save, $pool) = @_;
2341 $may_save = undef if $_no_auth_cache;
2342 print STDERR "Client certificate filename: ";
2344 chomp(my $filename = <STDIN>);
2345 $cred->cert_file($filename);
2346 $cred->may_save($may_save);
2347 $SVN::_Core::SVN_NO_ERROR;
2350 sub ssl_client_cert_pw {
2351 my ($cred, $realm, $may_save, $pool) = @_;
2352 $may_save = undef if $_no_auth_cache;
2353 $cred->password(_read_password("Password: ", $realm));
2354 $cred->may_save($may_save);
2355 $SVN::_Core::SVN_NO_ERROR;
2359 my ($cred, $realm, $may_save, $pool) = @_;
2360 $may_save = undef if $_no_auth_cache;
2361 if (defined $realm && length $realm) {
2362 print STDERR "Authentication realm: $realm\n";
2365 if (defined $_username) {
2366 $username = $_username;
2368 print STDERR "Username: ";
2370 chomp($username = <STDIN>);
2372 $cred->username($username);
2373 $cred->may_save($may_save);
2374 $SVN::_Core::SVN_NO_ERROR;
2377 sub _read_password {
2378 my ($prompt, $realm) = @_;
2379 print STDERR $prompt;
2381 require Term::ReadKey;
2382 Term::ReadKey::ReadMode('noecho');
2384 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2385 last if $key =~ /[\012\015]/; # \n\r
2388 Term::ReadKey::ReadMode('restore');
2397 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2398 $SVN::Node::dir.$SVN::Node::unknown.
2399 $SVN::Node::none.$SVN::Node::file.
2400 $SVN::Node::dir.$SVN::Node::unknown.
2401 $SVN::Auth::SSL::CNMISMATCH.
2402 $SVN::Auth::SSL::NOTYETVALID.
2403 $SVN::Auth::SSL::EXPIRED.
2404 $SVN::Auth::SSL::UNKNOWNCA.
2405 $SVN::Auth::SSL::OTHER;
2408 package SVN::Git::Fetcher;
2416 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2418 my ($class, $git_svn) = @_;
2419 my $self = SVN::Delta::Editor->new;
2420 bless $self, $class;
2421 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2422 $self->{empty} = {};
2423 $self->{dir_prop} = {};
2424 $self->{file_prop} = {};
2425 $self->{absent_dir} = {};
2426 $self->{absent_file} = {};
2427 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2431 sub set_path_strip {
2432 my ($self, $path) = @_;
2433 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2440 sub open_directory {
2441 my ($self, $path, $pb, $rev) = @_;
2446 my ($self, $path) = @_;
2447 if ($self->{path_strip}) {
2448 $path =~ s!$self->{path_strip}!! or
2449 die "Failed to strip path '$path' ($self->{path_strip})\n";
2455 my ($self, $path, $rev, $pb) = @_;
2457 my $gpath = $self->git_path($path);
2458 return undef if ($gpath eq '');
2460 # remove entire directories.
2461 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2462 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2464 $self->{c}, '--', $gpath);
2468 $self->{gii}->remove($_);
2469 print "\tD\t$_\n" unless $::_q;
2471 print "\tD\t$gpath/\n" unless $::_q;
2472 command_close_pipe($ls, $ctx);
2473 $self->{empty}->{$path} = 0
2475 $self->{gii}->remove($gpath);
2476 print "\tD\t$gpath\n" unless $::_q;
2482 my ($self, $path, $pb, $rev) = @_;
2483 my $gpath = $self->git_path($path);
2484 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2485 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2486 unless (defined $mode && defined $blob) {
2487 die "$path was not found in commit $self->{c} (r$rev)\n";
2489 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2490 pool => SVN::Pool->new, action => 'M' };
2494 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2495 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2496 delete $self->{empty}->{$dir};
2497 { path => $path, mode_a => 100644, mode_b => 100644,
2498 pool => SVN::Pool->new, action => 'A' };
2502 my ($self, $path, $cp_path, $cp_rev) = @_;
2503 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2504 delete $self->{empty}->{$dir};
2505 $self->{empty}->{$path} = 1;
2509 sub change_dir_prop {
2510 my ($self, $db, $prop, $value) = @_;
2511 $self->{dir_prop}->{$db->{path}} ||= {};
2512 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2516 sub absent_directory {
2517 my ($self, $path, $pb) = @_;
2518 $self->{absent_dir}->{$pb->{path}} ||= [];
2519 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2524 my ($self, $path, $pb) = @_;
2525 $self->{absent_file}->{$pb->{path}} ||= [];
2526 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2530 sub change_file_prop {
2531 my ($self, $fb, $prop, $value) = @_;
2532 if ($prop eq 'svn:executable') {
2533 if ($fb->{mode_b} != 120000) {
2534 $fb->{mode_b} = defined $value ? 100755 : 100644;
2536 } elsif ($prop eq 'svn:special') {
2537 $fb->{mode_b} = defined $value ? 120000 : 100644;
2539 $self->{file_prop}->{$fb->{path}} ||= {};
2540 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2545 sub apply_textdelta {
2546 my ($self, $fb, $exp) = @_;
2547 my $fh = IO::File->new_tmpfile;
2549 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2550 # (but $base does not,) so dup() it for reading in close_file
2551 open my $dup, '<&', $fh or croak $!;
2552 my $base = IO::File->new_tmpfile;
2553 $base->autoflush(1);
2555 defined (my $pid = fork) or croak $!;
2557 open STDOUT, '>&', $base or croak $!;
2558 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2559 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2565 seek $base, 0, 0 or croak $!;
2566 my $md5 = Digest::MD5->new;
2567 $md5->addfile($base);
2568 my $got = $md5->hexdigest;
2569 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2571 " got: $got\n" if ($got ne $exp);
2574 seek $base, 0, 0 or croak $!;
2576 $fb->{base} = $base;
2577 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2581 my ($self, $fb, $exp) = @_;
2583 my $path = $self->git_path($fb->{path});
2584 if (my $fh = $fb->{fh}) {
2586 seek($fh, 0, 0) or croak $!;
2587 my $md5 = Digest::MD5->new;
2589 my $got = $md5->hexdigest;
2591 die "Checksum mismatch: $path\n",
2592 "expected: $exp\n got: $got\n";
2595 sysseek($fh, 0, 0) or croak $!;
2596 if ($fb->{mode_b} == 120000) {
2597 sysread($fh, my $buf, 5) == 5 or croak $!;
2598 $buf eq 'link ' or die "$path has mode 120000",
2599 "but is not a link\n";
2601 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2603 open STDIN, '<&', $fh or croak $!;
2604 exec qw/git-hash-object -w --stdin/ or croak $!;
2606 chomp($hash = do { local $/; <$out> });
2607 close $out or croak $!;
2608 close $fh or croak $!;
2609 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2610 close $fb->{base} or croak $!;
2612 $hash = $fb->{blob} or die "no blob information\n";
2615 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2616 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2622 $self->{nr} = $self->{gii}->{nr};
2623 delete $self->{gii};
2624 $self->SUPER::abort_edit(@_);
2629 $self->{git_commit_ok} = 1;
2630 $self->{nr} = $self->{gii}->{nr};
2631 delete $self->{gii};
2632 $self->SUPER::close_edit(@_);
2635 package SVN::Git::Editor;
2636 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2644 my ($class, $opts) = @_;
2645 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2646 die "$_ required!\n" unless (defined $opts->{$_});
2649 my $pool = SVN::Pool->new;
2650 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2651 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2654 # $opts->{ra} functions should not be used after this:
2655 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2656 $opts->{editor_cb}, $pool);
2657 my $self = SVN::Delta::Editor->new(@ce, $pool);
2658 bless $self, $class;
2659 foreach (qw/svn_path r tree_a tree_b/) {
2660 $self->{$_} = $opts->{$_};
2662 $self->{url} = $opts->{ra}->{url};
2663 $self->{mods} = $mods;
2664 $self->{types} = $types;
2665 $self->{pool} = $pool;
2666 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2668 $self->{path_prefix} = length $self->{svn_path} ?
2669 "$self->{svn_path}/" : '';
2674 my ($tree_a, $tree_b) = @_;
2675 my @diff_tree = qw(diff-tree -z -r);
2676 if ($_cp_similarity) {
2677 push @diff_tree, "-C$_cp_similarity";
2679 push @diff_tree, '-C';
2681 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2682 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2683 push @diff_tree, $tree_a, $tree_b;
2684 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2688 while (<$diff_fh>) {
2689 chomp $_; # this gets rid of the trailing "\0"
2690 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2691 $::sha1\s($::sha1)\s
2692 ([MTCRAD])\d*$/xo) {
2693 push @mods, { mode_a => $1, mode_b => $2,
2694 sha1_b => $3, chg => $4 };
2695 if ($4 =~ /^(?:C|R)$/) {
2700 } elsif ($state eq 'file_a') {
2701 my $x = $mods[$#mods] or croak "Empty array\n";
2702 if ($x->{chg} !~ /^(?:C|R)$/) {
2703 croak "Error parsing $_, $x->{chg}\n";
2707 } elsif ($state eq 'file_b') {
2708 my $x = $mods[$#mods] or croak "Empty array\n";
2709 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2710 croak "Error parsing $_, $x->{chg}\n";
2712 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2713 croak "Error parsing $_, $x->{chg}\n";
2718 croak "Error parsing $_\n";
2721 command_close_pipe($diff_fh, $ctx);
2725 sub check_diff_paths {
2726 my ($ra, $pfx, $rev, $mods) = @_;
2728 $pfx .= '/' if length $pfx;
2730 sub type_diff_paths {
2731 my ($ra, $types, $path, $rev) = @_;
2732 my @p = split m#/+#, $path;
2734 unless (defined $types->{$c}) {
2735 $types->{$c} = $ra->check_path($c, $rev);
2738 $c .= '/' . shift @p;
2739 next if defined $types->{$c};
2740 $types->{$c} = $ra->check_path($c, $rev);
2744 foreach my $m (@$mods) {
2745 foreach my $f (qw/file_a file_b/) {
2746 next unless defined $m->{$f};
2747 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2748 if (length $pfx.$dir && ! defined $types{$dir}) {
2749 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2757 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2761 my ($self, $path) = @_;
2762 $self->{path_prefix}.(defined $path ? $path : '');
2766 my ($self, $path) = @_;
2767 if ($self->{url} =~ m#^https?://#) {
2768 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2770 $self->{url} . '/' . $self->repo_path($path);
2775 my $rm = $self->{rm};
2776 delete $rm->{''}; # we never delete the url we're tracking
2779 foreach (keys %$rm) {
2780 my @d = split m#/#, $_;
2784 $c .= '/' . shift @d;
2788 delete $rm->{$self->{svn_path}};
2789 delete $rm->{''}; # we never delete the url we're tracking
2792 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2797 my @dn = split m#/#, $_;
2799 delete $rm->{join '/', @dn};
2806 command_close_pipe($fh, $ctx);
2808 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2809 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2810 $self->close_directory($bat->{$d}, $p);
2811 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2812 print "\tD+\t$d/\n" unless $::_q;
2813 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2818 sub open_or_add_dir {
2819 my ($self, $full_path, $baton) = @_;
2820 my $t = $self->{types}->{$full_path};
2822 die "$full_path not known in r$self->{r} or we have a bug!\n";
2824 if ($t == $SVN::Node::none) {
2825 return $self->add_directory($full_path, $baton,
2826 undef, -1, $self->{pool});
2827 } elsif ($t == $SVN::Node::dir) {
2828 return $self->open_directory($full_path, $baton,
2829 $self->{r}, $self->{pool});
2831 print STDERR "$full_path already exists in repository at ",
2832 "r$self->{r} and it is not a directory (",
2833 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2838 my ($self, $path) = @_;
2839 my $bat = $self->{bat};
2840 my $repo_path = $self->repo_path($path);
2841 return $bat->{''} unless (length $repo_path);
2842 my @p = split m#/+#, $repo_path;
2844 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2847 $c .= '/' . shift @p;
2848 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2854 my ($self, $m) = @_;
2855 my ($dir, $file) = split_path($m->{file_b});
2856 my $pbat = $self->ensure_path($dir);
2857 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2859 print "\tA\t$m->{file_b}\n" unless $::_q;
2860 $self->chg_file($fbat, $m);
2861 $self->close_file($fbat,undef,$self->{pool});
2865 my ($self, $m) = @_;
2866 my ($dir, $file) = split_path($m->{file_b});
2867 my $pbat = $self->ensure_path($dir);
2868 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2869 $self->url_path($m->{file_a}), $self->{r});
2870 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2871 $self->chg_file($fbat, $m);
2872 $self->close_file($fbat,undef,$self->{pool});
2876 my ($self, $path, $pbat) = @_;
2877 my $rpath = $self->repo_path($path);
2878 my ($dir, $file) = split_path($rpath);
2879 $self->{rm}->{$dir} = 1;
2880 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2884 my ($self, $m) = @_;
2885 my ($dir, $file) = split_path($m->{file_b});
2886 my $pbat = $self->ensure_path($dir);
2887 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2888 $self->url_path($m->{file_a}), $self->{r});
2889 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2890 $self->chg_file($fbat, $m);
2891 $self->close_file($fbat,undef,$self->{pool});
2893 ($dir, $file) = split_path($m->{file_a});
2894 $pbat = $self->ensure_path($dir);
2895 $self->delete_entry($m->{file_a}, $pbat);
2899 my ($self, $m) = @_;
2900 my ($dir, $file) = split_path($m->{file_b});
2901 my $pbat = $self->ensure_path($dir);
2902 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2903 $pbat,$self->{r},$self->{pool});
2904 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2905 $self->chg_file($fbat, $m);
2906 $self->close_file($fbat,undef,$self->{pool});
2909 sub T { shift->M(@_) }
2911 sub change_file_prop {
2912 my ($self, $fbat, $pname, $pval) = @_;
2913 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2917 my ($self, $fbat, $m) = @_;
2918 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2919 $self->change_file_prop($fbat,'svn:executable','*');
2920 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2921 $self->change_file_prop($fbat,'svn:executable',undef);
2923 my $fh = IO::File->new_tmpfile or croak $!;
2924 if ($m->{mode_b} =~ /^120/) {
2925 print $fh 'link ' or croak $!;
2926 $self->change_file_prop($fbat,'svn:special','*');
2927 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2928 $self->change_file_prop($fbat,'svn:special',undef);
2930 defined(my $pid = fork) or croak $!;
2932 open STDOUT, '>&', $fh or croak $!;
2933 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2937 $fh->flush == 0 or croak $!;
2938 seek $fh, 0, 0 or croak $!;
2940 my $md5 = Digest::MD5->new;
2941 $md5->addfile($fh) or croak $!;
2942 seek $fh, 0, 0 or croak $!;
2944 my $exp = $md5->hexdigest;
2945 my $pool = SVN::Pool->new;
2946 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2947 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2948 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2951 close $fh or croak $!;
2955 my ($self, $m) = @_;
2956 my ($dir, $file) = split_path($m->{file_b});
2957 my $pbat = $self->ensure_path($dir);
2958 print "\tD\t$m->{file_b}\n" unless $::_q;
2959 $self->delete_entry($m->{file_b}, $pbat);
2964 my ($p,$bat) = ($self->{pool}, $self->{bat});
2965 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2967 $self->close_directory($bat->{$_}, $p);
2969 $self->close_directory($bat->{''}, $p);
2970 $self->SUPER::close_edit($p);
2976 $self->SUPER::abort_edit($self->{pool});
2981 $self->SUPER::DESTROY(@_);
2982 $self->{pool}->clear;
2985 # this drives the editor
2988 my $mods = $self->{mods};
2989 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2990 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2992 if (defined $o{$f}) {
2995 fatal("Invalid change type: $f\n");
2998 $self->rmdirs if $_rmdir;
3004 return scalar @$mods;
3007 package Git::SVN::Ra;
3008 use vars qw/@ISA $config_dir $_log_window_size/;
3011 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3014 # enforce temporary pool usage for some simple functions
3016 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3017 my $SUPER = "SUPER::$f";
3020 my $pool = SVN::Pool->new;
3021 my @ret = $self->$SUPER(@_,$pool);
3023 wantarray ? @ret : $ret[0];
3029 my ($class, $url) = @_;
3031 return $RA if ($RA && $RA->{url} eq $url);
3033 SVN::_Core::svn_config_ensure($config_dir, undef);
3034 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3035 SVN::Client::get_simple_provider(),
3036 SVN::Client::get_ssl_server_trust_file_provider(),
3037 SVN::Client::get_simple_prompt_provider(
3038 \&Git::SVN::Prompt::simple, 2),
3039 SVN::Client::get_ssl_client_cert_file_provider(),
3040 SVN::Client::get_ssl_client_cert_prompt_provider(
3041 \&Git::SVN::Prompt::ssl_client_cert, 2),
3042 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3043 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3044 SVN::Client::get_username_provider(),
3045 SVN::Client::get_ssl_server_trust_prompt_provider(
3046 \&Git::SVN::Prompt::ssl_server_trust),
3047 SVN::Client::get_username_prompt_provider(
3048 \&Git::SVN::Prompt::username, 2),
3050 my $config = SVN::Core::config_get_config($config_dir);
3052 my $self = SVN::Ra->new(url => $url, auth => $baton,
3054 pool => SVN::Pool->new,
3055 auth_provider_callbacks => $callbacks);
3056 $self->{svn_path} = $url;
3057 $self->{repos_root} = $self->get_repos_root;
3058 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3059 $self->{cache} = { check_path => { r => 0, data => {} },
3060 get_dir => { r => 0, data => {} } };
3061 $RA = bless $self, $class;
3065 my ($self, $path, $r) = @_;
3066 my $cache = $self->{cache}->{check_path};
3067 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3068 return $cache->{data}->{$path};
3070 my $pool = SVN::Pool->new;
3071 my $t = $self->SUPER::check_path($path, $r, $pool);
3073 if ($r != $cache->{r}) {
3074 %{$cache->{data}} = ();
3077 $cache->{data}->{$path} = $t;
3081 my ($self, $dir, $r) = @_;
3082 my $cache = $self->{cache}->{get_dir};
3083 if ($r == $cache->{r}) {
3084 if (my $x = $cache->{data}->{$dir}) {
3085 return wantarray ? @$x : $x->[0];
3088 my $pool = SVN::Pool->new;
3089 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3090 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3092 if ($r != $cache->{r}) {
3093 %{$cache->{data}} = ();
3096 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3097 wantarray ? (\%dirents, $r, $props) : \%dirents;
3101 # do not call the real DESTROY since we store ourselves in $RA
3105 my ($self, @args) = @_;
3106 my $pool = SVN::Pool->new;
3107 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3108 my $ret = $self->SUPER::get_log(@args, $pool);
3113 sub get_commit_editor {
3114 my ($self, $log, $cb, $pool) = @_;
3115 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3116 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3120 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3121 my $new = ($rev_a == $rev_b);
3122 my $path = $gs->{path};
3124 if ($new && -e $gs->{index}) {
3125 unlink $gs->{index} or die
3126 "Couldn't unlink index: $gs->{index}: $!\n";
3128 my $pool = SVN::Pool->new;
3129 $editor->set_path_strip($path);
3130 my (@pc) = split m#/#, $path;
3131 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3133 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3135 # Since we can't rely on svn_ra_reparent being available, we'll
3136 # just have to do some magic with set_path to make it so
3137 # we only want a partial path.
3139 my $final = join('/', @pc);
3141 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3142 $sp .= '/' if length $sp;
3145 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3147 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3149 $reporter->finish_report($pool);
3151 $editor->{git_commit_ok};
3154 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3155 # svn_ra_reparent didn't work before 1.4)
3157 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3158 my $path = $gs->{path};
3159 my $pool = SVN::Pool->new;
3161 my $full_url = $self->{url};
3162 my $old_url = $full_url;
3163 $full_url .= "/$path" if length $path;
3164 my ($ra, $reparented);
3165 if ($old_url ne $full_url) {
3166 if ($old_url !~ m#^svn(\+ssh)?://#) {
3167 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3169 $self->{url} = $full_url;
3175 $ra = Git::SVN::Ra->new($full_url);
3180 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3181 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3182 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3183 $reporter->finish_report($pool);
3186 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3187 $self->{url} = $old_url;
3191 $editor->{git_commit_ok};
3194 sub longest_common_path {
3195 my ($gsv, $globs) = @_;
3197 my $common_max = scalar @$gsv;
3199 foreach my $gs (@$gsv) {
3200 my @tmp = split m#/#, $gs->{path};
3203 $p .= length($p) ? "/$_" : $_;
3209 $common_max += scalar @$globs;
3210 foreach my $glob (@$globs) {
3211 my @tmp = split m#/#, $glob->{path}->{left};
3214 $p .= length($p) ? "/$_" : $_;
3220 my $longest_path = '';
3221 foreach (sort {length $b <=> length $a} keys %common) {
3222 if ($common{$_} == $common_max) {
3230 sub gs_fetch_loop_common {
3231 my ($self, $base, $head, $gsv, $globs) = @_;
3232 return if ($base > $head);
3233 my $inc = $_log_window_size;
3234 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3235 my $longest_path = longest_common_path($gsv, $globs);
3236 my $ra_url = $self->{url};
3240 my $err_handler = $SVN::Error::handler;
3241 $SVN::Error::handler = sub {
3243 skip_unknown_revs($err);
3246 my ($paths, $r, $author, $date, $log) = @_;
3247 [ dup_changed_paths($paths),
3248 { author => $author, date => $date, log => $log } ];
3250 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3251 sub { $revs{$_[1]} = _cb(@_) });
3252 if ($err && $max >= $head) {
3253 print STDERR "Path '$longest_path' ",
3254 "was probably deleted:\n",
3255 $err->expanded_message,
3256 "\nWill attempt to follow ",
3257 "revisions r$min .. r$max ",
3258 "committed before the deletion\n";
3260 while (--$hi >= $min) {
3262 $self->get_log([$longest_path], $min, $hi,
3265 $revs{$_[1]} = _cb(@_) });
3267 print STDERR "r$min .. r$ok OK\n";
3272 $SVN::Error::handler = $err_handler;
3274 my %exists = map { $_->{path} => $_ } @$gsv;
3275 foreach my $r (sort {$a <=> $b} keys %revs) {
3276 my ($paths, $logged) = @{$revs{$r}};
3278 foreach my $gs ($self->match_globs(\%exists, $paths,
3280 if ($gs->rev_db_max >= $r) {
3283 next unless $gs->match_paths($paths, $r);
3284 $gs->{logged_rev_props} = $logged;
3285 if (my $last_commit = $gs->last_commit) {
3286 $gs->assert_index_clean($last_commit);
3288 my $log_entry = $gs->do_fetch($paths, $r);
3290 $gs->do_git_commit($log_entry);
3293 foreach my $g (@$globs) {
3294 my $k = "svn-remote.$g->{remote}." .
3296 Git::SVN::tmp_config($k, $r);
3302 $self = Git::SVN::Ra->new($ra_url);
3303 $ra_invalid = undef;
3306 # pre-fill the .rev_db since it'll eventually get filled in
3307 # with '0' x40 if something new gets committed
3308 foreach my $gs (@$gsv) {
3309 next if defined $gs->rev_db_get($max);
3310 $gs->rev_db_set($max, 0 x40);
3312 foreach my $g (@$globs) {
3313 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3314 Git::SVN::tmp_config($k, $max);
3316 last if $max >= $head;
3319 $max = $head if ($max > $head);
3324 my ($self, $exists, $paths, $globs, $r) = @_;
3327 my ($self, $exists, $g, $r) = @_;
3328 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3329 return unless scalar @x == 3;
3330 my $dirents = $x[0];
3331 foreach my $de (keys %$dirents) {
3332 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3333 my $p = $g->{path}->full_path($de);
3334 next if $exists->{$p};
3335 next if (length $g->{path}->{right} &&
3336 ($self->check_path($p, $r) !=
3338 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3339 $g->{ref}->full_path($de), 1);
3342 foreach my $g (@$globs) {
3343 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3344 if ($path->{action} =~ /^[AR]$/) {
3345 get_dir_check($self, $exists, $g, $r);
3348 foreach (keys %$paths) {
3349 if (/$g->{path}->{left_regex}/ &&
3350 !/$g->{path}->{regex}/) {
3351 next if $paths->{$_}->{action} !~ /^[AR]$/;
3352 get_dir_check($self, $exists, $g, $r);
3354 next unless /$g->{path}->{regex}/;
3356 my $pathname = $g->{path}->full_path($p);
3357 next if $exists->{$pathname};
3358 next if ($self->check_path($pathname, $r) !=
3360 $exists->{$pathname} = Git::SVN->init(
3361 $self->{url}, $pathname, undef,
3362 $g->{ref}->full_path($p), 1);
3365 foreach (split m#/#, $g->{path}->{left}) {
3367 next unless ($paths->{$c} &&
3368 ($paths->{$c}->{action} =~ /^[AR]$/));
3369 get_dir_check($self, $exists, $g, $r);
3377 return $self->{url} if ($self->{url} eq $self->{repos_root});
3378 my $url = $self->{repos_root};
3379 my @components = split(m!/!, $self->{svn_path});
3382 $url .= "/$c" if length $c;
3383 eval { (ref $self)->new($url)->get_latest_revnum };
3384 } while ($@ && ($c = shift @components));
3390 unless (defined $can_do_switch) {
3391 my $pool = SVN::Pool->new;
3393 $self->do_switch(1, '', 0, $self->{url},
3394 SVN::Delta::Editor->new, $pool);
3399 $rep->abort_report($pool);
3407 sub skip_unknown_revs {
3409 my $errno = $err->apr_err();
3410 # Maybe the branch we're tracking didn't
3411 # exist when the repo started, so it's
3412 # not an error if it doesn't, just continue
3414 # Wonderfully consistent library, eh?
3415 # 160013 - svn:// and file://
3416 # 175002 - http(s)://
3417 # 175007 - http(s):// (this repo required authorization, too...)
3418 # More codes may be discovered later...
3419 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3420 my $err_key = $err->expanded_message;
3421 # revision numbers change every time, filter them out
3422 $err_key =~ s/\d+/\0/g;
3423 $err_key = "$errno\0$err_key";
3424 unless ($ignored_err{$err_key}) {
3425 warn "W: Ignoring error from SVN, path probably ",
3426 "does not exist: ($errno): ",
3427 $err->expanded_message,"\n";
3428 $ignored_err{$err_key} = 1;
3432 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3435 # svn_log_changed_path_t objects passed to get_log are likely to be
3436 # overwritten even if only the refs are copied to an external variable,
3437 # so we should dup the structures in their entirety. Using an externally
3438 # passed pool (instead of our temporary and quickly cleared pool in
3439 # Git::SVN::Ra) does not help matters at all...
3440 sub dup_changed_paths {
3442 return undef unless $paths;
3444 foreach my $p (keys %$paths) {
3445 my $i = $paths->{$p};
3446 my %s = map { $_ => $i->$_ }
3447 qw/copyfrom_path copyfrom_rev action/;
3453 package Git::SVN::Log;
3456 use POSIX qw/strftime/;
3457 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3458 %rusers $show_commit $incremental/;
3463 return 1 if defined $c->{r};
3465 # big commit message got truncated by the 16k pretty buffer in rev-list
3466 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3467 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3469 my @log = command(qw/cat-file commit/, $c->{c});
3471 # shift off the headers
3472 shift @log while ($log[0] ne '');
3475 # TODO: make $c->{l} not have a trailing newline in the future
3476 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3478 (undef, $c->{r}, undef) = ::extract_metadata(
3479 (grep(/^git-svn-id: /, @log))[-1]);
3481 return defined $c->{r};
3487 $dcvar = 'color.diff';
3488 $dc = `git-config --get $dcvar`;
3490 # nothing at all; fallback to "diff.color"
3491 $dcvar = 'diff.color';
3492 $dc = `git-config --get $dcvar`;
3495 if ($dc eq 'auto') {
3497 $pc = `git-config --get color.pager`;
3499 # does not have it -- fallback to pager.color
3500 $pc = `git-config --bool --get pager.color`;
3503 $pc = `git-config --bool --get color.pager`;
3509 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3510 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3514 return 0 if $dc eq 'never';
3515 return 1 if $dc eq 'always';
3516 chomp($dc = `git-config --bool --get $dcvar`);
3517 return ($dc eq 'true');
3520 sub git_svn_log_cmd {
3521 my ($r_min, $r_max, @args) = @_;
3523 my (@files, @log_opts);
3524 foreach my $x (@args) {
3525 if ($x eq '--' || @files) {
3528 if (::verify_ref("$x^0")) {
3536 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3537 $gs ||= Git::SVN->_new;
3538 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3540 push @cmd, '-r' unless $non_recursive;
3541 push @cmd, qw/--raw --name-status/ if $verbose;
3542 push @cmd, '--color' if log_use_color();
3543 push @cmd, @log_opts;
3544 if (defined $r_max && $r_max == $r_min) {
3545 push @cmd, '--max-count=1';
3546 if (my $c = $gs->rev_db_get($r_max)) {
3549 } elsif (defined $r_max) {
3550 my ($c_min, $c_max);
3551 $c_max = $gs->rev_db_get($r_max);
3552 $c_min = $gs->rev_db_get($r_min);
3553 if (defined $c_min && defined $c_max) {
3554 if ($r_max > $r_max) {
3555 push @cmd, "$c_min..$c_max";
3557 push @cmd, "$c_max..$c_min";
3559 } elsif ($r_max > $r_min) {
3565 return (@cmd, @files);
3568 # adapted from pager.c
3570 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3571 if (!defined $pager) {
3573 } elsif (length $pager == 0 || $pager eq 'cat') {
3579 return unless -t *STDOUT;
3580 pipe my $rfd, my $wfd or return;
3581 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3583 open STDOUT, '>&', $wfd or
3584 ::fatal "Can't redirect to stdout: $!\n";
3587 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3588 $ENV{LESS} ||= 'FRSX';
3589 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3592 sub tz_to_s_offset {
3595 return ($1 * 60) + ($tz * 3600);
3598 sub get_author_info {
3599 my ($dest, $author, $t, $tz) = @_;
3600 $author =~ s/(?:^\s*|\s*$)//g;
3601 $dest->{a_raw} = $author;
3604 $au = $rusers{$author} || undef;
3607 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3612 # Date::Parse isn't in the standard Perl distro :(
3613 if ($tz =~ s/^\+//) {
3614 $t += tz_to_s_offset($tz);
3615 } elsif ($tz =~ s/^\-//) {
3616 $t -= tz_to_s_offset($tz);
3618 $dest->{t_utc} = $t;
3621 sub process_commit {
3622 my ($c, $r_min, $r_max, $defer) = @_;
3623 if (defined $r_min && defined $r_max) {
3624 if ($r_min == $c->{r} && $r_min == $r_max) {
3628 return 1 if $r_min == $r_max;
3629 if ($r_min < $r_max) {
3630 # we need to reverse the print order
3631 return 0 if (defined $limit && --$limit < 0);
3635 if ($r_min != $r_max) {
3636 return 1 if ($r_min < $c->{r});
3637 return 1 if ($r_max > $c->{r});
3640 return 0 if (defined $limit && --$limit < 0);
3649 if (my $l = $c->{l}) {
3650 while ($l->[0] =~ /^\s*$/) { shift @$l }
3653 $l_fmt ||= 'A' . length($c->{r});
3654 print 'r',pack($l_fmt, $c->{r}),' | ';
3655 print "$c->{c} | " if $show_commit;
3658 show_commit_normal($c);
3662 sub show_commit_changed_paths {
3664 return unless $c->{changed};
3665 print "Changed paths:\n", @{$c->{changed}};
3668 sub show_commit_normal {
3670 print '-' x72, "\nr$c->{r} | ";
3671 print "$c->{c} | " if $show_commit;
3672 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3673 localtime($c->{t_utc})), ' | ';
3676 if (my $l = $c->{l}) {
3677 while ($l->[$#$l] eq "\n" && $#$l > 0
3678 && $l->[($#$l - 1)] eq "\n") {
3681 $nr_line = scalar @$l;
3683 print "1 line\n\n\n";
3685 if ($nr_line == 1) {
3686 $nr_line = '1 line';
3688 $nr_line .= ' lines';
3690 print $nr_line, "\n";
3691 show_commit_changed_paths($c);
3693 print $_ foreach @$l;
3697 show_commit_changed_paths($c);
3701 foreach my $x (qw/raw stat diff/) {
3704 print $_ foreach @{$c->{$x}}
3711 my ($r_min, $r_max);
3712 my $r_last = -1; # prevent dupes
3718 if (defined $::_revision) {
3719 if ($::_revision =~ /^(\d+):(\d+)$/) {
3720 ($r_min, $r_max) = ($1, $2);
3721 } elsif ($::_revision =~ /^\d+$/) {
3722 $r_min = $r_max = $::_revision;
3724 ::fatal "-r$::_revision is not supported, use ",
3725 "standard \'git log\' arguments instead\n";
3730 @args = git_svn_log_cmd($r_min, $r_max, @args);
3731 my $log = command_output_pipe(@args);
3733 my (@k, $c, $d, $stat);
3734 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3736 if (/^${esc_color}commit ($::sha1_short)/o) {
3738 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3740 process_commit($c, $r_min, $r_max, \@k) or
3745 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3746 get_author_info($c, $1, $2, $3);
3747 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3749 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3750 push @{$c->{raw}}, $_;
3751 } elsif (/^${esc_color}[ACRMDT]\t/) {
3752 # we could add $SVN->{svn_path} here, but that requires
3753 # remote access at the moment (repo_path_split)...
3754 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3755 push @{$c->{changed}}, $_;
3756 } elsif (/^${esc_color}diff /o) {
3758 push @{$c->{diff}}, $_;
3760 push @{$c->{diff}}, $_;
3761 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3762 $esc_color*[\+\-]*$esc_color$/x) {
3764 push @{$c->{stat}}, $_;
3765 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3766 push @{$c->{stat}}, $_;
3768 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3769 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3770 } elsif (s/^${esc_color} //o) {
3771 push @{$c->{l}}, $_;
3774 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3776 process_commit($c, $r_min, $r_max, \@k);
3782 process_commit($_, $r_min, $r_max) foreach reverse @k;
3786 print '-' x72,"\n" unless $incremental || $oneline;
3789 package Git::SVN::Migration;
3790 # these version numbers do NOT correspond to actual version numbers
3791 # of git nor git-svn. They are just relative.
3793 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3795 # v1 layout: .git/$id/info/url, refs/remotes/$id
3797 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3799 # v3 layout: .git/svn/$id, refs/remotes/$id
3800 # - info/url may remain for backwards compatibility
3801 # - this is what we migrate up to this layout automatically,
3802 # - this will be used by git svn init on single branches
3803 # v3.1 layout (auto migrated):
3804 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3805 # for backwards compatibility
3807 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3808 # - this is only created for newly multi-init-ed
3809 # repositories. Similar in spirit to the
3810 # --use-separate-remotes option in git-clone (now default)
3811 # - we do not automatically migrate to this (following
3812 # the example set by core git)
3816 use File::Path qw/mkpath/;
3817 use File::Basename qw/dirname basename/;
3818 use vars qw/$_minimize/;
3820 sub migrate_from_v0 {
3821 my $git_dir = $ENV{GIT_DIR};
3822 return undef unless -d $git_dir;
3823 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3827 my ($id, $orig_ref) = ($_, $_);
3828 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3829 next unless -f "$git_dir/$id/info/url";
3830 my $new_ref = "refs/remotes/$id";
3831 if (::verify_ref("$new_ref^0")) {
3832 print STDERR "W: $orig_ref is probably an old ",
3833 "branch used by an ancient version of ",
3835 "However, $new_ref also exists.\n",
3836 "We will not be able ",
3837 "to use this branch until this ",
3838 "ambiguity is resolved.\n";
3841 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3842 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3843 command_noisy('update-ref', $new_ref, $orig_ref);
3844 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3847 command_close_pipe($fh, $ctx);
3848 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3852 sub migrate_from_v1 {
3853 my $git_dir = $ENV{GIT_DIR};
3855 return $migrated unless -d $git_dir;
3856 my $svn_dir = "$git_dir/svn";
3858 # just in case somebody used 'svn' as their $id at some point...
3859 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3861 print STDERR "Migrating from a git-svn v1 layout...\n";
3863 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3864 "$svn_dir\n\t(required for this version ",
3865 "($::VERSION) of git-svn) does not. exist\n";
3866 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3869 next unless $x =~ s#^refs/remotes/##;
3871 next unless -f "$git_dir/$x/info/url";
3872 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3874 my $dn = dirname("$git_dir/svn/$x");
3875 mkpath([$dn]) unless -d $dn;
3876 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3877 mkpath(["$git_dir/svn/svn"]);
3878 print STDERR " - $git_dir/$x/info => ",
3879 "$git_dir/svn/$x/info\n";
3880 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3882 # don't worry too much about these, they probably
3883 # don't exist with repos this old (save for index,
3884 # and we can easily regenerate that)
3885 foreach my $f (qw/unhandled.log index .rev_db/) {
3886 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3889 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3890 rename "$git_dir/$x", "$git_dir/svn/$x" or
3895 command_close_pipe($fh, $ctx);
3896 print STDERR "Done migrating from a git-svn v1 layout\n";
3901 my ($l_map, $pfx, $path) = @_;
3903 foreach (<$path/*>) {
3904 if (-r "$_/info/url") {
3905 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3906 my $ref_id = $pfx . basename $_;
3907 my $url = ::file_to_s("$_/info/url");
3908 $l_map->{$ref_id} = $url;
3915 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3916 read_old_urls($l_map, $x, $_);
3920 sub migrate_from_v2 {
3921 my @cfg = command(qw/config -l/);
3922 return if grep /^svn-remote\..+\.url=/, @cfg;
3924 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3927 foreach my $ref_id (sort keys %l_map) {
3928 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3930 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3937 sub minimize_connections {
3938 my $r = Git::SVN::read_all_remotes();
3940 my $root_repos = {};
3941 foreach my $repo_id (keys %$r) {
3942 my $url = $r->{$repo_id}->{url} or next;
3943 my $fetch = $r->{$repo_id}->{fetch} or next;
3944 my $ra = Git::SVN::Ra->new($url);
3946 # skip existing cases where we already connect to the root
3947 if (($ra->{url} eq $ra->{repos_root}) ||
3948 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3950 $root_repos->{$ra->{url}} = $repo_id;
3954 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3955 my $root_path = $ra->{url};
3956 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3957 foreach my $path (keys %$fetch) {
3958 my $ref_id = $fetch->{$path};
3959 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3961 # make sure we can read when connecting to
3962 # a higher level of a repository
3963 my ($last_rev, undef) = $gs->last_rev_commit;
3964 if (!defined $last_rev) {
3966 $root_ra->get_latest_revnum;
3970 my $new = $root_path;
3971 $new .= length $path ? "/$path" : '';
3973 $root_ra->get_log([$new], $last_rev, $last_rev,
3977 $new_urls->{$ra->{repos_root}}->{$new} =
3978 { ref_id => $ref_id,
3979 old_repo_id => $repo_id,
3980 old_path => $path };
3985 foreach my $url (keys %$new_urls) {
3986 # see if we can re-use an existing [svn-remote "repo_id"]
3987 # instead of creating a(n ugly) new section:
3988 my $repo_id = $root_repos->{$url} ||
3989 Git::SVN::sanitize_remote_name($url);
3991 my $fetch = $new_urls->{$url};
3992 foreach my $path (keys %$fetch) {
3993 my $x = $fetch->{$path};
3994 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3995 my $pfx = "svn-remote.$x->{old_repo_id}";
3997 my $old_fetch = quotemeta("$x->{old_path}:".
3998 "refs/remotes/$x->{ref_id}");
3999 command_noisy(qw/config --unset/,
4000 "$pfx.fetch", '^'. $old_fetch . '$');
4001 delete $r->{$x->{old_repo_id}}->
4002 {fetch}->{$x->{old_path}};
4003 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4004 command_noisy(qw/config --unset/,
4006 push @emptied, $x->{old_repo_id}
4011 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4012 "$ENV{GIT_DIR}/config";
4014 The following [svn-remote] sections in your config file ($file) are empty
4015 and can be safely removed:
4017 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4021 sub migration_check {
4025 minimize_connections() if $_minimize;
4028 package Git::IndexInfo;
4031 use Git qw/command_input_pipe command_close_pipe/;
4035 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4036 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4040 my ($self, $path) = @_;
4041 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4042 return ++$self->{nr};
4048 my ($self, $mode, $hash, $path) = @_;
4049 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4050 return ++$self->{nr};
4057 command_close_pipe($self->{gui}, $self->{ctx});
4060 package Git::SVN::GlobSpec;
4065 my ($class, $glob) = @_;
4067 $re =~ s!/+$!!g; # no need for trailing slashes
4068 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4069 my ($left, $right) = ($1, $2);
4071 die "Only one '*' wildcard expansion ",
4072 "is supported (got $nr): '$glob'\n";
4073 } elsif ($nr == 0) {
4074 die "One '*' is needed for glob: '$glob'\n";
4076 $re = quotemeta($left) . $re . quotemeta($right);
4077 if (length $left && !($left =~ s!/+$!!g)) {
4078 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4080 if (length $right && !($right =~ s!^/+!!g)) {
4081 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4083 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4084 bless { left => $left, right => $right, left_regex => $left_re,
4085 regex => qr/$re/, glob => $glob }, $class;
4089 my ($self, $path) = @_;
4090 return (length $self->{left} ? "$self->{left}/" : '') .
4091 $path . (length $self->{right} ? "/$self->{right}" : '');
4099 $remotes = { # returned by read_all_remotes()
4101 # svn-remote.svn.url=https://svn.musicpd.org
4102 url => 'https://svn.musicpd.org',
4103 # svn-remote.svn.fetch=mpd/trunk:trunk
4105 'mpd/trunk' => 'trunk',
4107 # svn-remote.svn.tags=mpd/tags/*:tags/*
4112 regex => qr!mpd/tags/([^/]+)$!,
4118 regex => qr!tags/([^/]+)$!,
4125 $log_entry hashref as returned by libsvn_log_entry()
4127 log => 'whitespace-formatted log entry
4128 ', # trailing newline is preserved
4129 revision => '8', # integer
4130 date => '2004-02-24T17:01:44.108345Z', # commit date
4131 author => 'committer name'
4135 # this is generated by generate_diff();
4136 @mods = array of diff-index line hashes, each element represents one line
4137 of diff-index output
4139 diff-index line ($m hash)
4141 mode_a => first column of diff-index output, no leading ':',
4142 mode_b => second column of diff-index output,
4143 sha1_b => sha1sum of the final blob,
4144 chg => change type [MCRADT],
4145 file_a => original file name of a file (iff chg is 'C' or 'R')
4146 file_b => new/current file name of a file (any chg)
4150 # retval of read_url_paths{,_all}();
4152 # repository root url
4153 'https://svn.musicpd.org' => {
4154 # repository path # GIT_SVN_ID
4155 'mpd/trunk' => 'trunk',
4156 'mpd/tags/0.11.5' => 'tags/0.11.5',
4161 I don't trust the each() function on unless I created %hash myself
4162 because the internal iterator may not have started at base.