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";
377 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
378 'Cannot dcommit with a dirty index. Commit your changes first'
379 . "or stash them with `git stash'.\n";
382 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
383 print "Committing to $url ...\n";
385 die "Unable to determine upstream SVN information from ",
389 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
390 if ($_no_rebase && scalar(@$linear_refs) > 1) {
391 warn "Attempting to commit more than one change while ",
392 "--no-rebase is enabled.\n",
393 "If these changes depend on each other, re-running ",
394 "without --no-rebase will be required."
397 my $d = shift @$linear_refs or last;
398 unless (defined $last_rev) {
399 (undef, $last_rev, undef) = cmt_metadata("$d~1");
400 unless (defined $last_rev) {
401 fatal "Unable to extract revision information ",
402 "from commit $d~1\n";
406 print "diff-tree $d~1 $d\n";
409 my %ed_opts = ( r => $last_rev,
410 log => get_commit_entry($d)->{log},
411 ra => Git::SVN::Ra->new($gs->full_url),
415 print "Committed r$_[0]\n";
419 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
420 print "No changes\n$d~1 == $d\n";
421 } elsif ($parents->{$d} && @{$parents->{$d}}) {
422 $gs->{inject_parents_dcommit}->{$cmt_rev} =
425 $_fetch_all ? $gs->fetch_all : $gs->fetch;
428 # we always want to rebase against the current HEAD,
429 # not any head that was passed to us
430 my @diff = command('diff-tree', $d,
434 @finish = rebase_cmd();
435 print STDERR "W: $d and ", $gs->refname,
436 " differ, using @finish:\n",
437 join("\n", @diff), "\n";
439 print "No changes between current HEAD and ",
441 "\nResetting to the latest ",
443 @finish = qw/reset --mixed/;
445 command_noisy(@finish, $gs->refname);
448 my ($url_, $rev_, $uuid_, $gs_) =
449 working_head_info($head, \@refs);
450 my ($linear_refs_, $parents_) =
451 linearize_history($gs_, \@refs);
452 if (scalar(@$linear_refs) !=
453 scalar(@$linear_refs_)) {
454 fatal "# of revisions changed ",
456 join("\n", @$linear_refs),
458 join("\n", @$linear_refs_), "\n",
459 'If you are attempting to commit ',
460 "merges, try running:\n\t",
461 'git rebase --interactive',
462 '--preserve-merges ',
464 "\nBefore dcommitting";
467 fatal "URL mismatch after rebase: ",
470 if ($uuid_ ne $uuid) {
471 fatal "uuid mismatch after rebase: ",
476 for ($i = 0; $i < scalar @$linear_refs; $i++) {
477 my $new = $linear_refs_->[$i] or next;
479 $parents->{$linear_refs->[$i]};
485 $last_rev = $cmt_rev;
491 my $revision_or_hash = shift;
493 if ($revision_or_hash =~ /^r\d+$/) {
497 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
499 die "Unable to determine upstream SVN information from ",
502 my $desired_revision = substr($revision_or_hash, 1);
503 $result = $gs->rev_db_get($desired_revision);
505 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
508 print "$result\n" if $result;
512 command_noisy(qw/update-index --refresh/);
513 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
515 die "Unable to determine upstream SVN information from ",
516 "working tree history\n";
518 if (command(qw/diff-index HEAD --/)) {
519 print STDERR "Cannot rebase with uncommited changes:\n";
520 command_noisy('status');
524 $_fetch_all ? $gs->fetch_all : $gs->fetch;
526 command_noisy(rebase_cmd(), $gs->refname);
529 sub cmd_show_ignore {
530 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
531 $gs ||= Git::SVN->new;
532 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
533 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
538 unless (defined $_trunk || defined $_branches || defined $_tags) {
542 # there are currently some bugs that prevent multi-init/multi-fetch
543 # setups from working well without this.
544 $Git::SVN::_minimize_url = 1;
546 $_prefix = '' unless defined $_prefix;
552 if (defined $_trunk) {
553 my $trunk_ref = $_prefix . 'trunk';
554 # try both old-style and new-style lookups:
555 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
557 my ($trunk_url, $trunk_path) =
558 complete_svn_url($url, $_trunk);
559 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
563 return unless defined $_branches || defined $_tags;
564 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
565 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
566 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
569 sub cmd_multi_fetch {
570 my $remotes = Git::SVN::read_all_remotes();
571 foreach my $repo_id (sort keys %$remotes) {
572 if ($remotes->{$repo_id}->{url}) {
573 Git::SVN::fetch_all($repo_id, $remotes);
578 # this command is special because it requires no metadata
579 sub cmd_commit_diff {
580 my ($ta, $tb, $url) = @_;
581 my $usage = "Usage: $0 commit-diff -r<revision> ".
582 "<tree-ish> <tree-ish> [<URL>]\n";
583 fatal($usage) if (!defined $ta || !defined $tb);
586 my $gs = eval { Git::SVN->new };
588 fatal("Needed URL or usable git-svn --id in ",
589 "the command-line\n", $usage);
592 $svn_path = $gs->{path};
594 unless (defined $_revision) {
595 fatal("-r|--revision is a required argument\n", $usage);
597 if (defined $_message && defined $_file) {
598 fatal("Both --message/-m and --file/-F specified ",
599 "for the commit message.\n",
600 "I have no idea what you mean\n");
602 if (defined $_file) {
603 $_message = file_to_s($_file);
605 $_message ||= get_commit_entry($tb)->{log};
607 my $ra ||= Git::SVN::Ra->new($url);
608 $svn_path ||= $ra->{svn_path};
611 $r = $ra->get_latest_revnum;
612 } elsif ($r !~ /^\d+$/) {
613 die "revision argument: $r not understood by git-svn\n";
615 my %ed_opts = ( r => $r,
620 editor_cb => sub { print "Committed r$_[0]\n" },
621 svn_path => $svn_path );
622 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
623 print "No changes\n$ta == $tb\n";
627 ########################### utility functions #########################
630 my @cmd = qw/rebase/;
631 push @cmd, '-v' if $_verbose;
632 push @cmd, qw/--merge/ if $_merge;
633 push @cmd, "--strategy=$_strategy" if $_strategy;
637 sub post_fetch_checkout {
638 return if $_no_checkout;
639 my $gs = $Git::SVN::_head or return;
640 return if verify_ref('refs/heads/master^0');
642 my $valid_head = verify_ref('HEAD^0');
643 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
644 return if ($valid_head || !verify_ref('HEAD^0'));
646 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
647 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
650 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
651 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
652 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
653 print STDERR "Checked out HEAD:\n ",
654 $gs->full_url, " r", $gs->last_rev, "\n";
657 sub complete_svn_url {
658 my ($url, $path) = @_;
660 if ($path !~ m#^[a-z\+]+://#) {
661 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
662 fatal("E: '$path' is not a complete URL ",
663 "and a separate URL is not specified\n");
665 return ($url, $path);
670 sub complete_url_ls_init {
671 my ($ra, $repo_path, $switch, $pfx) = @_;
672 unless ($repo_path) {
673 print STDERR "W: $switch not specified\n";
676 $repo_path =~ s#/+$##;
677 if ($repo_path =~ m#^[a-z\+]+://#) {
678 $ra = Git::SVN::Ra->new($repo_path);
681 $repo_path =~ s#^/+##;
683 fatal("E: '$repo_path' is not a complete URL ",
684 "and a separate URL is not specified\n");
687 my $url = $ra->{url};
688 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
689 my $k = "svn-remote.$gs->{repo_id}.url";
690 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
691 if ($orig_url && ($orig_url ne $gs->{url})) {
692 die "$k already set: $orig_url\n",
693 "wanted to set to: $gs->{url}\n";
695 command_oneline('config', $k, $gs->{url}) unless $orig_url;
696 my $remote_path = "$ra->{svn_path}/$repo_path/*";
697 $remote_path =~ s#/+#/#g;
698 $remote_path =~ s#^/##g;
699 my ($n) = ($switch =~ /^--(\w+)/);
700 if (length $pfx && $pfx !~ m#/$#) {
701 die "--prefix='$pfx' must have a trailing slash '/'\n";
703 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
704 "$remote_path:refs/remotes/$pfx*");
709 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
713 sub get_tree_from_treeish {
715 # $treeish can be a symbolic ref, too:
716 my $type = command_oneline(qw/cat-file -t/, $treeish);
718 while ($type eq 'tag') {
719 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
721 if ($type eq 'commit') {
722 $expected = (grep /^tree /, command(qw/cat-file commit/,
724 ($expected) = ($expected =~ /^tree ($sha1)$/o);
725 die "Unable to get tree from $treeish\n" unless $expected;
726 } elsif ($type eq 'tree') {
727 $expected = $treeish;
729 die "$treeish is a $type, expected tree, tag or commit\n";
734 sub get_commit_entry {
735 my ($treeish) = shift;
736 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
737 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
738 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
739 open my $log_fh, '>', $commit_editmsg or croak $!;
741 my $type = command_oneline(qw/cat-file -t/, $treeish);
742 if ($type eq 'commit' || $type eq 'tag') {
743 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
748 $in_msg = 1 if (/^\s*$/);
749 } elsif (/^git-svn-id: /) {
750 # skip this for now, we regenerate the
751 # correct one on re-fetch anyways
752 # TODO: set *:merge properties or like...
754 print $log_fh $_ or croak $!;
757 command_close_pipe($msg_fh, $ctx);
759 close $log_fh or croak $!;
761 if ($_edit || ($type eq 'tree')) {
762 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
763 # TODO: strip out spaces, comments, like git-commit.sh
764 system($editor, $commit_editmsg);
766 rename $commit_editmsg, $commit_msg or croak $!;
767 open $log_fh, '<', $commit_msg or croak $!;
768 { local $/; chomp($log_entry{log} = <$log_fh>); }
769 close $log_fh or croak $!;
775 my ($str, $file, $mode) = @_;
776 open my $fd,'>',$file or croak $!;
777 print $fd $str,"\n" or croak $!;
778 close $fd or croak $!;
779 chmod ($mode &~ umask, $file) if (defined $mode);
784 open my $fd,'<',$file or croak "$!: file: $file\n";
787 close $fd or croak $!;
792 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
794 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
795 my $log = $cmd eq 'log';
798 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
799 my ($user, $name, $email) = ($1, $2, $3);
801 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
803 $users{$user} = [$name, $email];
806 close $authors or croak $!;
809 # convert GetOpt::Long specs for use by git-config
810 sub read_repo_config {
811 return unless -d $ENV{GIT_DIR};
814 foreach my $o (keys %$opts) {
815 # if we have mixedCase and a long option-only, then
816 # it's a config-only variable that we don't need for
818 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
820 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
822 my $arg = 'git-config';
823 $arg .= ' --int' if ($o =~ /[:=]i$/);
824 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
825 if (ref $v eq 'ARRAY') {
826 chomp(my @tmp = `$arg --get-all svn.$key`);
829 chomp(my $tmp = `$arg --get svn.$key`);
830 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
835 delete @$opts{@config_only} if @config_only;
838 sub extract_metadata {
839 my $id = shift or return (undef, undef, undef);
840 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
842 if (!defined $rev || !$uuid || !$url) {
843 # some of the original repositories I made had
844 # identifiers like this:
845 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
847 return ($url, $rev, $uuid);
851 return extract_metadata((grep(/^git-svn-id: /,
852 command(qw/cat-file commit/, shift)))[-1]);
855 sub working_head_info {
856 my ($head, $refs) = @_;
857 my ($fh, $ctx) = command_output_pipe('log', '--no-color', $head);
861 if ( m{^commit ($::sha1)$} ) {
862 unshift @$refs, $hash if $hash and $refs;
866 next unless s{^\s*(git-svn-id:)}{$1};
867 my ($url, $rev, $uuid) = extract_metadata($_);
868 if (defined $url && defined $rev) {
869 next if $max{$url} and $max{$url} < $rev;
870 if (my $gs = Git::SVN->find_by_url($url)) {
871 my $c = $gs->rev_db_get($rev);
872 if ($c && $c eq $hash) {
873 close $fh; # break the pipe
874 return ($url, $rev, $uuid, $gs);
876 $max{$url} ||= $gs->rev_db_max;
881 command_close_pipe($fh, $ctx);
882 (undef, undef, undef, undef);
885 sub read_commit_parents {
886 my ($parents, $c) = @_;
887 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
888 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
889 @{$parents->{$c}} = split(/ /, $p);
892 sub linearize_history {
893 my ($gs, $refs) = @_;
895 foreach my $c (@$refs) {
896 read_commit_parents(\%parents, $c);
901 my $last_svn_commit = $gs->last_commit;
902 foreach my $c (reverse @$refs) {
903 next if $c eq $last_svn_commit;
906 unshift @linear_refs, $c;
909 # we only want the first parent to diff against for linear
910 # history, we save the rest to inject when we finalize the
912 my $fp_a = verify_ref("$c~1");
913 my $fp_b = shift @{$parents{$c}} if $parents{$c};
914 if (!$fp_a || !$fp_b) {
916 "has no parent commit, and therefore ",
917 "nothing to diff against.\n",
918 "You should be working from a repository ",
919 "originally created by git-svn\n";
921 if ($fp_a ne $fp_b) {
922 die "$c~1 = $fp_a, however parsing commit $c ",
923 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
926 foreach my $p (@{$parents{$c}}) {
930 (\@linear_refs, \%parents);
936 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
937 $_repack $_repack_flags $_use_svm_props $_head
938 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
940 use File::Path qw/mkpath/;
941 use File::Copy qw/copy/;
945 # properties that we do not log:
948 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
949 svn:special svn:executable
950 svn:entry:committed-rev
951 svn:entry:last-author
953 svn:entry:committed-date/;
955 # some options are read globally, but can be overridden locally
956 # per [svn-remote "..."] section. Command-line options will *NOT*
957 # override options set in an [svn-remote "..."] section
959 for my $option (qw/follow_parent no_metadata use_svm_props
960 use_svnsync_props/) {
963 my $prop = "-$option";
966 return $self->{$prop} if exists $self->{$prop};
967 my $k = "svn-remote.$self->{repo_id}.$key";
968 eval { command_oneline(qw/config --get/, $k) };
970 $self->{$prop} = ${"Git::SVN::_$option"};
972 my $v = command_oneline(qw/config --bool/,$k);
973 $self->{$prop} = $v eq 'false' ? 0 : 1;
975 return $self->{$prop};
981 END { unlink keys %LOCKFILES if %LOCKFILES }
983 sub resolve_local_globs {
984 my ($url, $fetch, $glob_spec) = @_;
985 return unless defined $glob_spec;
986 my $ref = $glob_spec->{ref};
987 my $path = $glob_spec->{path};
988 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
989 next unless m#^refs/remotes/$ref->{regex}$#;
991 my $pathname = desanitize_refname($path->full_path($p));
992 my $refname = desanitize_refname($ref->full_path($p));
993 if (my $existing = $fetch->{$pathname}) {
994 if ($existing ne $refname) {
995 die "Refspec conflict:\n",
996 "existing: refs/remotes/$existing\n",
997 " globbed: refs/remotes/$refname\n";
999 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1000 $u =~ s!^\Q$url\E(/|$)!! or die
1001 "refs/remotes/$refname: '$url' not found in '$u'\n";
1002 if ($pathname ne $u) {
1003 warn "W: Refspec glob conflict ",
1004 "(ref: refs/remotes/$refname):\n",
1005 "expected path: $pathname\n",
1007 "Continuing ahead with $u\n";
1011 $fetch->{$pathname} = $refname;
1016 sub parse_revision_argument {
1017 my ($base, $head) = @_;
1018 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1019 return ($base, $head);
1021 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1022 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1023 return ($head, $head) if ($::_revision eq 'HEAD');
1024 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1025 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1026 die "revision argument: $::_revision not understood by git-svn\n";
1030 my ($repo_id, $remotes) = @_;
1034 $repo_id = $gs->{repo_id};
1036 $remotes ||= read_all_remotes();
1037 my $remote = $remotes->{$repo_id} or
1038 die "[svn-remote \"$repo_id\"] unknown\n";
1039 my $fetch = $remote->{fetch};
1040 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1042 my $ra = Git::SVN::Ra->new($url);
1043 my $uuid = $ra->get_uuid;
1044 my $head = $ra->get_latest_revnum;
1045 my $base = defined $fetch ? $head : 0;
1047 # read the max revs for wildcard expansion (branches/*, tags/*)
1048 foreach my $t (qw/branches tags/) {
1049 defined $remote->{$t} or next;
1050 push @globs, $remote->{$t};
1051 my $max_rev = eval { tmp_config(qw/--int --get/,
1052 "svn-remote.$repo_id.${t}-maxRev") };
1053 if (defined $max_rev && ($max_rev < $base)) {
1055 } elsif (!defined $max_rev) {
1061 foreach my $p (sort keys %$fetch) {
1062 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1063 my $lr = $gs->rev_db_max;
1065 $base = $lr if ($lr < $base);
1071 ($base, $head) = parse_revision_argument($base, $head);
1072 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1075 sub read_all_remotes {
1077 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1078 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1079 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1080 $local_ref =~ s{^/}{};
1081 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1082 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1083 $r->{$1}->{url} = $2;
1084 } elsif (m!^(.+)\.(branches|tags)=
1085 (.*):refs/remotes/(.+)\s*$/!x) {
1086 my ($p, $g) = ($3, $4);
1087 my $rs = $r->{$1}->{$2} = {
1090 path => Git::SVN::GlobSpec->new($p),
1091 ref => Git::SVN::GlobSpec->new($g) };
1092 if (length($rs->{ref}->{right}) != 0) {
1093 die "The '*' glob character must be the last ",
1094 "character of '$g'\n";
1102 if (defined $_repack) {
1103 $_repack = 1000 if ($_repack <= 0);
1104 $_repack_nr = $_repack;
1105 $_repack_flags ||= '-d';
1109 sub verify_remotes_sanity {
1110 return unless -d $ENV{GIT_DIR};
1112 foreach (command(qw/config -l/)) {
1113 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1115 die "Remote ref refs/remote/$1 is tracked by",
1116 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1117 "Please resolve this ambiguity in ",
1118 "your git configuration file before ",
1126 # we allow more chars than remotes2config.sh...
1127 sub sanitize_remote_name {
1129 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1133 sub find_existing_remote {
1134 my ($url, $remotes) = @_;
1135 return undef if $no_reuse_existing;
1137 foreach my $repo_id (keys %$remotes) {
1138 my $u = $remotes->{$repo_id}->{url} or next;
1140 $existing = $repo_id;
1146 sub init_remote_config {
1147 my ($self, $url, $no_write) = @_;
1148 $url =~ s!/+$!!; # strip trailing slash
1149 my $r = read_all_remotes();
1150 my $existing = find_existing_remote($url, $r);
1152 unless ($no_write) {
1153 print STDERR "Using existing ",
1154 "[svn-remote \"$existing\"]\n";
1156 $self->{repo_id} = $existing;
1157 } elsif ($_minimize_url) {
1158 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1159 $existing = find_existing_remote($min_url, $r);
1161 unless ($no_write) {
1162 print STDERR "Using existing ",
1163 "[svn-remote \"$existing\"]\n";
1165 $self->{repo_id} = $existing;
1167 if ($min_url ne $url) {
1168 unless ($no_write) {
1169 print STDERR "Using higher level of URL: ",
1170 "$url => $min_url\n";
1172 my $old_path = $self->{path};
1173 $self->{path} = $url;
1174 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1175 if (length $old_path) {
1176 $self->{path} .= "/$old_path";
1183 # verify that we aren't overwriting anything:
1185 command_oneline('config', '--get',
1186 "svn-remote.$self->{repo_id}.url")
1188 if ($orig_url && ($orig_url ne $url)) {
1189 die "svn-remote.$self->{repo_id}.url already set: ",
1190 "$orig_url\nwanted to set to: $url\n";
1193 my ($xrepo_id, $xpath) = find_ref($self->refname);
1194 if (defined $xpath) {
1195 die "svn-remote.$xrepo_id.fetch already set to track ",
1196 "$xpath:refs/remotes/", $self->refname, "\n";
1198 unless ($no_write) {
1199 command_noisy('config',
1200 "svn-remote.$self->{repo_id}.url", $url);
1201 $self->{path} =~ s{^/}{};
1202 command_noisy('config', '--add',
1203 "svn-remote.$self->{repo_id}.fetch",
1204 "$self->{path}:".$self->refname);
1206 $self->{url} = $url;
1209 sub find_by_url { # repos_root and, path are optional
1210 my ($class, $full_url, $repos_root, $path) = @_;
1212 return undef unless defined $full_url;
1213 remove_username($full_url);
1214 remove_username($repos_root) if defined $repos_root;
1215 my $remotes = read_all_remotes();
1216 if (defined $full_url && defined $repos_root && !defined $path) {
1218 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1220 foreach my $repo_id (keys %$remotes) {
1221 my $u = $remotes->{$repo_id}->{url} or next;
1222 remove_username($u);
1223 next if defined $repos_root && $repos_root ne $u;
1225 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1226 foreach (qw/branches tags/) {
1227 resolve_local_globs($u, $fetch,
1228 $remotes->{$repo_id}->{$_});
1231 unless (defined $p) {
1233 $p =~ s#^\Q$u\E(?:/|$)## or next;
1235 foreach my $f (keys %$fetch) {
1237 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1244 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1245 my $self = _new($class, $repo_id, $ref_id, $path);
1247 $self->init_remote_config($url, $no_write);
1254 foreach (command(qw/config -l/)) {
1255 next unless m!^svn-remote\.(.+)\.fetch=
1256 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1257 my ($repo_id, $path, $ref) = ($1, $2, $3);
1258 if ($ref eq $ref_id) {
1259 $path = '' if ($path =~ m#^\./?#);
1260 return ($repo_id, $path);
1263 (undef, undef, undef);
1267 my ($class, $ref_id, $repo_id, $path) = @_;
1268 if (defined $ref_id && !defined $repo_id && !defined $path) {
1269 ($repo_id, $path) = find_ref($ref_id);
1270 if (!defined $repo_id) {
1271 die "Could not find a \"svn-remote.*.fetch\" key ",
1272 "in the repository configuration matching: ",
1273 "refs/remotes/$ref_id\n";
1276 my $self = _new($class, $repo_id, $ref_id, $path);
1277 if (!defined $self->{path} || !length $self->{path}) {
1278 my $fetch = command_oneline('config', '--get',
1279 "svn-remote.$repo_id.fetch",
1280 ":refs/remotes/$ref_id\$") or
1281 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1282 "\":refs/remotes/$ref_id\$\" in config\n";
1283 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1285 $self->{url} = command_oneline('config', '--get',
1286 "svn-remote.$repo_id.url") or
1287 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1293 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1295 # It cannot end with a slash /, we'll throw up on this because
1296 # SVN can't have directories with a slash in their name, either:
1297 if ($refname =~ m{/$}) {
1298 die "ref: '$refname' ends with a trailing slash, this is ",
1299 "not permitted by git nor Subversion\n";
1302 # It cannot have ASCII control character space, tilde ~, caret ^,
1303 # colon :, question-mark ?, asterisk *, space, or open bracket [
1306 # Additionally, % must be escaped because it is used for escaping
1307 # and we want our escaped refname to be reversible
1308 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1310 # no slash-separated component can begin with a dot .
1312 $refname =~ s{/\.}{/%2E}g;
1314 # It cannot have two consecutive dots .. anywhere
1316 $refname =~ s{\.\.}{%2E%2E}g;
1321 sub desanitize_refname {
1323 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1329 return $self->{svm}->{uuid} if $self->svm;
1331 unless ($self->{svm}) {
1332 die "SVM UUID not cached, and reading remotely failed\n";
1334 $self->{svm}->{uuid};
1339 return $self->{svm} if $self->{svm};
1341 # see if we have it in our config, first:
1343 my $section = "svn-remote.$self->{repo_id}";
1345 source => tmp_config('--get', "$section.svm-source"),
1346 uuid => tmp_config('--get', "$section.svm-uuid"),
1347 replace => tmp_config('--get', "$section.svm-replace"),
1350 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1351 $self->{svm} = $svm;
1357 my ($self, $ra) = @_;
1358 return $ra if $self->svm;
1360 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1361 "(svm:source, svm:uuid) ",
1362 "from the following URLs:\n" );
1363 sub read_svm_props {
1364 my ($self, $ra, $path, $r) = @_;
1365 my $props = ($ra->get_dir($path, $r))[2];
1366 my $src = $props->{'svm:source'};
1367 my $uuid = $props->{'svm:uuid'};
1368 return undef if (!$src || !$uuid);
1372 $uuid =~ m{^[0-9a-f\-]{30,}$}
1373 or die "doesn't look right - svm:uuid is '$uuid'\n";
1375 # the '!' is used to mark the repos_root!/relative/path
1376 $src =~ s{/?!/?}{/};
1377 $src =~ s{/+$}{}; # no trailing slashes please
1378 # username is of no interest
1379 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1381 my $replace = $ra->{url};
1382 $replace .= "/$path" if length $path;
1384 my $section = "svn-remote.$self->{repo_id}";
1385 tmp_config("$section.svm-source", $src);
1386 tmp_config("$section.svm-replace", $replace);
1387 tmp_config("$section.svm-uuid", $uuid);
1395 my $r = $ra->get_latest_revnum;
1396 my $path = $self->{path};
1398 while (length $path) {
1399 unless ($tried{"$self->{url}/$path"}) {
1400 return $ra if $self->read_svm_props($ra, $path, $r);
1401 $tried{"$self->{url}/$path"} = 1;
1403 $path =~ s#/?[^/]+$##;
1405 die "Path: '$path' should be ''\n" if $path ne '';
1406 return $ra if $self->read_svm_props($ra, $path, $r);
1407 $tried{"$self->{url}/$path"} = 1;
1409 if ($ra->{repos_root} eq $self->{url}) {
1410 die @err, (map { " $_\n" } keys %tried), "\n";
1413 # nope, make sure we're connected to the repository root:
1416 $path = $ra->{svn_path};
1417 $ra = Git::SVN::Ra->new($ra->{repos_root});
1418 while (length $path) {
1419 unless ($tried{"$ra->{url}/$path"}) {
1420 $ok = $self->read_svm_props($ra, $path, $r);
1422 $tried{"$ra->{url}/$path"} = 1;
1424 $path =~ s#/?[^/]+$##;
1426 die "Path: '$path' should be ''\n" if $path ne '';
1427 $ok ||= $self->read_svm_props($ra, $path, $r);
1428 $tried{"$ra->{url}/$path"} = 1;
1430 die @err, (map { " $_\n" } keys %tried), "\n";
1432 Git::SVN::Ra->new($self->{url});
1437 return $self->{svnsync} if $self->{svnsync};
1439 if ($self->no_metadata) {
1440 die "Can't have both 'noMetadata' and ",
1441 "'useSvnsyncProps' options set!\n";
1443 if ($self->rewrite_root) {
1444 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1449 # see if we have it in our config, first:
1451 my $section = "svn-remote.$self->{repo_id}";
1453 url => tmp_config('--get', "$section.svnsync-url"),
1454 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1457 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1458 return $self->{svnsync} = $svnsync;
1461 my $err = "useSvnsyncProps set, but failed to read " .
1462 "svnsync property: svn:sync-from-";
1463 my $rp = $self->ra->rev_proplist(0);
1465 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1466 $url =~ m{^[a-z\+]+://} or
1467 die "doesn't look right - svn:sync-from-url is '$url'\n";
1469 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1470 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1471 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1473 my $section = "svn-remote.$self->{repo_id}";
1474 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1475 tmp_config('--add', "$section.svnsync-url", $url);
1476 return $self->{svnsync} = { url => $url, uuid => $uuid };
1479 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1480 # remote lookup (useful for 'git svn log').
1483 unless ($self->{ra_uuid}) {
1484 my $key = "svn-remote.$self->{repo_id}.uuid";
1485 my $uuid = eval { tmp_config('--get', $key) };
1486 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1487 $self->{ra_uuid} = $uuid;
1489 die "ra_uuid called without URL\n" unless $self->{url};
1490 $self->{ra_uuid} = $self->ra->get_uuid;
1491 tmp_config('--add', $key, $self->{ra_uuid});
1499 my $ra = Git::SVN::Ra->new($self->{url});
1500 if ($self->use_svm_props && !$self->{svm}) {
1501 if ($self->no_metadata) {
1502 die "Can't have both 'noMetadata' and ",
1503 "'useSvmProps' options set!\n";
1504 } elsif ($self->use_svnsync_props) {
1505 die "Can't have both 'useSvnsyncProps' and ",
1506 "'useSvmProps' options set!\n";
1508 $ra = $self->_set_svm_vars($ra);
1509 $self->{-want_revprops} = 1;
1516 my $repos_root = $self->ra->{repos_root};
1517 return $self->{path} if ($self->{url} eq $repos_root);
1518 my $url = $self->{url} .
1519 (length $self->{path} ? "/$self->{path}" : $self->{path});
1520 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1524 sub traverse_ignore {
1525 my ($self, $fh, $path, $r) = @_;
1528 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1530 $p =~ s#^\Q$self->{path}\E(/|$)##;
1531 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1532 if (my $s = $props->{'svn:ignore'}) {
1533 $s =~ s/[\r\n]+/\n/g;
1535 if (length $p == 0) {
1539 $s =~ s#\n#\n/$p/#g;
1540 print $fh "/$p/$s\n";
1543 foreach (sort keys %$dirent) {
1544 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1545 $self->traverse_ignore($fh, "$path/$_", $r);
1549 sub last_rev { ($_[0]->last_rev_commit)[0] }
1550 sub last_commit { ($_[0]->last_rev_commit)[1] }
1552 # returns the newest SVN revision number and newest commit SHA1
1553 sub last_rev_commit {
1555 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1556 return ($self->{last_rev}, $self->{last_commit});
1558 my $c = ::verify_ref($self->refname.'^0');
1559 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1560 my $rev = (::cmt_metadata($c))[1];
1562 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1566 my $db_path = $self->db_path;
1567 unless (-e $db_path) {
1568 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1569 return (undef, undef);
1571 my $offset = -41; # from tail
1573 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1574 sysseek($fh, $offset, 2); # don't care for errors
1575 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1577 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1579 sysseek($fh, $offset, 2); # don't care for errors
1580 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1583 if ($c && $c ne $rl) {
1584 die "$db_path and ", $self->refname,
1585 " inconsistent!:\n$c != $rl\n";
1587 my $rev = sysseek($fh, 0, 1) or croak $!;
1588 $rev = ($rev - 41) / 41;
1589 close $fh or croak $!;
1590 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1594 sub get_fetch_range {
1595 my ($self, $min, $max) = @_;
1596 $max ||= $self->ra->get_latest_revnum;
1597 $min ||= $self->rev_db_max;
1603 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1604 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1605 if (! -f $config && -f $old_def_config) {
1606 rename $old_def_config, $config or
1607 die "Failed rename $old_def_config => $config: $!\n";
1609 my $old_config = $ENV{GIT_CONFIG};
1610 $ENV{GIT_CONFIG} = $config;
1613 unless (-f $config) {
1615 open my $fh, '>', $config or
1616 die "Can't open $config: $!\n";
1617 print $fh "; This file is used internally by ",
1619 "Couldn't write to $config: $!\n";
1620 print $fh "; You should not have to edit it\n" or
1621 die "Couldn't write to $config: $!\n";
1622 close $fh or die "Couldn't close $config: $!\n";
1624 command('config', @args);
1627 if (defined $old_config) {
1628 $ENV{GIT_CONFIG} = $old_config;
1630 delete $ENV{GIT_CONFIG};
1633 wantarray ? @ret : $ret[0];
1637 my ($self, $sub) = @_;
1638 my $old_index = $ENV{GIT_INDEX_FILE};
1639 $ENV{GIT_INDEX_FILE} = $self->{index};
1642 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1643 mkpath([$dir]) unless -d $dir;
1647 if (defined $old_index) {
1648 $ENV{GIT_INDEX_FILE} = $old_index;
1650 delete $ENV{GIT_INDEX_FILE};
1653 wantarray ? @ret : $ret[0];
1656 sub assert_index_clean {
1657 my ($self, $treeish) = @_;
1659 $self->tmp_index_do(sub {
1660 command_noisy('read-tree', $treeish) unless -e $self->{index};
1661 my $x = command_oneline('write-tree');
1662 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1663 /^tree ($::sha1)/mo);
1666 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1667 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1668 command_noisy('read-tree', $treeish);
1669 $x = command_oneline('write-tree');
1671 ::fatal "trees ($treeish) $y != $x\n",
1672 "Something is seriously wrong...\n";
1677 sub get_commit_parents {
1678 my ($self, $log_entry) = @_;
1679 my (%seen, @ret, @tmp);
1680 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1681 if (my $ip = $self->{inject_parents}) {
1682 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1686 if (my $cur = ::verify_ref($self->refname.'^0')) {
1689 if (my $ipd = $self->{inject_parents_dcommit}) {
1690 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1691 push @tmp, @$commit;
1694 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1695 while (my $p = shift @tmp) {
1699 # MAXPARENT is defined to 16 in commit-tree.c:
1703 die "r$log_entry->{revision}: No room for parents:\n\t",
1704 join("\n\t", @tmp), "\n";
1711 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1712 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1713 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1716 if ($rwr !~ m#^[a-z\+]+://#) {
1717 die "$rwr is not a valid URL (key: $k)\n";
1720 $self->{-rewrite_root} = $rwr;
1725 ($self->rewrite_root || $self->{url}) .
1726 (length $self->{path} ? '/' . $self->{path} : '');
1731 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1735 my ($self, $log_entry) = @_;
1736 my $lr = $self->last_rev;
1737 if (defined $lr && $lr >= $log_entry->{revision}) {
1738 die "Last fetched revision of ", $self->refname,
1739 " was r$lr, but we are about to fetch: ",
1740 "r$log_entry->{revision}!\n";
1742 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1743 croak "$log_entry->{revision} = $c already exists! ",
1744 "Why are we refetching it?\n";
1746 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1747 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1748 $log_entry->{email};
1749 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1751 my $tree = $log_entry->{tree};
1752 if (!defined $tree) {
1753 $tree = $self->tmp_index_do(sub {
1754 command_oneline('write-tree') });
1756 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1758 my @exec = ('git-commit-tree', $tree);
1759 foreach ($self->get_commit_parents($log_entry)) {
1760 push @exec, '-p', $_;
1762 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1764 print $msg_fh $log_entry->{log} or croak $!;
1765 unless ($self->no_metadata) {
1766 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1769 $msg_fh->flush == 0 or croak $!;
1770 close $msg_fh or croak $!;
1771 chomp(my $commit = do { local $/; <$out_fh> });
1772 close $out_fh or croak $!;
1775 if ($commit !~ /^$::sha1$/o) {
1776 die "Failed to commit, invalid sha1: $commit\n";
1779 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1781 $self->{last_rev} = $log_entry->{revision};
1782 $self->{last_commit} = $commit;
1783 print "r$log_entry->{revision}";
1784 if (defined $log_entry->{svm_revision}) {
1785 print " (\@$log_entry->{svm_revision})";
1786 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1787 0, $self->svm_uuid);
1789 print " = $commit ($self->{ref_id})\n";
1790 if (defined $_repack && (--$_repack_nr == 0)) {
1791 $_repack_nr = $_repack;
1792 # repack doesn't use any arguments with spaces in them, does it?
1793 print "Running git repack $_repack_flags ...\n";
1794 command_noisy('repack', split(/\s+/, $_repack_flags));
1795 print "Done repacking\n";
1801 my ($self, $paths, $r) = @_;
1802 return 1 if $self->{path} eq '';
1803 if (my $path = $paths->{"/$self->{path}"}) {
1804 return ($path->{action} eq 'D') ? 0 : 1;
1806 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1807 if (grep /$self->{path_regex}/, keys %$paths) {
1811 foreach (split m#/#, $self->{path}) {
1813 next unless ($paths->{$c} &&
1814 ($paths->{$c}->{action} =~ /^[AR]$/));
1815 if ($self->ra->check_path($self->{path}, $r) ==
1823 sub find_parent_branch {
1824 my ($self, $paths, $rev) = @_;
1825 return undef unless $self->follow_parent;
1826 unless (defined $paths) {
1827 my $err_handler = $SVN::Error::handler;
1828 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1829 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1831 Git::SVN::Ra::dup_changed_paths($_[0]) });
1832 $SVN::Error::handler = $err_handler;
1834 return undef unless defined $paths;
1836 # look for a parent from another branch:
1837 my @b_path_components = split m#/#, $self->rel_path;
1838 my @a_path_components;
1840 while (@b_path_components) {
1841 $i = $paths->{'/'.join('/', @b_path_components)};
1842 last if $i && defined $i->{copyfrom_path};
1843 unshift(@a_path_components, pop(@b_path_components));
1845 return undef unless defined $i && defined $i->{copyfrom_path};
1846 my $branch_from = $i->{copyfrom_path};
1847 if (@a_path_components) {
1848 print STDERR "branch_from: $branch_from => ";
1849 $branch_from .= '/'.join('/', @a_path_components);
1850 print STDERR $branch_from, "\n";
1852 my $r = $i->{copyfrom_rev};
1853 my $repos_root = $self->ra->{repos_root};
1854 my $url = $self->ra->{url};
1855 my $new_url = $repos_root . $branch_from;
1856 print STDERR "Found possible branch point: ",
1857 "$new_url => ", $self->full_url, ", $r\n";
1858 $branch_from =~ s#^/##;
1859 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1861 my $ref_id = $self->{ref_id};
1862 $ref_id =~ s/\@\d+$//;
1864 # just grow a tail if we're not unique enough :x
1865 $ref_id .= '-' while find_ref($ref_id);
1866 print STDERR "Initializing parent: $ref_id\n";
1867 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1869 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1870 if (!defined $r0 || !defined $parent) {
1871 my ($base, $head) = parse_revision_argument(0, $r);
1873 $gs->fetch($base, $r);
1875 ($r0, $parent) = $gs->last_rev_commit;
1877 if (defined $r0 && defined $parent) {
1878 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1880 if ($self->ra->can_do_switch) {
1881 $self->assert_index_clean($parent);
1882 print STDERR "Following parent with do_switch\n";
1883 # do_switch works with svn/trunk >= r22312, but that
1884 # is not included with SVN 1.4.3 (the latest version
1885 # at the moment), so we can't rely on it
1886 $self->{last_commit} = $parent;
1887 $ed = SVN::Git::Fetcher->new($self);
1888 $gs->ra->gs_do_switch($r0, $rev, $gs,
1889 $self->full_url, $ed)
1890 or die "SVN connection failed somewhere...\n";
1892 print STDERR "Following parent with do_update\n";
1893 $ed = SVN::Git::Fetcher->new($self);
1894 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1895 or die "SVN connection failed somewhere...\n";
1897 print STDERR "Successfully followed parent\n";
1898 return $self->make_log_entry($rev, [$parent], $ed);
1904 my ($self, $paths, $rev) = @_;
1906 my ($last_rev, @parents);
1907 if (my $lc = $self->last_commit) {
1908 # we can have a branch that was deleted, then re-added
1909 # under the same name but copied from another path, in
1910 # which case we'll have multiple parents (we don't
1911 # want to break the original ref, nor lose copypath info):
1912 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1913 push @{$log_entry->{parents}}, $lc;
1916 $ed = SVN::Git::Fetcher->new($self);
1917 $last_rev = $self->{last_rev};
1922 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1925 $ed = SVN::Git::Fetcher->new($self);
1927 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1928 die "SVN connection failed somewhere...\n";
1930 $self->make_log_entry($rev, \@parents, $ed);
1934 my ($self, $ed) = @_;
1936 my $h = $ed->{empty};
1937 foreach (sort keys %$h) {
1938 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1939 push @out, " $act: " . uri_encode($_);
1940 warn "W: $act: $_\n";
1942 foreach my $t (qw/dir_prop file_prop/) {
1943 $h = $ed->{$t} or next;
1944 foreach my $path (sort keys %$h) {
1945 my $ppath = $path eq '' ? '.' : $path;
1946 foreach my $prop (sort keys %{$h->{$path}}) {
1947 next if $SKIP_PROP{$prop};
1948 my $v = $h->{$path}->{$prop};
1949 my $t_ppath_prop = "$t: " .
1950 uri_encode($ppath) . ' ' .
1953 push @out, " +$t_ppath_prop " .
1956 push @out, " -$t_ppath_prop";
1961 foreach my $t (qw/absent_file absent_directory/) {
1962 $h = $ed->{$t} or next;
1963 foreach my $parent (sort keys %$h) {
1964 foreach my $path (sort @{$h->{$parent}}) {
1965 push @out, " $t: " .
1966 uri_encode("$parent/$path");
1967 warn "W: $t: $parent/$path ",
1968 "Insufficient permissions?\n";
1975 sub parse_svn_date {
1976 my $date = shift || return '+0000 1970-01-01 00:00:00';
1977 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1978 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1979 croak "Unable to parse date: $date\n";
1980 "+0000 $Y-$m-$d $H:$M:$S";
1985 if (!defined $author || length $author == 0) {
1986 $author = '(no author)';
1988 if (defined $::_authors && ! defined $::users{$author}) {
1989 die "Author: $author not defined in $::_authors file\n";
1994 sub make_log_entry {
1995 my ($self, $rev, $parents, $ed) = @_;
1996 my $untracked = $self->get_untracked($ed);
1998 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1999 print $un "r$rev\n" or croak $!;
2000 print $un $_, "\n" foreach @$untracked;
2001 my %log_entry = ( parents => $parents || [], revision => $rev,
2005 my $logged = delete $self->{logged_rev_props};
2006 if (!$logged || $self->{-want_revprops}) {
2007 my $rp = $self->ra->rev_proplist($rev);
2008 foreach (sort keys %$rp) {
2010 if (/^svn:(author|date|log)$/) {
2011 $log_entry{$1} = $v;
2012 } elsif ($_ eq 'svm:headrev') {
2015 print $un " rev_prop: ", uri_encode($_), ' ',
2016 uri_encode($v), "\n";
2020 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2022 close $un or croak $!;
2024 $log_entry{date} = parse_svn_date($log_entry{date});
2025 $log_entry{log} .= "\n";
2026 my $author = $log_entry{author} = check_author($log_entry{author});
2027 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2029 if (defined $headrev && $self->use_svm_props) {
2030 if ($self->rewrite_root) {
2031 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2034 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2035 # we don't want "SVM: initializing mirror for junk" ...
2036 return undef if $r == 0;
2037 my $svm = $self->svm;
2038 if ($uuid ne $svm->{uuid}) {
2039 die "UUID mismatch on SVM path:\n",
2040 "expected: $svm->{uuid}\n",
2043 my $full_url = $self->full_url;
2044 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2045 die "Failed to replace '$svm->{replace}' with ",
2046 "'$svm->{source}' in $full_url\n";
2047 # throw away username for storing in records
2048 remove_username($full_url);
2049 $log_entry{metadata} = "$full_url\@$r $uuid";
2050 $log_entry{svm_revision} = $r;
2051 $email ||= "$author\@$uuid"
2052 } elsif ($self->use_svnsync_props) {
2053 my $full_url = $self->svnsync->{url};
2054 $full_url .= "/$self->{path}" if length $self->{path};
2055 remove_username($full_url);
2056 my $uuid = $self->svnsync->{uuid};
2057 $log_entry{metadata} = "$full_url\@$rev $uuid";
2058 $email ||= "$author\@$uuid"
2060 my $url = $self->metadata_url;
2061 remove_username($url);
2062 $log_entry{metadata} = "$url\@$rev " .
2063 $self->ra->get_uuid;
2064 $email ||= "$author\@" . $self->ra->get_uuid;
2066 $log_entry{name} = $name;
2067 $log_entry{email} = $email;
2072 my ($self, $min_rev, $max_rev, @parents) = @_;
2073 my ($last_rev, $last_commit) = $self->last_rev_commit;
2074 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2075 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2079 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2080 $self->{inject_parents} = { $rev => $tree };
2081 $self->fetch(undef, undef);
2085 my ($self, $tree) = (shift, shift);
2086 my $log_entry = ::get_commit_entry($tree);
2087 unless ($self->{last_rev}) {
2088 fatal("Must have an existing revision to commit\n");
2090 my %ed_opts = ( r => $self->{last_rev},
2091 log => $log_entry->{log},
2093 tree_a => $self->{last_commit},
2096 $self->set_tree_cb($log_entry, $tree, @_) },
2097 svn_path => $self->{path} );
2098 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2099 print "No changes\nr$self->{last_rev} = $tree\n";
2105 my $db_path = $self->db_path;
2106 return if (-e $db_path && ! -z $db_path);
2107 return unless ::verify_ref($self->refname.'^0');
2108 if (-f $self->{db_root}) {
2109 rename $self->{db_root}, $db_path or die
2110 "rename $self->{db_root} => $db_path failed: $!\n";
2111 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2112 symlink $base, $self->{db_root} or die
2113 "symlink $base => $self->{db_root} failed: $!\n";
2116 print "Rebuilding $db_path ...\n";
2117 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2119 my $full_url = $self->full_url;
2120 remove_username($full_url);
2124 if ( m{^commit ($::sha1)$} ) {
2128 next unless s{^\s*(git-svn-id:)}{$1};
2129 my ($url, $rev, $uuid) = ::extract_metadata($_);
2130 remove_username($url);
2132 # ignore merges (from set-tree)
2133 next if (!defined $rev || !$uuid);
2135 # if we merged or otherwise started elsewhere, this is
2136 # how we break out of it
2137 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2138 ($full_url && $url && ($url ne $full_url))) {
2142 $svn_uuid ||= $uuid;
2144 $self->rev_db_set($rev, $c);
2145 print "r$rev = $c\n";
2147 command_close_pipe($log, $ctx);
2148 print "Done rebuilding $db_path\n";
2152 # Tie::File seems to be prone to offset errors if revisions get sparse,
2153 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2154 # one of my favorite modules is out :< Next up would be one of the DBM
2155 # modules, but I'm not sure which is most portable... So I'll just
2156 # go with something that's plain-text, but still capable of
2157 # being randomly accessed. So here's my ultra-simple fixed-width
2158 # database. All records are 40 characters + "\n", so it's easy to seek
2159 # to a revision: (41 * rev) is the byte offset.
2160 # A record of 40 0s denotes an empty revision.
2161 # And yes, it's still pretty fast (faster than Tie::File).
2162 # These files are disposable unless noMetadata or useSvmProps is set
2165 my ($fh, $rev, $commit) = @_;
2166 my $offset = $rev * 41;
2167 # assume that append is the common case:
2168 seek $fh, 0, 2 or croak $!;
2170 if ($pos < $offset) {
2171 for (1 .. (($offset - $pos) / 41)) {
2172 print $fh (('0' x 40),"\n") or croak $!;
2175 seek $fh, $offset, 0 or croak $!;
2176 print $fh $commit,"\n" or croak $!;
2182 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2183 mkpath([$dir]) unless -d $dir;
2184 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2185 close $fh or die "Couldn't close (create) $path: $!\n";
2190 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2191 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2192 my $db = $self->db_path($uuid);
2193 my $db_lock = "$db.lock";
2196 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2197 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2201 $LOCKFILES{$db_lock} = 1;
2203 # both of these options make our .rev_db file very, very important
2204 # and we can't afford to lose it because rebuild() won't work
2205 if ($self->use_svm_props || $self->no_metadata) {
2207 copy($db, $db_lock) or die "rev_db_set(@_): ",
2209 "$db => $db_lock ($!)\n";
2211 rename $db, $db_lock or die "rev_db_set(@_): ",
2212 "Failed to rename: ",
2213 "$db => $db_lock ($!)\n";
2215 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2216 _rev_db_set($fh, $rev, $commit);
2218 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2219 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2221 close $fh or croak $!;
2224 command_noisy('update-ref', '-m', "r$rev",
2225 $self->refname, $commit);
2227 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2228 "$db_lock => $db ($!)\n";
2229 delete $LOCKFILES{$db_lock};
2231 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2232 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2233 kill $sig, $$ if defined $sig;
2240 my $db_path = $self->db_path;
2241 my @stat = stat $db_path or return 0;
2242 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2243 my $max = $stat[7] / 41;
2244 (($max > 0) ? $max - 1 : 0);
2248 my ($self, $rev, $uuid) = @_;
2250 my $offset = $rev * 41;
2251 my $db_path = $self->db_path($uuid);
2252 return undef unless -e $db_path;
2253 open my $fh, '<', $db_path or croak $!;
2254 if (sysseek($fh, $offset, 0) == $offset) {
2255 my $read = sysread($fh, $ret, 40);
2256 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2258 close $fh or croak $!;
2262 sub find_rev_before {
2263 my ($self, $rev, $eq_ok) = @_;
2264 --$rev unless $eq_ok;
2266 if (my $c = $self->rev_db_get($rev)) {
2271 return (undef, undef);
2275 my ($class, $repo_id, $ref_id, $path) = @_;
2276 unless (defined $repo_id && length $repo_id) {
2277 $repo_id = $Git::SVN::default_repo_id;
2279 unless (defined $ref_id && length $ref_id) {
2280 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2282 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2283 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2284 $_[3] = $path = '' unless (defined $path);
2285 mkpath(["$ENV{GIT_DIR}/svn"]);
2287 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2288 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2289 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2293 my ($self, $uuid) = @_;
2294 $uuid ||= $self->ra_uuid;
2295 "$self->{db_root}.$uuid";
2300 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2304 sub remove_username {
2305 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2308 package Git::SVN::Prompt;
2312 use vars qw/$_no_auth_cache $_username/;
2315 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2316 $may_save = undef if $_no_auth_cache;
2317 $default_username = $_username if defined $_username;
2318 if (defined $default_username && length $default_username) {
2319 if (defined $realm && length $realm) {
2320 print STDERR "Authentication realm: $realm\n";
2323 $cred->username($default_username);
2325 username($cred, $realm, $may_save, $pool);
2327 $cred->password(_read_password("Password for '" .
2328 $cred->username . "': ", $realm));
2329 $cred->may_save($may_save);
2330 $SVN::_Core::SVN_NO_ERROR;
2333 sub ssl_server_trust {
2334 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2335 $may_save = undef if $_no_auth_cache;
2336 print STDERR "Error validating server certificate for '$realm':\n";
2337 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2338 print STDERR " - The certificate is not issued by a trusted ",
2339 "authority. Use the\n",
2340 " fingerprint to validate the certificate manually!\n";
2342 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2343 print STDERR " - The certificate hostname does not match.\n";
2345 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2346 print STDERR " - The certificate is not yet valid.\n";
2348 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2349 print STDERR " - The certificate has expired.\n";
2351 if ($failures & $SVN::Auth::SSL::OTHER) {
2352 print STDERR " - The certificate has an unknown error.\n";
2355 "Certificate information:\n".
2356 " - Hostname: %s\n".
2357 " - Valid: from %s until %s\n".
2359 " - Fingerprint: %s\n",
2360 map $cert_info->$_, qw(hostname valid_from valid_until
2361 issuer_dname fingerprint);
2364 print STDERR $may_save ?
2365 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2366 "(R)eject or accept (t)emporarily? ";
2368 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2369 if ($choice =~ /^t$/i) {
2370 $cred->may_save(undef);
2371 } elsif ($choice =~ /^r$/i) {
2373 } elsif ($may_save && $choice =~ /^p$/i) {
2374 $cred->may_save($may_save);
2378 $cred->accepted_failures($failures);
2379 $SVN::_Core::SVN_NO_ERROR;
2382 sub ssl_client_cert {
2383 my ($cred, $realm, $may_save, $pool) = @_;
2384 $may_save = undef if $_no_auth_cache;
2385 print STDERR "Client certificate filename: ";
2387 chomp(my $filename = <STDIN>);
2388 $cred->cert_file($filename);
2389 $cred->may_save($may_save);
2390 $SVN::_Core::SVN_NO_ERROR;
2393 sub ssl_client_cert_pw {
2394 my ($cred, $realm, $may_save, $pool) = @_;
2395 $may_save = undef if $_no_auth_cache;
2396 $cred->password(_read_password("Password: ", $realm));
2397 $cred->may_save($may_save);
2398 $SVN::_Core::SVN_NO_ERROR;
2402 my ($cred, $realm, $may_save, $pool) = @_;
2403 $may_save = undef if $_no_auth_cache;
2404 if (defined $realm && length $realm) {
2405 print STDERR "Authentication realm: $realm\n";
2408 if (defined $_username) {
2409 $username = $_username;
2411 print STDERR "Username: ";
2413 chomp($username = <STDIN>);
2415 $cred->username($username);
2416 $cred->may_save($may_save);
2417 $SVN::_Core::SVN_NO_ERROR;
2420 sub _read_password {
2421 my ($prompt, $realm) = @_;
2422 print STDERR $prompt;
2424 require Term::ReadKey;
2425 Term::ReadKey::ReadMode('noecho');
2427 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2428 last if $key =~ /[\012\015]/; # \n\r
2431 Term::ReadKey::ReadMode('restore');
2440 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2441 $SVN::Node::dir.$SVN::Node::unknown.
2442 $SVN::Node::none.$SVN::Node::file.
2443 $SVN::Node::dir.$SVN::Node::unknown.
2444 $SVN::Auth::SSL::CNMISMATCH.
2445 $SVN::Auth::SSL::NOTYETVALID.
2446 $SVN::Auth::SSL::EXPIRED.
2447 $SVN::Auth::SSL::UNKNOWNCA.
2448 $SVN::Auth::SSL::OTHER;
2451 package SVN::Git::Fetcher;
2459 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2461 my ($class, $git_svn) = @_;
2462 my $self = SVN::Delta::Editor->new;
2463 bless $self, $class;
2464 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2465 $self->{empty} = {};
2466 $self->{dir_prop} = {};
2467 $self->{file_prop} = {};
2468 $self->{absent_dir} = {};
2469 $self->{absent_file} = {};
2470 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2474 sub set_path_strip {
2475 my ($self, $path) = @_;
2476 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2483 sub open_directory {
2484 my ($self, $path, $pb, $rev) = @_;
2489 my ($self, $path) = @_;
2490 if ($self->{path_strip}) {
2491 $path =~ s!$self->{path_strip}!! or
2492 die "Failed to strip path '$path' ($self->{path_strip})\n";
2498 my ($self, $path, $rev, $pb) = @_;
2500 my $gpath = $self->git_path($path);
2501 return undef if ($gpath eq '');
2503 # remove entire directories.
2504 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2505 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2507 $self->{c}, '--', $gpath);
2511 $self->{gii}->remove($_);
2512 print "\tD\t$_\n" unless $::_q;
2514 print "\tD\t$gpath/\n" unless $::_q;
2515 command_close_pipe($ls, $ctx);
2516 $self->{empty}->{$path} = 0
2518 $self->{gii}->remove($gpath);
2519 print "\tD\t$gpath\n" unless $::_q;
2525 my ($self, $path, $pb, $rev) = @_;
2526 my $gpath = $self->git_path($path);
2527 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2528 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2529 unless (defined $mode && defined $blob) {
2530 die "$path was not found in commit $self->{c} (r$rev)\n";
2532 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2533 pool => SVN::Pool->new, action => 'M' };
2537 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2538 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2539 delete $self->{empty}->{$dir};
2540 { path => $path, mode_a => 100644, mode_b => 100644,
2541 pool => SVN::Pool->new, action => 'A' };
2545 my ($self, $path, $cp_path, $cp_rev) = @_;
2546 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2547 delete $self->{empty}->{$dir};
2548 $self->{empty}->{$path} = 1;
2552 sub change_dir_prop {
2553 my ($self, $db, $prop, $value) = @_;
2554 $self->{dir_prop}->{$db->{path}} ||= {};
2555 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2559 sub absent_directory {
2560 my ($self, $path, $pb) = @_;
2561 $self->{absent_dir}->{$pb->{path}} ||= [];
2562 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2567 my ($self, $path, $pb) = @_;
2568 $self->{absent_file}->{$pb->{path}} ||= [];
2569 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2573 sub change_file_prop {
2574 my ($self, $fb, $prop, $value) = @_;
2575 if ($prop eq 'svn:executable') {
2576 if ($fb->{mode_b} != 120000) {
2577 $fb->{mode_b} = defined $value ? 100755 : 100644;
2579 } elsif ($prop eq 'svn:special') {
2580 $fb->{mode_b} = defined $value ? 120000 : 100644;
2582 $self->{file_prop}->{$fb->{path}} ||= {};
2583 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2588 sub apply_textdelta {
2589 my ($self, $fb, $exp) = @_;
2590 my $fh = IO::File->new_tmpfile;
2592 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2593 # (but $base does not,) so dup() it for reading in close_file
2594 open my $dup, '<&', $fh or croak $!;
2595 my $base = IO::File->new_tmpfile;
2596 $base->autoflush(1);
2598 defined (my $pid = fork) or croak $!;
2600 open STDOUT, '>&', $base or croak $!;
2601 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2602 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2608 seek $base, 0, 0 or croak $!;
2609 my $md5 = Digest::MD5->new;
2610 $md5->addfile($base);
2611 my $got = $md5->hexdigest;
2612 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2614 " got: $got\n" if ($got ne $exp);
2617 seek $base, 0, 0 or croak $!;
2619 $fb->{base} = $base;
2620 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2624 my ($self, $fb, $exp) = @_;
2626 my $path = $self->git_path($fb->{path});
2627 if (my $fh = $fb->{fh}) {
2629 seek($fh, 0, 0) or croak $!;
2630 my $md5 = Digest::MD5->new;
2632 my $got = $md5->hexdigest;
2634 die "Checksum mismatch: $path\n",
2635 "expected: $exp\n got: $got\n";
2638 sysseek($fh, 0, 0) or croak $!;
2639 if ($fb->{mode_b} == 120000) {
2640 sysread($fh, my $buf, 5) == 5 or croak $!;
2641 $buf eq 'link ' or die "$path has mode 120000",
2642 "but is not a link\n";
2644 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2646 open STDIN, '<&', $fh or croak $!;
2647 exec qw/git-hash-object -w --stdin/ or croak $!;
2649 chomp($hash = do { local $/; <$out> });
2650 close $out or croak $!;
2651 close $fh or croak $!;
2652 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2653 close $fb->{base} or croak $!;
2655 $hash = $fb->{blob} or die "no blob information\n";
2658 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2659 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2665 $self->{nr} = $self->{gii}->{nr};
2666 delete $self->{gii};
2667 $self->SUPER::abort_edit(@_);
2672 $self->{git_commit_ok} = 1;
2673 $self->{nr} = $self->{gii}->{nr};
2674 delete $self->{gii};
2675 $self->SUPER::close_edit(@_);
2678 package SVN::Git::Editor;
2679 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2687 my ($class, $opts) = @_;
2688 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2689 die "$_ required!\n" unless (defined $opts->{$_});
2692 my $pool = SVN::Pool->new;
2693 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2694 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2697 # $opts->{ra} functions should not be used after this:
2698 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2699 $opts->{editor_cb}, $pool);
2700 my $self = SVN::Delta::Editor->new(@ce, $pool);
2701 bless $self, $class;
2702 foreach (qw/svn_path r tree_a tree_b/) {
2703 $self->{$_} = $opts->{$_};
2705 $self->{url} = $opts->{ra}->{url};
2706 $self->{mods} = $mods;
2707 $self->{types} = $types;
2708 $self->{pool} = $pool;
2709 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2711 $self->{path_prefix} = length $self->{svn_path} ?
2712 "$self->{svn_path}/" : '';
2717 my ($tree_a, $tree_b) = @_;
2718 my @diff_tree = qw(diff-tree -z -r);
2719 if ($_cp_similarity) {
2720 push @diff_tree, "-C$_cp_similarity";
2722 push @diff_tree, '-C';
2724 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2725 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2726 push @diff_tree, $tree_a, $tree_b;
2727 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2731 while (<$diff_fh>) {
2732 chomp $_; # this gets rid of the trailing "\0"
2733 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2734 $::sha1\s($::sha1)\s
2735 ([MTCRAD])\d*$/xo) {
2736 push @mods, { mode_a => $1, mode_b => $2,
2737 sha1_b => $3, chg => $4 };
2738 if ($4 =~ /^(?:C|R)$/) {
2743 } elsif ($state eq 'file_a') {
2744 my $x = $mods[$#mods] or croak "Empty array\n";
2745 if ($x->{chg} !~ /^(?:C|R)$/) {
2746 croak "Error parsing $_, $x->{chg}\n";
2750 } elsif ($state eq 'file_b') {
2751 my $x = $mods[$#mods] or croak "Empty array\n";
2752 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2753 croak "Error parsing $_, $x->{chg}\n";
2755 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2756 croak "Error parsing $_, $x->{chg}\n";
2761 croak "Error parsing $_\n";
2764 command_close_pipe($diff_fh, $ctx);
2768 sub check_diff_paths {
2769 my ($ra, $pfx, $rev, $mods) = @_;
2771 $pfx .= '/' if length $pfx;
2773 sub type_diff_paths {
2774 my ($ra, $types, $path, $rev) = @_;
2775 my @p = split m#/+#, $path;
2777 unless (defined $types->{$c}) {
2778 $types->{$c} = $ra->check_path($c, $rev);
2781 $c .= '/' . shift @p;
2782 next if defined $types->{$c};
2783 $types->{$c} = $ra->check_path($c, $rev);
2787 foreach my $m (@$mods) {
2788 foreach my $f (qw/file_a file_b/) {
2789 next unless defined $m->{$f};
2790 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2791 if (length $pfx.$dir && ! defined $types{$dir}) {
2792 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2800 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2804 my ($self, $path) = @_;
2805 $self->{path_prefix}.(defined $path ? $path : '');
2809 my ($self, $path) = @_;
2810 if ($self->{url} =~ m#^https?://#) {
2811 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2813 $self->{url} . '/' . $self->repo_path($path);
2818 my $rm = $self->{rm};
2819 delete $rm->{''}; # we never delete the url we're tracking
2822 foreach (keys %$rm) {
2823 my @d = split m#/#, $_;
2827 $c .= '/' . shift @d;
2831 delete $rm->{$self->{svn_path}};
2832 delete $rm->{''}; # we never delete the url we're tracking
2835 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2840 my @dn = split m#/#, $_;
2842 delete $rm->{join '/', @dn};
2849 command_close_pipe($fh, $ctx);
2851 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2852 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2853 $self->close_directory($bat->{$d}, $p);
2854 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2855 print "\tD+\t$d/\n" unless $::_q;
2856 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2861 sub open_or_add_dir {
2862 my ($self, $full_path, $baton) = @_;
2863 my $t = $self->{types}->{$full_path};
2865 die "$full_path not known in r$self->{r} or we have a bug!\n";
2867 if ($t == $SVN::Node::none) {
2868 return $self->add_directory($full_path, $baton,
2869 undef, -1, $self->{pool});
2870 } elsif ($t == $SVN::Node::dir) {
2871 return $self->open_directory($full_path, $baton,
2872 $self->{r}, $self->{pool});
2874 print STDERR "$full_path already exists in repository at ",
2875 "r$self->{r} and it is not a directory (",
2876 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2881 my ($self, $path) = @_;
2882 my $bat = $self->{bat};
2883 my $repo_path = $self->repo_path($path);
2884 return $bat->{''} unless (length $repo_path);
2885 my @p = split m#/+#, $repo_path;
2887 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2890 $c .= '/' . shift @p;
2891 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2897 my ($self, $m) = @_;
2898 my ($dir, $file) = split_path($m->{file_b});
2899 my $pbat = $self->ensure_path($dir);
2900 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2902 print "\tA\t$m->{file_b}\n" unless $::_q;
2903 $self->chg_file($fbat, $m);
2904 $self->close_file($fbat,undef,$self->{pool});
2908 my ($self, $m) = @_;
2909 my ($dir, $file) = split_path($m->{file_b});
2910 my $pbat = $self->ensure_path($dir);
2911 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2912 $self->url_path($m->{file_a}), $self->{r});
2913 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2914 $self->chg_file($fbat, $m);
2915 $self->close_file($fbat,undef,$self->{pool});
2919 my ($self, $path, $pbat) = @_;
2920 my $rpath = $self->repo_path($path);
2921 my ($dir, $file) = split_path($rpath);
2922 $self->{rm}->{$dir} = 1;
2923 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2927 my ($self, $m) = @_;
2928 my ($dir, $file) = split_path($m->{file_b});
2929 my $pbat = $self->ensure_path($dir);
2930 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2931 $self->url_path($m->{file_a}), $self->{r});
2932 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2933 $self->chg_file($fbat, $m);
2934 $self->close_file($fbat,undef,$self->{pool});
2936 ($dir, $file) = split_path($m->{file_a});
2937 $pbat = $self->ensure_path($dir);
2938 $self->delete_entry($m->{file_a}, $pbat);
2942 my ($self, $m) = @_;
2943 my ($dir, $file) = split_path($m->{file_b});
2944 my $pbat = $self->ensure_path($dir);
2945 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2946 $pbat,$self->{r},$self->{pool});
2947 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2948 $self->chg_file($fbat, $m);
2949 $self->close_file($fbat,undef,$self->{pool});
2952 sub T { shift->M(@_) }
2954 sub change_file_prop {
2955 my ($self, $fbat, $pname, $pval) = @_;
2956 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2960 my ($self, $fbat, $m) = @_;
2961 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2962 $self->change_file_prop($fbat,'svn:executable','*');
2963 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2964 $self->change_file_prop($fbat,'svn:executable',undef);
2966 my $fh = IO::File->new_tmpfile or croak $!;
2967 if ($m->{mode_b} =~ /^120/) {
2968 print $fh 'link ' or croak $!;
2969 $self->change_file_prop($fbat,'svn:special','*');
2970 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2971 $self->change_file_prop($fbat,'svn:special',undef);
2973 defined(my $pid = fork) or croak $!;
2975 open STDOUT, '>&', $fh or croak $!;
2976 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2980 $fh->flush == 0 or croak $!;
2981 seek $fh, 0, 0 or croak $!;
2983 my $md5 = Digest::MD5->new;
2984 $md5->addfile($fh) or croak $!;
2985 seek $fh, 0, 0 or croak $!;
2987 my $exp = $md5->hexdigest;
2988 my $pool = SVN::Pool->new;
2989 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2990 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2991 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2994 close $fh or croak $!;
2998 my ($self, $m) = @_;
2999 my ($dir, $file) = split_path($m->{file_b});
3000 my $pbat = $self->ensure_path($dir);
3001 print "\tD\t$m->{file_b}\n" unless $::_q;
3002 $self->delete_entry($m->{file_b}, $pbat);
3007 my ($p,$bat) = ($self->{pool}, $self->{bat});
3008 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3010 $self->close_directory($bat->{$_}, $p);
3012 $self->close_directory($bat->{''}, $p);
3013 $self->SUPER::close_edit($p);
3019 $self->SUPER::abort_edit($self->{pool});
3024 $self->SUPER::DESTROY(@_);
3025 $self->{pool}->clear;
3028 # this drives the editor
3031 my $mods = $self->{mods};
3032 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3033 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3035 if (defined $o{$f}) {
3038 fatal("Invalid change type: $f\n");
3041 $self->rmdirs if $_rmdir;
3047 return scalar @$mods;
3050 package Git::SVN::Ra;
3051 use vars qw/@ISA $config_dir $_log_window_size/;
3054 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3057 # enforce temporary pool usage for some simple functions
3059 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3060 my $SUPER = "SUPER::$f";
3063 my $pool = SVN::Pool->new;
3064 my @ret = $self->$SUPER(@_,$pool);
3066 wantarray ? @ret : $ret[0];
3072 my ($class, $url) = @_;
3074 return $RA if ($RA && $RA->{url} eq $url);
3076 SVN::_Core::svn_config_ensure($config_dir, undef);
3077 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3078 SVN::Client::get_simple_provider(),
3079 SVN::Client::get_ssl_server_trust_file_provider(),
3080 SVN::Client::get_simple_prompt_provider(
3081 \&Git::SVN::Prompt::simple, 2),
3082 SVN::Client::get_ssl_client_cert_file_provider(),
3083 SVN::Client::get_ssl_client_cert_prompt_provider(
3084 \&Git::SVN::Prompt::ssl_client_cert, 2),
3085 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3086 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3087 SVN::Client::get_username_provider(),
3088 SVN::Client::get_ssl_server_trust_prompt_provider(
3089 \&Git::SVN::Prompt::ssl_server_trust),
3090 SVN::Client::get_username_prompt_provider(
3091 \&Git::SVN::Prompt::username, 2),
3093 my $config = SVN::Core::config_get_config($config_dir);
3095 my $self = SVN::Ra->new(url => $url, auth => $baton,
3097 pool => SVN::Pool->new,
3098 auth_provider_callbacks => $callbacks);
3099 $self->{svn_path} = $url;
3100 $self->{repos_root} = $self->get_repos_root;
3101 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3102 $self->{cache} = { check_path => { r => 0, data => {} },
3103 get_dir => { r => 0, data => {} } };
3104 $RA = bless $self, $class;
3108 my ($self, $path, $r) = @_;
3109 my $cache = $self->{cache}->{check_path};
3110 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3111 return $cache->{data}->{$path};
3113 my $pool = SVN::Pool->new;
3114 my $t = $self->SUPER::check_path($path, $r, $pool);
3116 if ($r != $cache->{r}) {
3117 %{$cache->{data}} = ();
3120 $cache->{data}->{$path} = $t;
3124 my ($self, $dir, $r) = @_;
3125 my $cache = $self->{cache}->{get_dir};
3126 if ($r == $cache->{r}) {
3127 if (my $x = $cache->{data}->{$dir}) {
3128 return wantarray ? @$x : $x->[0];
3131 my $pool = SVN::Pool->new;
3132 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3133 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3135 if ($r != $cache->{r}) {
3136 %{$cache->{data}} = ();
3139 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3140 wantarray ? (\%dirents, $r, $props) : \%dirents;
3144 # do not call the real DESTROY since we store ourselves in $RA
3148 my ($self, @args) = @_;
3149 my $pool = SVN::Pool->new;
3150 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3151 my $ret = $self->SUPER::get_log(@args, $pool);
3156 sub get_commit_editor {
3157 my ($self, $log, $cb, $pool) = @_;
3158 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3159 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3163 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3164 my $new = ($rev_a == $rev_b);
3165 my $path = $gs->{path};
3167 if ($new && -e $gs->{index}) {
3168 unlink $gs->{index} or die
3169 "Couldn't unlink index: $gs->{index}: $!\n";
3171 my $pool = SVN::Pool->new;
3172 $editor->set_path_strip($path);
3173 my (@pc) = split m#/#, $path;
3174 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3176 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3178 # Since we can't rely on svn_ra_reparent being available, we'll
3179 # just have to do some magic with set_path to make it so
3180 # we only want a partial path.
3182 my $final = join('/', @pc);
3184 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3185 $sp .= '/' if length $sp;
3188 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3190 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3192 $reporter->finish_report($pool);
3194 $editor->{git_commit_ok};
3197 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3198 # svn_ra_reparent didn't work before 1.4)
3200 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3201 my $path = $gs->{path};
3202 my $pool = SVN::Pool->new;
3204 my $full_url = $self->{url};
3205 my $old_url = $full_url;
3206 $full_url .= "/$path" if length $path;
3207 my ($ra, $reparented);
3208 if ($old_url ne $full_url) {
3209 if ($old_url !~ m#^svn(\+ssh)?://#) {
3210 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3212 $self->{url} = $full_url;
3218 $ra = Git::SVN::Ra->new($full_url);
3223 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3224 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3225 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3226 $reporter->finish_report($pool);
3229 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3230 $self->{url} = $old_url;
3234 $editor->{git_commit_ok};
3237 sub longest_common_path {
3238 my ($gsv, $globs) = @_;
3240 my $common_max = scalar @$gsv;
3242 foreach my $gs (@$gsv) {
3243 my @tmp = split m#/#, $gs->{path};
3246 $p .= length($p) ? "/$_" : $_;
3252 $common_max += scalar @$globs;
3253 foreach my $glob (@$globs) {
3254 my @tmp = split m#/#, $glob->{path}->{left};
3257 $p .= length($p) ? "/$_" : $_;
3263 my $longest_path = '';
3264 foreach (sort {length $b <=> length $a} keys %common) {
3265 if ($common{$_} == $common_max) {
3273 sub gs_fetch_loop_common {
3274 my ($self, $base, $head, $gsv, $globs) = @_;
3275 return if ($base > $head);
3276 my $inc = $_log_window_size;
3277 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3278 my $longest_path = longest_common_path($gsv, $globs);
3279 my $ra_url = $self->{url};
3283 my $err_handler = $SVN::Error::handler;
3284 $SVN::Error::handler = sub {
3286 skip_unknown_revs($err);
3289 my ($paths, $r, $author, $date, $log) = @_;
3290 [ dup_changed_paths($paths),
3291 { author => $author, date => $date, log => $log } ];
3293 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3294 sub { $revs{$_[1]} = _cb(@_) });
3295 if ($err && $max >= $head) {
3296 print STDERR "Path '$longest_path' ",
3297 "was probably deleted:\n",
3298 $err->expanded_message,
3299 "\nWill attempt to follow ",
3300 "revisions r$min .. r$max ",
3301 "committed before the deletion\n";
3303 while (--$hi >= $min) {
3305 $self->get_log([$longest_path], $min, $hi,
3308 $revs{$_[1]} = _cb(@_) });
3310 print STDERR "r$min .. r$ok OK\n";
3315 $SVN::Error::handler = $err_handler;
3317 my %exists = map { $_->{path} => $_ } @$gsv;
3318 foreach my $r (sort {$a <=> $b} keys %revs) {
3319 my ($paths, $logged) = @{$revs{$r}};
3321 foreach my $gs ($self->match_globs(\%exists, $paths,
3323 if ($gs->rev_db_max >= $r) {
3326 next unless $gs->match_paths($paths, $r);
3327 $gs->{logged_rev_props} = $logged;
3328 if (my $last_commit = $gs->last_commit) {
3329 $gs->assert_index_clean($last_commit);
3331 my $log_entry = $gs->do_fetch($paths, $r);
3333 $gs->do_git_commit($log_entry);
3336 foreach my $g (@$globs) {
3337 my $k = "svn-remote.$g->{remote}." .
3339 Git::SVN::tmp_config($k, $r);
3345 $self = Git::SVN::Ra->new($ra_url);
3346 $ra_invalid = undef;
3349 # pre-fill the .rev_db since it'll eventually get filled in
3350 # with '0' x40 if something new gets committed
3351 foreach my $gs (@$gsv) {
3352 next if defined $gs->rev_db_get($max);
3353 $gs->rev_db_set($max, 0 x40);
3355 foreach my $g (@$globs) {
3356 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3357 Git::SVN::tmp_config($k, $max);
3359 last if $max >= $head;
3362 $max = $head if ($max > $head);
3367 my ($self, $exists, $paths, $globs, $r) = @_;
3370 my ($self, $exists, $g, $r) = @_;
3371 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3372 return unless scalar @x == 3;
3373 my $dirents = $x[0];
3374 foreach my $de (keys %$dirents) {
3375 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3376 my $p = $g->{path}->full_path($de);
3377 next if $exists->{$p};
3378 next if (length $g->{path}->{right} &&
3379 ($self->check_path($p, $r) !=
3381 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3382 $g->{ref}->full_path($de), 1);
3385 foreach my $g (@$globs) {
3386 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3387 if ($path->{action} =~ /^[AR]$/) {
3388 get_dir_check($self, $exists, $g, $r);
3391 foreach (keys %$paths) {
3392 if (/$g->{path}->{left_regex}/ &&
3393 !/$g->{path}->{regex}/) {
3394 next if $paths->{$_}->{action} !~ /^[AR]$/;
3395 get_dir_check($self, $exists, $g, $r);
3397 next unless /$g->{path}->{regex}/;
3399 my $pathname = $g->{path}->full_path($p);
3400 next if $exists->{$pathname};
3401 next if ($self->check_path($pathname, $r) !=
3403 $exists->{$pathname} = Git::SVN->init(
3404 $self->{url}, $pathname, undef,
3405 $g->{ref}->full_path($p), 1);
3408 foreach (split m#/#, $g->{path}->{left}) {
3410 next unless ($paths->{$c} &&
3411 ($paths->{$c}->{action} =~ /^[AR]$/));
3412 get_dir_check($self, $exists, $g, $r);
3420 return $self->{url} if ($self->{url} eq $self->{repos_root});
3421 my $url = $self->{repos_root};
3422 my @components = split(m!/!, $self->{svn_path});
3425 $url .= "/$c" if length $c;
3426 eval { (ref $self)->new($url)->get_latest_revnum };
3427 } while ($@ && ($c = shift @components));
3433 unless (defined $can_do_switch) {
3434 my $pool = SVN::Pool->new;
3436 $self->do_switch(1, '', 0, $self->{url},
3437 SVN::Delta::Editor->new, $pool);
3442 $rep->abort_report($pool);
3450 sub skip_unknown_revs {
3452 my $errno = $err->apr_err();
3453 # Maybe the branch we're tracking didn't
3454 # exist when the repo started, so it's
3455 # not an error if it doesn't, just continue
3457 # Wonderfully consistent library, eh?
3458 # 160013 - svn:// and file://
3459 # 175002 - http(s)://
3460 # 175007 - http(s):// (this repo required authorization, too...)
3461 # More codes may be discovered later...
3462 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3463 my $err_key = $err->expanded_message;
3464 # revision numbers change every time, filter them out
3465 $err_key =~ s/\d+/\0/g;
3466 $err_key = "$errno\0$err_key";
3467 unless ($ignored_err{$err_key}) {
3468 warn "W: Ignoring error from SVN, path probably ",
3469 "does not exist: ($errno): ",
3470 $err->expanded_message,"\n";
3471 $ignored_err{$err_key} = 1;
3475 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3478 # svn_log_changed_path_t objects passed to get_log are likely to be
3479 # overwritten even if only the refs are copied to an external variable,
3480 # so we should dup the structures in their entirety. Using an externally
3481 # passed pool (instead of our temporary and quickly cleared pool in
3482 # Git::SVN::Ra) does not help matters at all...
3483 sub dup_changed_paths {
3485 return undef unless $paths;
3487 foreach my $p (keys %$paths) {
3488 my $i = $paths->{$p};
3489 my %s = map { $_ => $i->$_ }
3490 qw/copyfrom_path copyfrom_rev action/;
3496 package Git::SVN::Log;
3499 use POSIX qw/strftime/;
3500 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3501 %rusers $show_commit $incremental/;
3506 return 1 if defined $c->{r};
3508 # big commit message got truncated by the 16k pretty buffer in rev-list
3509 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3510 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3512 my @log = command(qw/cat-file commit/, $c->{c});
3514 # shift off the headers
3515 shift @log while ($log[0] ne '');
3518 # TODO: make $c->{l} not have a trailing newline in the future
3519 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3521 (undef, $c->{r}, undef) = ::extract_metadata(
3522 (grep(/^git-svn-id: /, @log))[-1]);
3524 return defined $c->{r};
3530 $dcvar = 'color.diff';
3531 $dc = `git-config --get $dcvar`;
3533 # nothing at all; fallback to "diff.color"
3534 $dcvar = 'diff.color';
3535 $dc = `git-config --get $dcvar`;
3538 if ($dc eq 'auto') {
3540 $pc = `git-config --get color.pager`;
3542 # does not have it -- fallback to pager.color
3543 $pc = `git-config --bool --get pager.color`;
3546 $pc = `git-config --bool --get color.pager`;
3552 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3553 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3557 return 0 if $dc eq 'never';
3558 return 1 if $dc eq 'always';
3559 chomp($dc = `git-config --bool --get $dcvar`);
3560 return ($dc eq 'true');
3563 sub git_svn_log_cmd {
3564 my ($r_min, $r_max, @args) = @_;
3566 my (@files, @log_opts);
3567 foreach my $x (@args) {
3568 if ($x eq '--' || @files) {
3571 if (::verify_ref("$x^0")) {
3579 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3580 $gs ||= Git::SVN->_new;
3581 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3583 push @cmd, '-r' unless $non_recursive;
3584 push @cmd, qw/--raw --name-status/ if $verbose;
3585 push @cmd, '--color' if log_use_color();
3586 push @cmd, @log_opts;
3587 if (defined $r_max && $r_max == $r_min) {
3588 push @cmd, '--max-count=1';
3589 if (my $c = $gs->rev_db_get($r_max)) {
3592 } elsif (defined $r_max) {
3593 my ($c_min, $c_max);
3594 $c_max = $gs->rev_db_get($r_max);
3595 $c_min = $gs->rev_db_get($r_min);
3596 if (defined $c_min && defined $c_max) {
3597 if ($r_max > $r_max) {
3598 push @cmd, "$c_min..$c_max";
3600 push @cmd, "$c_max..$c_min";
3602 } elsif ($r_max > $r_min) {
3608 return (@cmd, @files);
3611 # adapted from pager.c
3613 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3614 if (!defined $pager) {
3616 } elsif (length $pager == 0 || $pager eq 'cat') {
3622 return unless -t *STDOUT && defined $pager;
3623 pipe my $rfd, my $wfd or return;
3624 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3626 open STDOUT, '>&', $wfd or
3627 ::fatal "Can't redirect to stdout: $!\n";
3630 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3631 $ENV{LESS} ||= 'FRSX';
3632 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3635 sub tz_to_s_offset {
3638 return ($1 * 60) + ($tz * 3600);
3641 sub get_author_info {
3642 my ($dest, $author, $t, $tz) = @_;
3643 $author =~ s/(?:^\s*|\s*$)//g;
3644 $dest->{a_raw} = $author;
3647 $au = $rusers{$author} || undef;
3650 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3655 # Date::Parse isn't in the standard Perl distro :(
3656 if ($tz =~ s/^\+//) {
3657 $t += tz_to_s_offset($tz);
3658 } elsif ($tz =~ s/^\-//) {
3659 $t -= tz_to_s_offset($tz);
3661 $dest->{t_utc} = $t;
3664 sub process_commit {
3665 my ($c, $r_min, $r_max, $defer) = @_;
3666 if (defined $r_min && defined $r_max) {
3667 if ($r_min == $c->{r} && $r_min == $r_max) {
3671 return 1 if $r_min == $r_max;
3672 if ($r_min < $r_max) {
3673 # we need to reverse the print order
3674 return 0 if (defined $limit && --$limit < 0);
3678 if ($r_min != $r_max) {
3679 return 1 if ($r_min < $c->{r});
3680 return 1 if ($r_max > $c->{r});
3683 return 0 if (defined $limit && --$limit < 0);
3692 if (my $l = $c->{l}) {
3693 while ($l->[0] =~ /^\s*$/) { shift @$l }
3696 $l_fmt ||= 'A' . length($c->{r});
3697 print 'r',pack($l_fmt, $c->{r}),' | ';
3698 print "$c->{c} | " if $show_commit;
3701 show_commit_normal($c);
3705 sub show_commit_changed_paths {
3707 return unless $c->{changed};
3708 print "Changed paths:\n", @{$c->{changed}};
3711 sub show_commit_normal {
3713 print '-' x72, "\nr$c->{r} | ";
3714 print "$c->{c} | " if $show_commit;
3715 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3716 localtime($c->{t_utc})), ' | ';
3719 if (my $l = $c->{l}) {
3720 while ($l->[$#$l] eq "\n" && $#$l > 0
3721 && $l->[($#$l - 1)] eq "\n") {
3724 $nr_line = scalar @$l;
3726 print "1 line\n\n\n";
3728 if ($nr_line == 1) {
3729 $nr_line = '1 line';
3731 $nr_line .= ' lines';
3733 print $nr_line, "\n";
3734 show_commit_changed_paths($c);
3736 print $_ foreach @$l;
3740 show_commit_changed_paths($c);
3744 foreach my $x (qw/raw stat diff/) {
3747 print $_ foreach @{$c->{$x}}
3754 my ($r_min, $r_max);
3755 my $r_last = -1; # prevent dupes
3761 if (defined $::_revision) {
3762 if ($::_revision =~ /^(\d+):(\d+)$/) {
3763 ($r_min, $r_max) = ($1, $2);
3764 } elsif ($::_revision =~ /^\d+$/) {
3765 $r_min = $r_max = $::_revision;
3767 ::fatal "-r$::_revision is not supported, use ",
3768 "standard \'git log\' arguments instead\n";
3773 @args = git_svn_log_cmd($r_min, $r_max, @args);
3774 my $log = command_output_pipe(@args);
3776 my (@k, $c, $d, $stat);
3777 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3779 if (/^${esc_color}commit ($::sha1_short)/o) {
3781 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3783 process_commit($c, $r_min, $r_max, \@k) or
3788 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3789 get_author_info($c, $1, $2, $3);
3790 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3792 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3793 push @{$c->{raw}}, $_;
3794 } elsif (/^${esc_color}[ACRMDT]\t/) {
3795 # we could add $SVN->{svn_path} here, but that requires
3796 # remote access at the moment (repo_path_split)...
3797 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3798 push @{$c->{changed}}, $_;
3799 } elsif (/^${esc_color}diff /o) {
3801 push @{$c->{diff}}, $_;
3803 push @{$c->{diff}}, $_;
3804 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3805 $esc_color*[\+\-]*$esc_color$/x) {
3807 push @{$c->{stat}}, $_;
3808 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3809 push @{$c->{stat}}, $_;
3811 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3812 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3813 } elsif (s/^${esc_color} //o) {
3814 push @{$c->{l}}, $_;
3817 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3819 process_commit($c, $r_min, $r_max, \@k);
3825 process_commit($_, $r_min, $r_max) foreach reverse @k;
3829 print '-' x72,"\n" unless $incremental || $oneline;
3832 package Git::SVN::Migration;
3833 # these version numbers do NOT correspond to actual version numbers
3834 # of git nor git-svn. They are just relative.
3836 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3838 # v1 layout: .git/$id/info/url, refs/remotes/$id
3840 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3842 # v3 layout: .git/svn/$id, refs/remotes/$id
3843 # - info/url may remain for backwards compatibility
3844 # - this is what we migrate up to this layout automatically,
3845 # - this will be used by git svn init on single branches
3846 # v3.1 layout (auto migrated):
3847 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3848 # for backwards compatibility
3850 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3851 # - this is only created for newly multi-init-ed
3852 # repositories. Similar in spirit to the
3853 # --use-separate-remotes option in git-clone (now default)
3854 # - we do not automatically migrate to this (following
3855 # the example set by core git)
3859 use File::Path qw/mkpath/;
3860 use File::Basename qw/dirname basename/;
3861 use vars qw/$_minimize/;
3863 sub migrate_from_v0 {
3864 my $git_dir = $ENV{GIT_DIR};
3865 return undef unless -d $git_dir;
3866 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3870 my ($id, $orig_ref) = ($_, $_);
3871 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3872 next unless -f "$git_dir/$id/info/url";
3873 my $new_ref = "refs/remotes/$id";
3874 if (::verify_ref("$new_ref^0")) {
3875 print STDERR "W: $orig_ref is probably an old ",
3876 "branch used by an ancient version of ",
3878 "However, $new_ref also exists.\n",
3879 "We will not be able ",
3880 "to use this branch until this ",
3881 "ambiguity is resolved.\n";
3884 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3885 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3886 command_noisy('update-ref', $new_ref, $orig_ref);
3887 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3890 command_close_pipe($fh, $ctx);
3891 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3895 sub migrate_from_v1 {
3896 my $git_dir = $ENV{GIT_DIR};
3898 return $migrated unless -d $git_dir;
3899 my $svn_dir = "$git_dir/svn";
3901 # just in case somebody used 'svn' as their $id at some point...
3902 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3904 print STDERR "Migrating from a git-svn v1 layout...\n";
3906 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3907 "$svn_dir\n\t(required for this version ",
3908 "($::VERSION) of git-svn) does not. exist\n";
3909 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3912 next unless $x =~ s#^refs/remotes/##;
3914 next unless -f "$git_dir/$x/info/url";
3915 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3917 my $dn = dirname("$git_dir/svn/$x");
3918 mkpath([$dn]) unless -d $dn;
3919 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3920 mkpath(["$git_dir/svn/svn"]);
3921 print STDERR " - $git_dir/$x/info => ",
3922 "$git_dir/svn/$x/info\n";
3923 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3925 # don't worry too much about these, they probably
3926 # don't exist with repos this old (save for index,
3927 # and we can easily regenerate that)
3928 foreach my $f (qw/unhandled.log index .rev_db/) {
3929 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3932 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3933 rename "$git_dir/$x", "$git_dir/svn/$x" or
3938 command_close_pipe($fh, $ctx);
3939 print STDERR "Done migrating from a git-svn v1 layout\n";
3944 my ($l_map, $pfx, $path) = @_;
3946 foreach (<$path/*>) {
3947 if (-r "$_/info/url") {
3948 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3949 my $ref_id = $pfx . basename $_;
3950 my $url = ::file_to_s("$_/info/url");
3951 $l_map->{$ref_id} = $url;
3958 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3959 read_old_urls($l_map, $x, $_);
3963 sub migrate_from_v2 {
3964 my @cfg = command(qw/config -l/);
3965 return if grep /^svn-remote\..+\.url=/, @cfg;
3967 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3970 foreach my $ref_id (sort keys %l_map) {
3971 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3973 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3980 sub minimize_connections {
3981 my $r = Git::SVN::read_all_remotes();
3983 my $root_repos = {};
3984 foreach my $repo_id (keys %$r) {
3985 my $url = $r->{$repo_id}->{url} or next;
3986 my $fetch = $r->{$repo_id}->{fetch} or next;
3987 my $ra = Git::SVN::Ra->new($url);
3989 # skip existing cases where we already connect to the root
3990 if (($ra->{url} eq $ra->{repos_root}) ||
3991 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3993 $root_repos->{$ra->{url}} = $repo_id;
3997 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3998 my $root_path = $ra->{url};
3999 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4000 foreach my $path (keys %$fetch) {
4001 my $ref_id = $fetch->{$path};
4002 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4004 # make sure we can read when connecting to
4005 # a higher level of a repository
4006 my ($last_rev, undef) = $gs->last_rev_commit;
4007 if (!defined $last_rev) {
4009 $root_ra->get_latest_revnum;
4013 my $new = $root_path;
4014 $new .= length $path ? "/$path" : '';
4016 $root_ra->get_log([$new], $last_rev, $last_rev,
4020 $new_urls->{$ra->{repos_root}}->{$new} =
4021 { ref_id => $ref_id,
4022 old_repo_id => $repo_id,
4023 old_path => $path };
4028 foreach my $url (keys %$new_urls) {
4029 # see if we can re-use an existing [svn-remote "repo_id"]
4030 # instead of creating a(n ugly) new section:
4031 my $repo_id = $root_repos->{$url} ||
4032 Git::SVN::sanitize_remote_name($url);
4034 my $fetch = $new_urls->{$url};
4035 foreach my $path (keys %$fetch) {
4036 my $x = $fetch->{$path};
4037 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4038 my $pfx = "svn-remote.$x->{old_repo_id}";
4040 my $old_fetch = quotemeta("$x->{old_path}:".
4041 "refs/remotes/$x->{ref_id}");
4042 command_noisy(qw/config --unset/,
4043 "$pfx.fetch", '^'. $old_fetch . '$');
4044 delete $r->{$x->{old_repo_id}}->
4045 {fetch}->{$x->{old_path}};
4046 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4047 command_noisy(qw/config --unset/,
4049 push @emptied, $x->{old_repo_id}
4054 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4055 "$ENV{GIT_DIR}/config";
4057 The following [svn-remote] sections in your config file ($file) are empty
4058 and can be safely removed:
4060 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4064 sub migration_check {
4068 minimize_connections() if $_minimize;
4071 package Git::IndexInfo;
4074 use Git qw/command_input_pipe command_close_pipe/;
4078 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4079 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4083 my ($self, $path) = @_;
4084 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4085 return ++$self->{nr};
4091 my ($self, $mode, $hash, $path) = @_;
4092 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4093 return ++$self->{nr};
4100 command_close_pipe($self->{gui}, $self->{ctx});
4103 package Git::SVN::GlobSpec;
4108 my ($class, $glob) = @_;
4110 $re =~ s!/+$!!g; # no need for trailing slashes
4111 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4112 my ($left, $right) = ($1, $2);
4114 die "Only one '*' wildcard expansion ",
4115 "is supported (got $nr): '$glob'\n";
4116 } elsif ($nr == 0) {
4117 die "One '*' is needed for glob: '$glob'\n";
4119 $re = quotemeta($left) . $re . quotemeta($right);
4120 if (length $left && !($left =~ s!/+$!!g)) {
4121 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4123 if (length $right && !($right =~ s!^/+!!g)) {
4124 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4126 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4127 bless { left => $left, right => $right, left_regex => $left_re,
4128 regex => qr/$re/, glob => $glob }, $class;
4132 my ($self, $path) = @_;
4133 return (length $self->{left} ? "$self->{left}/" : '') .
4134 $path . (length $self->{right} ? "/$self->{right}" : '');
4142 $remotes = { # returned by read_all_remotes()
4144 # svn-remote.svn.url=https://svn.musicpd.org
4145 url => 'https://svn.musicpd.org',
4146 # svn-remote.svn.fetch=mpd/trunk:trunk
4148 'mpd/trunk' => 'trunk',
4150 # svn-remote.svn.tags=mpd/tags/*:tags/*
4155 regex => qr!mpd/tags/([^/]+)$!,
4161 regex => qr!tags/([^/]+)$!,
4168 $log_entry hashref as returned by libsvn_log_entry()
4170 log => 'whitespace-formatted log entry
4171 ', # trailing newline is preserved
4172 revision => '8', # integer
4173 date => '2004-02-24T17:01:44.108345Z', # commit date
4174 author => 'committer name'
4178 # this is generated by generate_diff();
4179 @mods = array of diff-index line hashes, each element represents one line
4180 of diff-index output
4182 diff-index line ($m hash)
4184 mode_a => first column of diff-index output, no leading ':',
4185 mode_b => second column of diff-index output,
4186 sha1_b => sha1sum of the final blob,
4187 chg => change type [MCRADT],
4188 file_a => original file name of a file (iff chg is 'C' or 'R')
4189 file_b => new/current file name of a file (any chg)
4193 # retval of read_url_paths{,_all}();
4195 # repository root url
4196 'https://svn.musicpd.org' => {
4197 # repository path # GIT_SVN_ID
4198 'mpd/trunk' => 'trunk',
4199 'mpd/tags/0.11.5' => 'tags/0.11.5',
4204 I don't trust the each() function on unless I created %hash myself
4205 because the internal iterator may not have started at base.