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
129 'multi-fetch' => [ \&cmd_multi_fetch,
130 "Deprecated alias for $0 fetch --all",
131 { 'revision|r=s' => \$_revision, %fc_opts } ],
132 'migrate' => [ sub { },
133 # no-op, we automatically run this anyways,
134 'Migrate configuration/metadata/layout from
135 previous versions of git-svn',
136 { 'minimize' => \$Git::SVN::Migration::_minimize,
138 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
139 { 'limit=i' => \$Git::SVN::Log::limit,
140 'revision|r=s' => \$_revision,
141 'verbose|v' => \$Git::SVN::Log::verbose,
142 'incremental' => \$Git::SVN::Log::incremental,
143 'oneline' => \$Git::SVN::Log::oneline,
144 'show-commit' => \$Git::SVN::Log::show_commit,
145 'non-recursive' => \$Git::SVN::Log::non_recursive,
146 'authors-file|A=s' => \$_authors,
147 'color' => \$Git::SVN::Log::color,
148 'pager=s' => \$Git::SVN::Log::pager
150 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
152 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
153 { 'merge|m|M' => \$_merge,
154 'verbose|v' => \$_verbose,
155 'strategy|s=s' => \$_strategy,
156 'local|l' => \$_local,
157 'fetch-all|all' => \$_fetch_all,
159 'commit-diff' => [ \&cmd_commit_diff,
160 'Commit a diff between two trees',
161 { 'message|m=s' => \$_message,
162 'file|F=s' => \$_file,
163 'revision|r=s' => \$_revision,
168 for (my $i = 0; $i < @ARGV; $i++) {
169 if (defined $cmd{$ARGV[$i]}) {
176 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
178 read_repo_config(\%opts);
179 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
180 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
181 'minimize-connections' => \$Git::SVN::Migration::_minimize,
182 'id|i=s' => \$Git::SVN::default_ref_id,
183 'svn-remote|remote|R=s' => sub {
184 $Git::SVN::no_reuse_existing = 1;
185 $Git::SVN::default_repo_id = $_[1] });
186 exit 1 if (!$rv && $cmd && $cmd ne 'log');
189 version() if $_version;
190 usage(1) unless defined $cmd;
191 load_authors() if $_authors;
193 # make sure we're always running
194 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
195 unless (-d $ENV{GIT_DIR}) {
196 if ($git_dir_user_set) {
197 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
198 "but it is not a directory\n";
200 my $git_dir = delete $ENV{GIT_DIR};
201 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
202 unless (length $cdup) {
203 die "Already at toplevel, but $git_dir ",
204 "not found '$cdup'\n";
206 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
207 unless (-d $git_dir) {
208 die "$git_dir still not found after going to ",
211 $ENV{GIT_DIR} = $git_dir;
214 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
215 Git::SVN::Migration::migration_check();
217 Git::SVN::init_vars();
219 Git::SVN::verify_remotes_sanity();
220 $cmd{$cmd}->[0]->(@ARGV);
223 post_fetch_checkout();
226 ####################### primary functions ######################
228 my $exit = shift || 0;
229 my $fd = $exit ? \*STDERR : \*STDOUT;
231 git-svn - bidirectional operations between a single Subversion tree and git
232 Usage: $0 <command> [options] [arguments]\n
234 print $fd "Available commands:\n" unless $cmd;
236 foreach (sort keys %cmd) {
237 next if $cmd && $cmd ne $_;
238 next if /^multi-/; # don't show deprecated commands
239 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
240 foreach (keys %{$cmd{$_}->[2]}) {
241 # mixed-case options are for .git/config only
242 next if /[A-Z]/ && /^[a-z]+$/i;
243 # prints out arguments as they should be passed:
244 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
245 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
247 split /\|/,$_)," $x\n";
251 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
252 arbitrary identifier if you're tracking multiple SVN branches/repositories in
253 one git repository and want to keep them separate. See git-svn(1) for more
260 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
265 unless (-d $ENV{GIT_DIR}) {
266 my @init_db = ('init');
267 push @init_db, "--template=$_template" if defined $_template;
268 if (defined $_shared) {
269 if ($_shared =~ /[a-z]/) {
270 push @init_db, "--shared=$_shared";
272 push @init_db, "--shared";
275 command_noisy(@init_db);
278 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
279 foreach my $i (keys %icv) {
280 die "'$set' and '$i' cannot both be set\n" if $set;
281 next unless defined $icv{$i};
282 command_noisy('config', "$pfx.$i", $icv{$i});
288 my $repo_path = shift or return;
289 mkpath([$repo_path]) unless -d $repo_path;
290 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
291 $ENV{GIT_DIR} = '.git';
295 my ($url, $path) = @_;
296 if (!defined $path &&
297 (defined $_trunk || defined $_branches || defined $_tags ||
298 defined $_stdlayout) &&
299 $url !~ m#^[a-z\+]+://#) {
302 $path = basename($url) if !defined $path || !length $path;
303 cmd_init($url, $path);
304 Git::SVN::fetch_all($Git::SVN::default_repo_id);
308 if (defined $_stdlayout) {
309 $_trunk = 'trunk' if (!defined $_trunk);
310 $_tags = 'tags' if (!defined $_tags);
311 $_branches = 'branches' if (!defined $_branches);
313 if (defined $_trunk || defined $_branches || defined $_tags) {
314 return cmd_multi_init(@_);
316 my $url = shift or die "SVN repository location required ",
317 "as a command-line argument\n";
321 Git::SVN->init($url);
325 if (grep /^\d+=./, @_) {
326 die "'<rev>=<commit>' fetch arguments are ",
327 "no longer supported.\n";
331 die "Usage: $0 fetch [--all] [svn-remote]\n";
333 $remote ||= $Git::SVN::default_repo_id;
337 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
343 if ($_stdin || !@commits) {
344 print "Reading from stdin...\n";
347 if (/\b($sha1_short)\b/o) {
348 unshift @commits, $1;
353 foreach my $c (@commits) {
354 my @tmp = command('rev-parse',$c);
355 if (scalar @tmp == 1) {
357 } elsif (scalar @tmp > 1) {
358 push @revs, reverse(command('rev-list',@tmp));
360 fatal "Failed to rev-parse $c\n";
363 my $gs = Git::SVN->new;
364 my ($r_last, $cmt_last) = $gs->last_rev_commit;
366 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
367 fatal "There are new revisions that were fetched ",
368 "and need to be merged (or acknowledged) ",
369 "before committing.\nlast rev: $r_last\n",
370 " current: $gs->{last_rev}\n";
372 $gs->set_tree($_) foreach @revs;
373 print "Done committing ",scalar @revs," revisions to SVN\n";
380 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
381 print "Committing to $url ...\n";
383 die "Unable to determine upstream SVN information from ",
387 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
388 if ($_no_rebase && scalar(@$linear_refs) > 1) {
389 warn "Attempting to commit more than one change while ",
390 "--no-rebase is enabled.\n",
391 "If these changes depend on each other, re-running ",
392 "without --no-rebase will be required."
394 foreach my $d (@$linear_refs) {
395 unless (defined $last_rev) {
396 (undef, $last_rev, undef) = cmt_metadata("$d~1");
397 unless (defined $last_rev) {
398 fatal "Unable to extract revision information ",
399 "from commit $d~1\n";
403 print "diff-tree $d~1 $d\n";
406 my %ed_opts = ( r => $last_rev,
407 log => get_commit_entry($d)->{log},
408 ra => Git::SVN::Ra->new($gs->full_url),
412 print "Committed r$_[0]\n";
416 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
417 print "No changes\n$d~1 == $d\n";
418 } elsif ($parents->{$d} && @{$parents->{$d}}) {
419 $gs->{inject_parents_dcommit}->{$cmt_rev} =
422 $_fetch_all ? $gs->fetch_all : $gs->fetch;
425 # we always want to rebase against the current HEAD,
426 # not any head that was passed to us
427 my @diff = command('diff-tree', 'HEAD',
431 @finish = rebase_cmd();
432 print STDERR "W: HEAD and ", $gs->refname,
433 " differ, using @finish:\n",
436 print "No changes between current HEAD and ",
438 "\nResetting to the latest ",
440 @finish = qw/reset --mixed/;
442 command_noisy(@finish, $gs->refname);
443 $last_rev = $cmt_rev;
449 my $revision_or_hash = shift;
451 if ($revision_or_hash =~ /^r\d+$/) {
455 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
457 die "Unable to determine upstream SVN information from ",
460 my $desired_revision = substr($revision_or_hash, 1);
461 $result = $gs->rev_db_get($desired_revision);
463 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
466 print "$result\n" if $result;
470 command_noisy(qw/update-index --refresh/);
471 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
473 die "Unable to determine upstream SVN information from ",
474 "working tree history\n";
476 if (command(qw/diff-index HEAD --/)) {
477 print STDERR "Cannot rebase with uncommited changes:\n";
478 command_noisy('status');
482 $_fetch_all ? $gs->fetch_all : $gs->fetch;
484 command_noisy(rebase_cmd(), $gs->refname);
487 sub cmd_show_ignore {
488 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
489 $gs ||= Git::SVN->new;
490 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
491 $gs->traverse_ignore(\*STDOUT, $gs->{path}, $r);
496 unless (defined $_trunk || defined $_branches || defined $_tags) {
500 # there are currently some bugs that prevent multi-init/multi-fetch
501 # setups from working well without this.
502 $Git::SVN::_minimize_url = 1;
504 $_prefix = '' unless defined $_prefix;
510 if (defined $_trunk) {
511 my $trunk_ref = $_prefix . 'trunk';
512 # try both old-style and new-style lookups:
513 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
515 my ($trunk_url, $trunk_path) =
516 complete_svn_url($url, $_trunk);
517 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
521 return unless defined $_branches || defined $_tags;
522 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
523 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
524 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
527 sub cmd_multi_fetch {
528 my $remotes = Git::SVN::read_all_remotes();
529 foreach my $repo_id (sort keys %$remotes) {
530 if ($remotes->{$repo_id}->{url}) {
531 Git::SVN::fetch_all($repo_id, $remotes);
536 # this command is special because it requires no metadata
537 sub cmd_commit_diff {
538 my ($ta, $tb, $url) = @_;
539 my $usage = "Usage: $0 commit-diff -r<revision> ".
540 "<tree-ish> <tree-ish> [<URL>]\n";
541 fatal($usage) if (!defined $ta || !defined $tb);
544 my $gs = eval { Git::SVN->new };
546 fatal("Needed URL or usable git-svn --id in ",
547 "the command-line\n", $usage);
550 $svn_path = $gs->{path};
552 unless (defined $_revision) {
553 fatal("-r|--revision is a required argument\n", $usage);
555 if (defined $_message && defined $_file) {
556 fatal("Both --message/-m and --file/-F specified ",
557 "for the commit message.\n",
558 "I have no idea what you mean\n");
560 if (defined $_file) {
561 $_message = file_to_s($_file);
563 $_message ||= get_commit_entry($tb)->{log};
565 my $ra ||= Git::SVN::Ra->new($url);
566 $svn_path ||= $ra->{svn_path};
569 $r = $ra->get_latest_revnum;
570 } elsif ($r !~ /^\d+$/) {
571 die "revision argument: $r not understood by git-svn\n";
573 my %ed_opts = ( r => $r,
578 editor_cb => sub { print "Committed r$_[0]\n" },
579 svn_path => $svn_path );
580 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
581 print "No changes\n$ta == $tb\n";
585 ########################### utility functions #########################
588 my @cmd = qw/rebase/;
589 push @cmd, '-v' if $_verbose;
590 push @cmd, qw/--merge/ if $_merge;
591 push @cmd, "--strategy=$_strategy" if $_strategy;
595 sub post_fetch_checkout {
596 return if $_no_checkout;
597 my $gs = $Git::SVN::_head or return;
598 return if verify_ref('refs/heads/master^0');
600 my $valid_head = verify_ref('HEAD^0');
601 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
602 return if ($valid_head || !verify_ref('HEAD^0'));
604 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
605 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
608 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
609 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
610 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
611 print STDERR "Checked out HEAD:\n ",
612 $gs->full_url, " r", $gs->last_rev, "\n";
615 sub complete_svn_url {
616 my ($url, $path) = @_;
618 if ($path !~ m#^[a-z\+]+://#) {
619 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
620 fatal("E: '$path' is not a complete URL ",
621 "and a separate URL is not specified\n");
623 return ($url, $path);
628 sub complete_url_ls_init {
629 my ($ra, $repo_path, $switch, $pfx) = @_;
630 unless ($repo_path) {
631 print STDERR "W: $switch not specified\n";
634 $repo_path =~ s#/+$##;
635 if ($repo_path =~ m#^[a-z\+]+://#) {
636 $ra = Git::SVN::Ra->new($repo_path);
639 $repo_path =~ s#^/+##;
641 fatal("E: '$repo_path' is not a complete URL ",
642 "and a separate URL is not specified\n");
645 my $url = $ra->{url};
646 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
647 my $k = "svn-remote.$gs->{repo_id}.url";
648 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
649 if ($orig_url && ($orig_url ne $gs->{url})) {
650 die "$k already set: $orig_url\n",
651 "wanted to set to: $gs->{url}\n";
653 command_oneline('config', $k, $gs->{url}) unless $orig_url;
654 my $remote_path = "$ra->{svn_path}/$repo_path/*";
655 $remote_path =~ s#/+#/#g;
656 $remote_path =~ s#^/##g;
657 my ($n) = ($switch =~ /^--(\w+)/);
658 if (length $pfx && $pfx !~ m#/$#) {
659 die "--prefix='$pfx' must have a trailing slash '/'\n";
661 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
662 "$remote_path:refs/remotes/$pfx*");
667 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
671 sub get_tree_from_treeish {
673 # $treeish can be a symbolic ref, too:
674 my $type = command_oneline(qw/cat-file -t/, $treeish);
676 while ($type eq 'tag') {
677 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
679 if ($type eq 'commit') {
680 $expected = (grep /^tree /, command(qw/cat-file commit/,
682 ($expected) = ($expected =~ /^tree ($sha1)$/o);
683 die "Unable to get tree from $treeish\n" unless $expected;
684 } elsif ($type eq 'tree') {
685 $expected = $treeish;
687 die "$treeish is a $type, expected tree, tag or commit\n";
692 sub get_commit_entry {
693 my ($treeish) = shift;
694 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
695 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
696 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
697 open my $log_fh, '>', $commit_editmsg or croak $!;
699 my $type = command_oneline(qw/cat-file -t/, $treeish);
700 if ($type eq 'commit' || $type eq 'tag') {
701 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
706 $in_msg = 1 if (/^\s*$/);
707 } elsif (/^git-svn-id: /) {
708 # skip this for now, we regenerate the
709 # correct one on re-fetch anyways
710 # TODO: set *:merge properties or like...
712 print $log_fh $_ or croak $!;
715 command_close_pipe($msg_fh, $ctx);
717 close $log_fh or croak $!;
719 if ($_edit || ($type eq 'tree')) {
720 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
721 # TODO: strip out spaces, comments, like git-commit.sh
722 system($editor, $commit_editmsg);
724 rename $commit_editmsg, $commit_msg or croak $!;
725 open $log_fh, '<', $commit_msg or croak $!;
726 { local $/; chomp($log_entry{log} = <$log_fh>); }
727 close $log_fh or croak $!;
733 my ($str, $file, $mode) = @_;
734 open my $fd,'>',$file or croak $!;
735 print $fd $str,"\n" or croak $!;
736 close $fd or croak $!;
737 chmod ($mode &~ umask, $file) if (defined $mode);
742 open my $fd,'<',$file or croak "$!: file: $file\n";
745 close $fd or croak $!;
750 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
752 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
753 my $log = $cmd eq 'log';
756 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
757 my ($user, $name, $email) = ($1, $2, $3);
759 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
761 $users{$user} = [$name, $email];
764 close $authors or croak $!;
767 # convert GetOpt::Long specs for use by git-config
768 sub read_repo_config {
769 return unless -d $ENV{GIT_DIR};
772 foreach my $o (keys %$opts) {
773 # if we have mixedCase and a long option-only, then
774 # it's a config-only variable that we don't need for
776 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
778 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
780 my $arg = 'git-config';
781 $arg .= ' --int' if ($o =~ /[:=]i$/);
782 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
783 if (ref $v eq 'ARRAY') {
784 chomp(my @tmp = `$arg --get-all svn.$key`);
787 chomp(my $tmp = `$arg --get svn.$key`);
788 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
793 delete @$opts{@config_only} if @config_only;
796 sub extract_metadata {
797 my $id = shift or return (undef, undef, undef);
798 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
800 if (!defined $rev || !$uuid || !$url) {
801 # some of the original repositories I made had
802 # identifiers like this:
803 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
805 return ($url, $rev, $uuid);
809 return extract_metadata((grep(/^git-svn-id: /,
810 command(qw/cat-file commit/, shift)))[-1]);
813 sub working_head_info {
814 my ($head, $refs) = @_;
815 my @args = ('log', '--no-color', '--first-parent');
816 my ($fh, $ctx) = command_output_pipe(@args, $head);
820 if ( m{^commit ($::sha1)$} ) {
821 unshift @$refs, $hash if $hash and $refs;
825 next unless s{^\s*(git-svn-id:)}{$1};
826 my ($url, $rev, $uuid) = extract_metadata($_);
827 if (defined $url && defined $rev) {
828 next if $max{$url} and $max{$url} < $rev;
829 if (my $gs = Git::SVN->find_by_url($url)) {
830 my $c = $gs->rev_db_get($rev);
831 if ($c && $c eq $hash) {
832 close $fh; # break the pipe
833 return ($url, $rev, $uuid, $gs);
835 $max{$url} ||= $gs->rev_db_max;
840 command_close_pipe($fh, $ctx);
841 (undef, undef, undef, undef);
844 sub read_commit_parents {
845 my ($parents, $c) = @_;
846 my ($fh, $ctx) = command_output_pipe(qw/cat-file commit/, $c);
850 /^parent ($sha1)/ or next;
851 push @{$parents->{$c}}, $1;
853 close $fh; # break the pipe
856 sub linearize_history {
857 my ($gs, $refs) = @_;
859 foreach my $c (@$refs) {
860 read_commit_parents(\%parents, $c);
865 my $last_svn_commit = $gs->last_commit;
866 foreach my $c (reverse @$refs) {
867 next if $c eq $last_svn_commit;
870 unshift @linear_refs, $c;
873 # we only want the first parent to diff against for linear
874 # history, we save the rest to inject when we finalize the
876 my $fp_a = verify_ref("$c~1");
877 my $fp_b = shift @{$parents{$c}} if $parents{$c};
878 if (!$fp_a || !$fp_b) {
880 "has no parent commit, and therefore ",
881 "nothing to diff against.\n",
882 "You should be working from a repository ",
883 "originally created by git-svn\n";
885 if ($fp_a ne $fp_b) {
886 die "$c~1 = $fp_a, however parsing commit $c ",
887 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
890 foreach my $p (@{$parents{$c}}) {
894 (\@linear_refs, \%parents);
900 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
901 $_repack $_repack_flags $_use_svm_props $_head
902 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
904 use File::Path qw/mkpath/;
905 use File::Copy qw/copy/;
909 # properties that we do not log:
912 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
913 svn:special svn:executable
914 svn:entry:committed-rev
915 svn:entry:last-author
917 svn:entry:committed-date/;
919 # some options are read globally, but can be overridden locally
920 # per [svn-remote "..."] section. Command-line options will *NOT*
921 # override options set in an [svn-remote "..."] section
923 for my $option (qw/follow_parent no_metadata use_svm_props
924 use_svnsync_props/) {
927 my $prop = "-$option";
930 return $self->{$prop} if exists $self->{$prop};
931 my $k = "svn-remote.$self->{repo_id}.$key";
932 eval { command_oneline(qw/config --get/, $k) };
934 $self->{$prop} = ${"Git::SVN::_$option"};
936 my $v = command_oneline(qw/config --bool/,$k);
937 $self->{$prop} = $v eq 'false' ? 0 : 1;
939 return $self->{$prop};
945 END { unlink keys %LOCKFILES if %LOCKFILES }
947 sub resolve_local_globs {
948 my ($url, $fetch, $glob_spec) = @_;
949 return unless defined $glob_spec;
950 my $ref = $glob_spec->{ref};
951 my $path = $glob_spec->{path};
952 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
953 next unless m#^refs/remotes/$ref->{regex}$#;
955 my $pathname = desanitize_refname($path->full_path($p));
956 my $refname = desanitize_refname($ref->full_path($p));
957 if (my $existing = $fetch->{$pathname}) {
958 if ($existing ne $refname) {
959 die "Refspec conflict:\n",
960 "existing: refs/remotes/$existing\n",
961 " globbed: refs/remotes/$refname\n";
963 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
964 $u =~ s!^\Q$url\E(/|$)!! or die
965 "refs/remotes/$refname: '$url' not found in '$u'\n";
966 if ($pathname ne $u) {
967 warn "W: Refspec glob conflict ",
968 "(ref: refs/remotes/$refname):\n",
969 "expected path: $pathname\n",
971 "Continuing ahead with $u\n";
975 $fetch->{$pathname} = $refname;
980 sub parse_revision_argument {
981 my ($base, $head) = @_;
982 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
983 return ($base, $head);
985 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
986 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
987 return ($head, $head) if ($::_revision eq 'HEAD');
988 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
989 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
990 die "revision argument: $::_revision not understood by git-svn\n";
994 my ($repo_id, $remotes) = @_;
998 $repo_id = $gs->{repo_id};
1000 $remotes ||= read_all_remotes();
1001 my $remote = $remotes->{$repo_id} or
1002 die "[svn-remote \"$repo_id\"] unknown\n";
1003 my $fetch = $remote->{fetch};
1004 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1006 my $ra = Git::SVN::Ra->new($url);
1007 my $uuid = $ra->get_uuid;
1008 my $head = $ra->get_latest_revnum;
1009 my $base = defined $fetch ? $head : 0;
1011 # read the max revs for wildcard expansion (branches/*, tags/*)
1012 foreach my $t (qw/branches tags/) {
1013 defined $remote->{$t} or next;
1014 push @globs, $remote->{$t};
1015 my $max_rev = eval { tmp_config(qw/--int --get/,
1016 "svn-remote.$repo_id.${t}-maxRev") };
1017 if (defined $max_rev && ($max_rev < $base)) {
1019 } elsif (!defined $max_rev) {
1025 foreach my $p (sort keys %$fetch) {
1026 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1027 my $lr = $gs->rev_db_max;
1029 $base = $lr if ($lr < $base);
1035 ($base, $head) = parse_revision_argument($base, $head);
1036 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1039 sub read_all_remotes {
1041 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1042 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1043 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1044 $local_ref =~ s{^/}{};
1045 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1046 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1047 $r->{$1}->{url} = $2;
1048 } elsif (m!^(.+)\.(branches|tags)=
1049 (.*):refs/remotes/(.+)\s*$/!x) {
1050 my ($p, $g) = ($3, $4);
1051 my $rs = $r->{$1}->{$2} = {
1054 path => Git::SVN::GlobSpec->new($p),
1055 ref => Git::SVN::GlobSpec->new($g) };
1056 if (length($rs->{ref}->{right}) != 0) {
1057 die "The '*' glob character must be the last ",
1058 "character of '$g'\n";
1066 if (defined $_repack) {
1067 $_repack = 1000 if ($_repack <= 0);
1068 $_repack_nr = $_repack;
1069 $_repack_flags ||= '-d';
1073 sub verify_remotes_sanity {
1074 return unless -d $ENV{GIT_DIR};
1076 foreach (command(qw/config -l/)) {
1077 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1079 die "Remote ref refs/remote/$1 is tracked by",
1080 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1081 "Please resolve this ambiguity in ",
1082 "your git configuration file before ",
1090 # we allow more chars than remotes2config.sh...
1091 sub sanitize_remote_name {
1093 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1097 sub find_existing_remote {
1098 my ($url, $remotes) = @_;
1099 return undef if $no_reuse_existing;
1101 foreach my $repo_id (keys %$remotes) {
1102 my $u = $remotes->{$repo_id}->{url} or next;
1104 $existing = $repo_id;
1110 sub init_remote_config {
1111 my ($self, $url, $no_write) = @_;
1112 $url =~ s!/+$!!; # strip trailing slash
1113 my $r = read_all_remotes();
1114 my $existing = find_existing_remote($url, $r);
1116 unless ($no_write) {
1117 print STDERR "Using existing ",
1118 "[svn-remote \"$existing\"]\n";
1120 $self->{repo_id} = $existing;
1121 } elsif ($_minimize_url) {
1122 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1123 $existing = find_existing_remote($min_url, $r);
1125 unless ($no_write) {
1126 print STDERR "Using existing ",
1127 "[svn-remote \"$existing\"]\n";
1129 $self->{repo_id} = $existing;
1131 if ($min_url ne $url) {
1132 unless ($no_write) {
1133 print STDERR "Using higher level of URL: ",
1134 "$url => $min_url\n";
1136 my $old_path = $self->{path};
1137 $self->{path} = $url;
1138 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1139 if (length $old_path) {
1140 $self->{path} .= "/$old_path";
1147 # verify that we aren't overwriting anything:
1149 command_oneline('config', '--get',
1150 "svn-remote.$self->{repo_id}.url")
1152 if ($orig_url && ($orig_url ne $url)) {
1153 die "svn-remote.$self->{repo_id}.url already set: ",
1154 "$orig_url\nwanted to set to: $url\n";
1157 my ($xrepo_id, $xpath) = find_ref($self->refname);
1158 if (defined $xpath) {
1159 die "svn-remote.$xrepo_id.fetch already set to track ",
1160 "$xpath:refs/remotes/", $self->refname, "\n";
1162 unless ($no_write) {
1163 command_noisy('config',
1164 "svn-remote.$self->{repo_id}.url", $url);
1165 $self->{path} =~ s{^/}{};
1166 command_noisy('config', '--add',
1167 "svn-remote.$self->{repo_id}.fetch",
1168 "$self->{path}:".$self->refname);
1170 $self->{url} = $url;
1173 sub find_by_url { # repos_root and, path are optional
1174 my ($class, $full_url, $repos_root, $path) = @_;
1176 return undef unless defined $full_url;
1177 remove_username($full_url);
1178 remove_username($repos_root) if defined $repos_root;
1179 my $remotes = read_all_remotes();
1180 if (defined $full_url && defined $repos_root && !defined $path) {
1182 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1184 foreach my $repo_id (keys %$remotes) {
1185 my $u = $remotes->{$repo_id}->{url} or next;
1186 remove_username($u);
1187 next if defined $repos_root && $repos_root ne $u;
1189 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1190 foreach (qw/branches tags/) {
1191 resolve_local_globs($u, $fetch,
1192 $remotes->{$repo_id}->{$_});
1195 unless (defined $p) {
1197 $p =~ s#^\Q$u\E(?:/|$)## or next;
1199 foreach my $f (keys %$fetch) {
1201 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1208 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1209 my $self = _new($class, $repo_id, $ref_id, $path);
1211 $self->init_remote_config($url, $no_write);
1218 foreach (command(qw/config -l/)) {
1219 next unless m!^svn-remote\.(.+)\.fetch=
1220 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1221 my ($repo_id, $path, $ref) = ($1, $2, $3);
1222 if ($ref eq $ref_id) {
1223 $path = '' if ($path =~ m#^\./?#);
1224 return ($repo_id, $path);
1227 (undef, undef, undef);
1231 my ($class, $ref_id, $repo_id, $path) = @_;
1232 if (defined $ref_id && !defined $repo_id && !defined $path) {
1233 ($repo_id, $path) = find_ref($ref_id);
1234 if (!defined $repo_id) {
1235 die "Could not find a \"svn-remote.*.fetch\" key ",
1236 "in the repository configuration matching: ",
1237 "refs/remotes/$ref_id\n";
1240 my $self = _new($class, $repo_id, $ref_id, $path);
1241 if (!defined $self->{path} || !length $self->{path}) {
1242 my $fetch = command_oneline('config', '--get',
1243 "svn-remote.$repo_id.fetch",
1244 ":refs/remotes/$ref_id\$") or
1245 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1246 "\":refs/remotes/$ref_id\$\" in config\n";
1247 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1249 $self->{url} = command_oneline('config', '--get',
1250 "svn-remote.$repo_id.url") or
1251 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1257 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1259 # It cannot end with a slash /, we'll throw up on this because
1260 # SVN can't have directories with a slash in their name, either:
1261 if ($refname =~ m{/$}) {
1262 die "ref: '$refname' ends with a trailing slash, this is ",
1263 "not permitted by git nor Subversion\n";
1266 # It cannot have ASCII control character space, tilde ~, caret ^,
1267 # colon :, question-mark ?, asterisk *, space, or open bracket [
1270 # Additionally, % must be escaped because it is used for escaping
1271 # and we want our escaped refname to be reversible
1272 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1274 # no slash-separated component can begin with a dot .
1276 $refname =~ s{/\.}{/%2E}g;
1278 # It cannot have two consecutive dots .. anywhere
1280 $refname =~ s{\.\.}{%2E%2E}g;
1285 sub desanitize_refname {
1287 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1293 return $self->{svm}->{uuid} if $self->svm;
1295 unless ($self->{svm}) {
1296 die "SVM UUID not cached, and reading remotely failed\n";
1298 $self->{svm}->{uuid};
1303 return $self->{svm} if $self->{svm};
1305 # see if we have it in our config, first:
1307 my $section = "svn-remote.$self->{repo_id}";
1309 source => tmp_config('--get', "$section.svm-source"),
1310 uuid => tmp_config('--get', "$section.svm-uuid"),
1311 replace => tmp_config('--get', "$section.svm-replace"),
1314 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1315 $self->{svm} = $svm;
1321 my ($self, $ra) = @_;
1322 return $ra if $self->svm;
1324 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1325 "(svm:source, svm:uuid) ",
1326 "from the following URLs:\n" );
1327 sub read_svm_props {
1328 my ($self, $ra, $path, $r) = @_;
1329 my $props = ($ra->get_dir($path, $r))[2];
1330 my $src = $props->{'svm:source'};
1331 my $uuid = $props->{'svm:uuid'};
1332 return undef if (!$src || !$uuid);
1336 $uuid =~ m{^[0-9a-f\-]{30,}$}
1337 or die "doesn't look right - svm:uuid is '$uuid'\n";
1339 # the '!' is used to mark the repos_root!/relative/path
1340 $src =~ s{/?!/?}{/};
1341 $src =~ s{/+$}{}; # no trailing slashes please
1342 # username is of no interest
1343 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1345 my $replace = $ra->{url};
1346 $replace .= "/$path" if length $path;
1348 my $section = "svn-remote.$self->{repo_id}";
1349 tmp_config("$section.svm-source", $src);
1350 tmp_config("$section.svm-replace", $replace);
1351 tmp_config("$section.svm-uuid", $uuid);
1359 my $r = $ra->get_latest_revnum;
1360 my $path = $self->{path};
1362 while (length $path) {
1363 unless ($tried{"$self->{url}/$path"}) {
1364 return $ra if $self->read_svm_props($ra, $path, $r);
1365 $tried{"$self->{url}/$path"} = 1;
1367 $path =~ s#/?[^/]+$##;
1369 die "Path: '$path' should be ''\n" if $path ne '';
1370 return $ra if $self->read_svm_props($ra, $path, $r);
1371 $tried{"$self->{url}/$path"} = 1;
1373 if ($ra->{repos_root} eq $self->{url}) {
1374 die @err, (map { " $_\n" } keys %tried), "\n";
1377 # nope, make sure we're connected to the repository root:
1380 $path = $ra->{svn_path};
1381 $ra = Git::SVN::Ra->new($ra->{repos_root});
1382 while (length $path) {
1383 unless ($tried{"$ra->{url}/$path"}) {
1384 $ok = $self->read_svm_props($ra, $path, $r);
1386 $tried{"$ra->{url}/$path"} = 1;
1388 $path =~ s#/?[^/]+$##;
1390 die "Path: '$path' should be ''\n" if $path ne '';
1391 $ok ||= $self->read_svm_props($ra, $path, $r);
1392 $tried{"$ra->{url}/$path"} = 1;
1394 die @err, (map { " $_\n" } keys %tried), "\n";
1396 Git::SVN::Ra->new($self->{url});
1401 return $self->{svnsync} if $self->{svnsync};
1403 if ($self->no_metadata) {
1404 die "Can't have both 'noMetadata' and ",
1405 "'useSvnsyncProps' options set!\n";
1407 if ($self->rewrite_root) {
1408 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1413 # see if we have it in our config, first:
1415 my $section = "svn-remote.$self->{repo_id}";
1417 url => tmp_config('--get', "$section.svnsync-url"),
1418 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1421 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1422 return $self->{svnsync} = $svnsync;
1425 my $err = "useSvnsyncProps set, but failed to read " .
1426 "svnsync property: svn:sync-from-";
1427 my $rp = $self->ra->rev_proplist(0);
1429 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1430 $url =~ m{^[a-z\+]+://} or
1431 die "doesn't look right - svn:sync-from-url is '$url'\n";
1433 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1434 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1435 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1437 my $section = "svn-remote.$self->{repo_id}";
1438 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1439 tmp_config('--add', "$section.svnsync-url", $url);
1440 return $self->{svnsync} = { url => $url, uuid => $uuid };
1443 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1444 # remote lookup (useful for 'git svn log').
1447 unless ($self->{ra_uuid}) {
1448 my $key = "svn-remote.$self->{repo_id}.uuid";
1449 my $uuid = eval { tmp_config('--get', $key) };
1450 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1451 $self->{ra_uuid} = $uuid;
1453 die "ra_uuid called without URL\n" unless $self->{url};
1454 $self->{ra_uuid} = $self->ra->get_uuid;
1455 tmp_config('--add', $key, $self->{ra_uuid});
1463 my $ra = Git::SVN::Ra->new($self->{url});
1464 if ($self->use_svm_props && !$self->{svm}) {
1465 if ($self->no_metadata) {
1466 die "Can't have both 'noMetadata' and ",
1467 "'useSvmProps' options set!\n";
1468 } elsif ($self->use_svnsync_props) {
1469 die "Can't have both 'useSvnsyncProps' and ",
1470 "'useSvmProps' options set!\n";
1472 $ra = $self->_set_svm_vars($ra);
1473 $self->{-want_revprops} = 1;
1480 my $repos_root = $self->ra->{repos_root};
1481 return $self->{path} if ($self->{url} eq $repos_root);
1482 my $url = $self->{url} .
1483 (length $self->{path} ? "/$self->{path}" : $self->{path});
1484 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1488 sub traverse_ignore {
1489 my ($self, $fh, $path, $r) = @_;
1492 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1494 $p =~ s#^\Q$self->{path}\E(/|$)##;
1495 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1496 if (my $s = $props->{'svn:ignore'}) {
1497 $s =~ s/[\r\n]+/\n/g;
1499 if (length $p == 0) {
1503 $s =~ s#\n#\n/$p/#g;
1504 print $fh "/$p/$s\n";
1507 foreach (sort keys %$dirent) {
1508 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1509 $self->traverse_ignore($fh, "$path/$_", $r);
1513 sub last_rev { ($_[0]->last_rev_commit)[0] }
1514 sub last_commit { ($_[0]->last_rev_commit)[1] }
1516 # returns the newest SVN revision number and newest commit SHA1
1517 sub last_rev_commit {
1519 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1520 return ($self->{last_rev}, $self->{last_commit});
1522 my $c = ::verify_ref($self->refname.'^0');
1523 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1524 my $rev = (::cmt_metadata($c))[1];
1526 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1530 my $db_path = $self->db_path;
1531 unless (-e $db_path) {
1532 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1533 return (undef, undef);
1535 my $offset = -41; # from tail
1537 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1538 sysseek($fh, $offset, 2); # don't care for errors
1539 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1541 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1543 sysseek($fh, $offset, 2); # don't care for errors
1544 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1547 if ($c && $c ne $rl) {
1548 die "$db_path and ", $self->refname,
1549 " inconsistent!:\n$c != $rl\n";
1551 my $rev = sysseek($fh, 0, 1) or croak $!;
1552 $rev = ($rev - 41) / 41;
1553 close $fh or croak $!;
1554 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1558 sub get_fetch_range {
1559 my ($self, $min, $max) = @_;
1560 $max ||= $self->ra->get_latest_revnum;
1561 $min ||= $self->rev_db_max;
1567 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1568 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1569 if (! -f $config && -f $old_def_config) {
1570 rename $old_def_config, $config or
1571 die "Failed rename $old_def_config => $config: $!\n";
1573 my $old_config = $ENV{GIT_CONFIG};
1574 $ENV{GIT_CONFIG} = $config;
1577 unless (-f $config) {
1579 open my $fh, '>', $config or
1580 die "Can't open $config: $!\n";
1581 print $fh "; This file is used internally by ",
1583 "Couldn't write to $config: $!\n";
1584 print $fh "; You should not have to edit it\n" or
1585 die "Couldn't write to $config: $!\n";
1586 close $fh or die "Couldn't close $config: $!\n";
1588 command('config', @args);
1591 if (defined $old_config) {
1592 $ENV{GIT_CONFIG} = $old_config;
1594 delete $ENV{GIT_CONFIG};
1597 wantarray ? @ret : $ret[0];
1601 my ($self, $sub) = @_;
1602 my $old_index = $ENV{GIT_INDEX_FILE};
1603 $ENV{GIT_INDEX_FILE} = $self->{index};
1606 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1607 mkpath([$dir]) unless -d $dir;
1611 if (defined $old_index) {
1612 $ENV{GIT_INDEX_FILE} = $old_index;
1614 delete $ENV{GIT_INDEX_FILE};
1617 wantarray ? @ret : $ret[0];
1620 sub assert_index_clean {
1621 my ($self, $treeish) = @_;
1623 $self->tmp_index_do(sub {
1624 command_noisy('read-tree', $treeish) unless -e $self->{index};
1625 my $x = command_oneline('write-tree');
1626 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1627 /^tree ($::sha1)/mo);
1630 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1631 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1632 command_noisy('read-tree', $treeish);
1633 $x = command_oneline('write-tree');
1635 ::fatal "trees ($treeish) $y != $x\n",
1636 "Something is seriously wrong...\n";
1641 sub get_commit_parents {
1642 my ($self, $log_entry) = @_;
1643 my (%seen, @ret, @tmp);
1644 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1645 if (my $ip = $self->{inject_parents}) {
1646 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1650 if (my $cur = ::verify_ref($self->refname.'^0')) {
1653 if (my $ipd = $self->{inject_parents_dcommit}) {
1654 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1655 push @tmp, @$commit;
1658 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1659 while (my $p = shift @tmp) {
1663 # MAXPARENT is defined to 16 in commit-tree.c:
1667 die "r$log_entry->{revision}: No room for parents:\n\t",
1668 join("\n\t", @tmp), "\n";
1675 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1676 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1677 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1680 if ($rwr !~ m#^[a-z\+]+://#) {
1681 die "$rwr is not a valid URL (key: $k)\n";
1684 $self->{-rewrite_root} = $rwr;
1689 ($self->rewrite_root || $self->{url}) .
1690 (length $self->{path} ? '/' . $self->{path} : '');
1695 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1699 my ($self, $log_entry) = @_;
1700 my $lr = $self->last_rev;
1701 if (defined $lr && $lr >= $log_entry->{revision}) {
1702 die "Last fetched revision of ", $self->refname,
1703 " was r$lr, but we are about to fetch: ",
1704 "r$log_entry->{revision}!\n";
1706 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1707 croak "$log_entry->{revision} = $c already exists! ",
1708 "Why are we refetching it?\n";
1710 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1711 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1712 $log_entry->{email};
1713 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1715 my $tree = $log_entry->{tree};
1716 if (!defined $tree) {
1717 $tree = $self->tmp_index_do(sub {
1718 command_oneline('write-tree') });
1720 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1722 my @exec = ('git-commit-tree', $tree);
1723 foreach ($self->get_commit_parents($log_entry)) {
1724 push @exec, '-p', $_;
1726 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1728 print $msg_fh $log_entry->{log} or croak $!;
1729 unless ($self->no_metadata) {
1730 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1733 $msg_fh->flush == 0 or croak $!;
1734 close $msg_fh or croak $!;
1735 chomp(my $commit = do { local $/; <$out_fh> });
1736 close $out_fh or croak $!;
1739 if ($commit !~ /^$::sha1$/o) {
1740 die "Failed to commit, invalid sha1: $commit\n";
1743 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1745 $self->{last_rev} = $log_entry->{revision};
1746 $self->{last_commit} = $commit;
1747 print "r$log_entry->{revision}";
1748 if (defined $log_entry->{svm_revision}) {
1749 print " (\@$log_entry->{svm_revision})";
1750 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1751 0, $self->svm_uuid);
1753 print " = $commit ($self->{ref_id})\n";
1754 if (defined $_repack && (--$_repack_nr == 0)) {
1755 $_repack_nr = $_repack;
1756 # repack doesn't use any arguments with spaces in them, does it?
1757 print "Running git repack $_repack_flags ...\n";
1758 command_noisy('repack', split(/\s+/, $_repack_flags));
1759 print "Done repacking\n";
1765 my ($self, $paths, $r) = @_;
1766 return 1 if $self->{path} eq '';
1767 if (my $path = $paths->{"/$self->{path}"}) {
1768 return ($path->{action} eq 'D') ? 0 : 1;
1770 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1771 if (grep /$self->{path_regex}/, keys %$paths) {
1775 foreach (split m#/#, $self->{path}) {
1777 next unless ($paths->{$c} &&
1778 ($paths->{$c}->{action} =~ /^[AR]$/));
1779 if ($self->ra->check_path($self->{path}, $r) ==
1787 sub find_parent_branch {
1788 my ($self, $paths, $rev) = @_;
1789 return undef unless $self->follow_parent;
1790 unless (defined $paths) {
1791 my $err_handler = $SVN::Error::handler;
1792 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1793 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1795 Git::SVN::Ra::dup_changed_paths($_[0]) });
1796 $SVN::Error::handler = $err_handler;
1798 return undef unless defined $paths;
1800 # look for a parent from another branch:
1801 my @b_path_components = split m#/#, $self->rel_path;
1802 my @a_path_components;
1804 while (@b_path_components) {
1805 $i = $paths->{'/'.join('/', @b_path_components)};
1806 last if $i && defined $i->{copyfrom_path};
1807 unshift(@a_path_components, pop(@b_path_components));
1809 return undef unless defined $i && defined $i->{copyfrom_path};
1810 my $branch_from = $i->{copyfrom_path};
1811 if (@a_path_components) {
1812 print STDERR "branch_from: $branch_from => ";
1813 $branch_from .= '/'.join('/', @a_path_components);
1814 print STDERR $branch_from, "\n";
1816 my $r = $i->{copyfrom_rev};
1817 my $repos_root = $self->ra->{repos_root};
1818 my $url = $self->ra->{url};
1819 my $new_url = $repos_root . $branch_from;
1820 print STDERR "Found possible branch point: ",
1821 "$new_url => ", $self->full_url, ", $r\n";
1822 $branch_from =~ s#^/##;
1823 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1825 my $ref_id = $self->{ref_id};
1826 $ref_id =~ s/\@\d+$//;
1828 # just grow a tail if we're not unique enough :x
1829 $ref_id .= '-' while find_ref($ref_id);
1830 print STDERR "Initializing parent: $ref_id\n";
1831 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1833 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1834 if (!defined $r0 || !defined $parent) {
1835 my ($base, $head) = parse_revision_argument(0, $r);
1837 $gs->fetch($base, $r);
1839 ($r0, $parent) = $gs->last_rev_commit;
1841 if (defined $r0 && defined $parent) {
1842 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1844 if ($self->ra->can_do_switch) {
1845 $self->assert_index_clean($parent);
1846 print STDERR "Following parent with do_switch\n";
1847 # do_switch works with svn/trunk >= r22312, but that
1848 # is not included with SVN 1.4.3 (the latest version
1849 # at the moment), so we can't rely on it
1850 $self->{last_commit} = $parent;
1851 $ed = SVN::Git::Fetcher->new($self);
1852 $gs->ra->gs_do_switch($r0, $rev, $gs,
1853 $self->full_url, $ed)
1854 or die "SVN connection failed somewhere...\n";
1856 print STDERR "Following parent with do_update\n";
1857 $ed = SVN::Git::Fetcher->new($self);
1858 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1859 or die "SVN connection failed somewhere...\n";
1861 print STDERR "Successfully followed parent\n";
1862 return $self->make_log_entry($rev, [$parent], $ed);
1868 my ($self, $paths, $rev) = @_;
1870 my ($last_rev, @parents);
1871 if (my $lc = $self->last_commit) {
1872 # we can have a branch that was deleted, then re-added
1873 # under the same name but copied from another path, in
1874 # which case we'll have multiple parents (we don't
1875 # want to break the original ref, nor lose copypath info):
1876 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1877 push @{$log_entry->{parents}}, $lc;
1880 $ed = SVN::Git::Fetcher->new($self);
1881 $last_rev = $self->{last_rev};
1886 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1889 $ed = SVN::Git::Fetcher->new($self);
1891 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1892 die "SVN connection failed somewhere...\n";
1894 $self->make_log_entry($rev, \@parents, $ed);
1898 my ($self, $ed) = @_;
1900 my $h = $ed->{empty};
1901 foreach (sort keys %$h) {
1902 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1903 push @out, " $act: " . uri_encode($_);
1904 warn "W: $act: $_\n";
1906 foreach my $t (qw/dir_prop file_prop/) {
1907 $h = $ed->{$t} or next;
1908 foreach my $path (sort keys %$h) {
1909 my $ppath = $path eq '' ? '.' : $path;
1910 foreach my $prop (sort keys %{$h->{$path}}) {
1911 next if $SKIP_PROP{$prop};
1912 my $v = $h->{$path}->{$prop};
1913 my $t_ppath_prop = "$t: " .
1914 uri_encode($ppath) . ' ' .
1917 push @out, " +$t_ppath_prop " .
1920 push @out, " -$t_ppath_prop";
1925 foreach my $t (qw/absent_file absent_directory/) {
1926 $h = $ed->{$t} or next;
1927 foreach my $parent (sort keys %$h) {
1928 foreach my $path (sort @{$h->{$parent}}) {
1929 push @out, " $t: " .
1930 uri_encode("$parent/$path");
1931 warn "W: $t: $parent/$path ",
1932 "Insufficient permissions?\n";
1939 sub parse_svn_date {
1940 my $date = shift || return '+0000 1970-01-01 00:00:00';
1941 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1942 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1943 croak "Unable to parse date: $date\n";
1944 "+0000 $Y-$m-$d $H:$M:$S";
1949 if (!defined $author || length $author == 0) {
1950 $author = '(no author)';
1952 if (defined $::_authors && ! defined $::users{$author}) {
1953 die "Author: $author not defined in $::_authors file\n";
1958 sub make_log_entry {
1959 my ($self, $rev, $parents, $ed) = @_;
1960 my $untracked = $self->get_untracked($ed);
1962 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1963 print $un "r$rev\n" or croak $!;
1964 print $un $_, "\n" foreach @$untracked;
1965 my %log_entry = ( parents => $parents || [], revision => $rev,
1969 my $logged = delete $self->{logged_rev_props};
1970 if (!$logged || $self->{-want_revprops}) {
1971 my $rp = $self->ra->rev_proplist($rev);
1972 foreach (sort keys %$rp) {
1974 if (/^svn:(author|date|log)$/) {
1975 $log_entry{$1} = $v;
1976 } elsif ($_ eq 'svm:headrev') {
1979 print $un " rev_prop: ", uri_encode($_), ' ',
1980 uri_encode($v), "\n";
1984 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1986 close $un or croak $!;
1988 $log_entry{date} = parse_svn_date($log_entry{date});
1989 $log_entry{log} .= "\n";
1990 my $author = $log_entry{author} = check_author($log_entry{author});
1991 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1993 if (defined $headrev && $self->use_svm_props) {
1994 if ($self->rewrite_root) {
1995 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1998 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1999 # we don't want "SVM: initializing mirror for junk" ...
2000 return undef if $r == 0;
2001 my $svm = $self->svm;
2002 if ($uuid ne $svm->{uuid}) {
2003 die "UUID mismatch on SVM path:\n",
2004 "expected: $svm->{uuid}\n",
2007 my $full_url = $self->full_url;
2008 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2009 die "Failed to replace '$svm->{replace}' with ",
2010 "'$svm->{source}' in $full_url\n";
2011 # throw away username for storing in records
2012 remove_username($full_url);
2013 $log_entry{metadata} = "$full_url\@$r $uuid";
2014 $log_entry{svm_revision} = $r;
2015 $email ||= "$author\@$uuid"
2016 } elsif ($self->use_svnsync_props) {
2017 my $full_url = $self->svnsync->{url};
2018 $full_url .= "/$self->{path}" if length $self->{path};
2019 remove_username($full_url);
2020 my $uuid = $self->svnsync->{uuid};
2021 $log_entry{metadata} = "$full_url\@$rev $uuid";
2022 $email ||= "$author\@$uuid"
2024 my $url = $self->metadata_url;
2025 remove_username($url);
2026 $log_entry{metadata} = "$url\@$rev " .
2027 $self->ra->get_uuid;
2028 $email ||= "$author\@" . $self->ra->get_uuid;
2030 $log_entry{name} = $name;
2031 $log_entry{email} = $email;
2036 my ($self, $min_rev, $max_rev, @parents) = @_;
2037 my ($last_rev, $last_commit) = $self->last_rev_commit;
2038 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2039 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2043 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2044 $self->{inject_parents} = { $rev => $tree };
2045 $self->fetch(undef, undef);
2049 my ($self, $tree) = (shift, shift);
2050 my $log_entry = ::get_commit_entry($tree);
2051 unless ($self->{last_rev}) {
2052 fatal("Must have an existing revision to commit\n");
2054 my %ed_opts = ( r => $self->{last_rev},
2055 log => $log_entry->{log},
2057 tree_a => $self->{last_commit},
2060 $self->set_tree_cb($log_entry, $tree, @_) },
2061 svn_path => $self->{path} );
2062 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2063 print "No changes\nr$self->{last_rev} = $tree\n";
2069 my $db_path = $self->db_path;
2070 return if (-e $db_path && ! -z $db_path);
2071 return unless ::verify_ref($self->refname.'^0');
2072 if (-f $self->{db_root}) {
2073 rename $self->{db_root}, $db_path or die
2074 "rename $self->{db_root} => $db_path failed: $!\n";
2075 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2076 symlink $base, $self->{db_root} or die
2077 "symlink $base => $self->{db_root} failed: $!\n";
2080 print "Rebuilding $db_path ...\n";
2081 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2083 my $full_url = $self->full_url;
2084 remove_username($full_url);
2088 if ( m{^commit ($::sha1)$} ) {
2092 next unless s{^\s*(git-svn-id:)}{$1};
2093 my ($url, $rev, $uuid) = ::extract_metadata($_);
2094 remove_username($url);
2096 # ignore merges (from set-tree)
2097 next if (!defined $rev || !$uuid);
2099 # if we merged or otherwise started elsewhere, this is
2100 # how we break out of it
2101 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2102 ($full_url && $url && ($url ne $full_url))) {
2106 $svn_uuid ||= $uuid;
2108 $self->rev_db_set($rev, $c);
2109 print "r$rev = $c\n";
2111 command_close_pipe($log, $ctx);
2112 print "Done rebuilding $db_path\n";
2116 # Tie::File seems to be prone to offset errors if revisions get sparse,
2117 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2118 # one of my favorite modules is out :< Next up would be one of the DBM
2119 # modules, but I'm not sure which is most portable... So I'll just
2120 # go with something that's plain-text, but still capable of
2121 # being randomly accessed. So here's my ultra-simple fixed-width
2122 # database. All records are 40 characters + "\n", so it's easy to seek
2123 # to a revision: (41 * rev) is the byte offset.
2124 # A record of 40 0s denotes an empty revision.
2125 # And yes, it's still pretty fast (faster than Tie::File).
2126 # These files are disposable unless noMetadata or useSvmProps is set
2129 my ($fh, $rev, $commit) = @_;
2130 my $offset = $rev * 41;
2131 # assume that append is the common case:
2132 seek $fh, 0, 2 or croak $!;
2134 if ($pos < $offset) {
2135 for (1 .. (($offset - $pos) / 41)) {
2136 print $fh (('0' x 40),"\n") or croak $!;
2139 seek $fh, $offset, 0 or croak $!;
2140 print $fh $commit,"\n" or croak $!;
2146 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2147 mkpath([$dir]) unless -d $dir;
2148 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2149 close $fh or die "Couldn't close (create) $path: $!\n";
2154 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2155 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2156 my $db = $self->db_path($uuid);
2157 my $db_lock = "$db.lock";
2160 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2161 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2165 $LOCKFILES{$db_lock} = 1;
2167 # both of these options make our .rev_db file very, very important
2168 # and we can't afford to lose it because rebuild() won't work
2169 if ($self->use_svm_props || $self->no_metadata) {
2171 copy($db, $db_lock) or die "rev_db_set(@_): ",
2173 "$db => $db_lock ($!)\n";
2175 rename $db, $db_lock or die "rev_db_set(@_): ",
2176 "Failed to rename: ",
2177 "$db => $db_lock ($!)\n";
2179 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2180 _rev_db_set($fh, $rev, $commit);
2182 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2183 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2185 close $fh or croak $!;
2188 command_noisy('update-ref', '-m', "r$rev",
2189 $self->refname, $commit);
2191 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2192 "$db_lock => $db ($!)\n";
2193 delete $LOCKFILES{$db_lock};
2195 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2196 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2197 kill $sig, $$ if defined $sig;
2204 my $db_path = $self->db_path;
2205 my @stat = stat $db_path or return 0;
2206 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2207 my $max = $stat[7] / 41;
2208 (($max > 0) ? $max - 1 : 0);
2212 my ($self, $rev, $uuid) = @_;
2214 my $offset = $rev * 41;
2215 my $db_path = $self->db_path($uuid);
2216 return undef unless -e $db_path;
2217 open my $fh, '<', $db_path or croak $!;
2218 if (sysseek($fh, $offset, 0) == $offset) {
2219 my $read = sysread($fh, $ret, 40);
2220 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2222 close $fh or croak $!;
2226 sub find_rev_before {
2227 my ($self, $rev, $eq_ok) = @_;
2228 --$rev unless $eq_ok;
2230 if (my $c = $self->rev_db_get($rev)) {
2235 return (undef, undef);
2239 my ($class, $repo_id, $ref_id, $path) = @_;
2240 unless (defined $repo_id && length $repo_id) {
2241 $repo_id = $Git::SVN::default_repo_id;
2243 unless (defined $ref_id && length $ref_id) {
2244 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2246 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2247 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2248 $_[3] = $path = '' unless (defined $path);
2249 mkpath(["$ENV{GIT_DIR}/svn"]);
2251 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2252 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2253 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2257 my ($self, $uuid) = @_;
2258 $uuid ||= $self->ra_uuid;
2259 "$self->{db_root}.$uuid";
2264 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2268 sub remove_username {
2269 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2272 package Git::SVN::Prompt;
2276 use vars qw/$_no_auth_cache $_username/;
2279 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2280 $may_save = undef if $_no_auth_cache;
2281 $default_username = $_username if defined $_username;
2282 if (defined $default_username && length $default_username) {
2283 if (defined $realm && length $realm) {
2284 print STDERR "Authentication realm: $realm\n";
2287 $cred->username($default_username);
2289 username($cred, $realm, $may_save, $pool);
2291 $cred->password(_read_password("Password for '" .
2292 $cred->username . "': ", $realm));
2293 $cred->may_save($may_save);
2294 $SVN::_Core::SVN_NO_ERROR;
2297 sub ssl_server_trust {
2298 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2299 $may_save = undef if $_no_auth_cache;
2300 print STDERR "Error validating server certificate for '$realm':\n";
2301 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2302 print STDERR " - The certificate is not issued by a trusted ",
2303 "authority. Use the\n",
2304 " fingerprint to validate the certificate manually!\n";
2306 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2307 print STDERR " - The certificate hostname does not match.\n";
2309 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2310 print STDERR " - The certificate is not yet valid.\n";
2312 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2313 print STDERR " - The certificate has expired.\n";
2315 if ($failures & $SVN::Auth::SSL::OTHER) {
2316 print STDERR " - The certificate has an unknown error.\n";
2319 "Certificate information:\n".
2320 " - Hostname: %s\n".
2321 " - Valid: from %s until %s\n".
2323 " - Fingerprint: %s\n",
2324 map $cert_info->$_, qw(hostname valid_from valid_until
2325 issuer_dname fingerprint);
2328 print STDERR $may_save ?
2329 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2330 "(R)eject or accept (t)emporarily? ";
2332 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2333 if ($choice =~ /^t$/i) {
2334 $cred->may_save(undef);
2335 } elsif ($choice =~ /^r$/i) {
2337 } elsif ($may_save && $choice =~ /^p$/i) {
2338 $cred->may_save($may_save);
2342 $cred->accepted_failures($failures);
2343 $SVN::_Core::SVN_NO_ERROR;
2346 sub ssl_client_cert {
2347 my ($cred, $realm, $may_save, $pool) = @_;
2348 $may_save = undef if $_no_auth_cache;
2349 print STDERR "Client certificate filename: ";
2351 chomp(my $filename = <STDIN>);
2352 $cred->cert_file($filename);
2353 $cred->may_save($may_save);
2354 $SVN::_Core::SVN_NO_ERROR;
2357 sub ssl_client_cert_pw {
2358 my ($cred, $realm, $may_save, $pool) = @_;
2359 $may_save = undef if $_no_auth_cache;
2360 $cred->password(_read_password("Password: ", $realm));
2361 $cred->may_save($may_save);
2362 $SVN::_Core::SVN_NO_ERROR;
2366 my ($cred, $realm, $may_save, $pool) = @_;
2367 $may_save = undef if $_no_auth_cache;
2368 if (defined $realm && length $realm) {
2369 print STDERR "Authentication realm: $realm\n";
2372 if (defined $_username) {
2373 $username = $_username;
2375 print STDERR "Username: ";
2377 chomp($username = <STDIN>);
2379 $cred->username($username);
2380 $cred->may_save($may_save);
2381 $SVN::_Core::SVN_NO_ERROR;
2384 sub _read_password {
2385 my ($prompt, $realm) = @_;
2386 print STDERR $prompt;
2388 require Term::ReadKey;
2389 Term::ReadKey::ReadMode('noecho');
2391 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2392 last if $key =~ /[\012\015]/; # \n\r
2395 Term::ReadKey::ReadMode('restore');
2404 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2405 $SVN::Node::dir.$SVN::Node::unknown.
2406 $SVN::Node::none.$SVN::Node::file.
2407 $SVN::Node::dir.$SVN::Node::unknown.
2408 $SVN::Auth::SSL::CNMISMATCH.
2409 $SVN::Auth::SSL::NOTYETVALID.
2410 $SVN::Auth::SSL::EXPIRED.
2411 $SVN::Auth::SSL::UNKNOWNCA.
2412 $SVN::Auth::SSL::OTHER;
2415 package SVN::Git::Fetcher;
2423 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2425 my ($class, $git_svn) = @_;
2426 my $self = SVN::Delta::Editor->new;
2427 bless $self, $class;
2428 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2429 $self->{empty} = {};
2430 $self->{dir_prop} = {};
2431 $self->{file_prop} = {};
2432 $self->{absent_dir} = {};
2433 $self->{absent_file} = {};
2434 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2438 sub set_path_strip {
2439 my ($self, $path) = @_;
2440 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2447 sub open_directory {
2448 my ($self, $path, $pb, $rev) = @_;
2453 my ($self, $path) = @_;
2454 if ($self->{path_strip}) {
2455 $path =~ s!$self->{path_strip}!! or
2456 die "Failed to strip path '$path' ($self->{path_strip})\n";
2462 my ($self, $path, $rev, $pb) = @_;
2464 my $gpath = $self->git_path($path);
2465 return undef if ($gpath eq '');
2467 # remove entire directories.
2468 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2469 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2471 $self->{c}, '--', $gpath);
2475 $self->{gii}->remove($_);
2476 print "\tD\t$_\n" unless $::_q;
2478 print "\tD\t$gpath/\n" unless $::_q;
2479 command_close_pipe($ls, $ctx);
2480 $self->{empty}->{$path} = 0
2482 $self->{gii}->remove($gpath);
2483 print "\tD\t$gpath\n" unless $::_q;
2489 my ($self, $path, $pb, $rev) = @_;
2490 my $gpath = $self->git_path($path);
2491 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2492 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2493 unless (defined $mode && defined $blob) {
2494 die "$path was not found in commit $self->{c} (r$rev)\n";
2496 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2497 pool => SVN::Pool->new, action => 'M' };
2501 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2502 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2503 delete $self->{empty}->{$dir};
2504 { path => $path, mode_a => 100644, mode_b => 100644,
2505 pool => SVN::Pool->new, action => 'A' };
2509 my ($self, $path, $cp_path, $cp_rev) = @_;
2510 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2511 delete $self->{empty}->{$dir};
2512 $self->{empty}->{$path} = 1;
2516 sub change_dir_prop {
2517 my ($self, $db, $prop, $value) = @_;
2518 $self->{dir_prop}->{$db->{path}} ||= {};
2519 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2523 sub absent_directory {
2524 my ($self, $path, $pb) = @_;
2525 $self->{absent_dir}->{$pb->{path}} ||= [];
2526 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2531 my ($self, $path, $pb) = @_;
2532 $self->{absent_file}->{$pb->{path}} ||= [];
2533 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2537 sub change_file_prop {
2538 my ($self, $fb, $prop, $value) = @_;
2539 if ($prop eq 'svn:executable') {
2540 if ($fb->{mode_b} != 120000) {
2541 $fb->{mode_b} = defined $value ? 100755 : 100644;
2543 } elsif ($prop eq 'svn:special') {
2544 $fb->{mode_b} = defined $value ? 120000 : 100644;
2546 $self->{file_prop}->{$fb->{path}} ||= {};
2547 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2552 sub apply_textdelta {
2553 my ($self, $fb, $exp) = @_;
2554 my $fh = IO::File->new_tmpfile;
2556 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2557 # (but $base does not,) so dup() it for reading in close_file
2558 open my $dup, '<&', $fh or croak $!;
2559 my $base = IO::File->new_tmpfile;
2560 $base->autoflush(1);
2562 defined (my $pid = fork) or croak $!;
2564 open STDOUT, '>&', $base or croak $!;
2565 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2566 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2572 seek $base, 0, 0 or croak $!;
2573 my $md5 = Digest::MD5->new;
2574 $md5->addfile($base);
2575 my $got = $md5->hexdigest;
2576 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2578 " got: $got\n" if ($got ne $exp);
2581 seek $base, 0, 0 or croak $!;
2583 $fb->{base} = $base;
2584 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2588 my ($self, $fb, $exp) = @_;
2590 my $path = $self->git_path($fb->{path});
2591 if (my $fh = $fb->{fh}) {
2593 seek($fh, 0, 0) or croak $!;
2594 my $md5 = Digest::MD5->new;
2596 my $got = $md5->hexdigest;
2598 die "Checksum mismatch: $path\n",
2599 "expected: $exp\n got: $got\n";
2602 sysseek($fh, 0, 0) or croak $!;
2603 if ($fb->{mode_b} == 120000) {
2604 sysread($fh, my $buf, 5) == 5 or croak $!;
2605 $buf eq 'link ' or die "$path has mode 120000",
2606 "but is not a link\n";
2608 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2610 open STDIN, '<&', $fh or croak $!;
2611 exec qw/git-hash-object -w --stdin/ or croak $!;
2613 chomp($hash = do { local $/; <$out> });
2614 close $out or croak $!;
2615 close $fh or croak $!;
2616 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2617 close $fb->{base} or croak $!;
2619 $hash = $fb->{blob} or die "no blob information\n";
2622 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2623 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2629 $self->{nr} = $self->{gii}->{nr};
2630 delete $self->{gii};
2631 $self->SUPER::abort_edit(@_);
2636 $self->{git_commit_ok} = 1;
2637 $self->{nr} = $self->{gii}->{nr};
2638 delete $self->{gii};
2639 $self->SUPER::close_edit(@_);
2642 package SVN::Git::Editor;
2643 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2651 my ($class, $opts) = @_;
2652 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2653 die "$_ required!\n" unless (defined $opts->{$_});
2656 my $pool = SVN::Pool->new;
2657 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2658 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2661 # $opts->{ra} functions should not be used after this:
2662 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2663 $opts->{editor_cb}, $pool);
2664 my $self = SVN::Delta::Editor->new(@ce, $pool);
2665 bless $self, $class;
2666 foreach (qw/svn_path r tree_a tree_b/) {
2667 $self->{$_} = $opts->{$_};
2669 $self->{url} = $opts->{ra}->{url};
2670 $self->{mods} = $mods;
2671 $self->{types} = $types;
2672 $self->{pool} = $pool;
2673 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2675 $self->{path_prefix} = length $self->{svn_path} ?
2676 "$self->{svn_path}/" : '';
2681 my ($tree_a, $tree_b) = @_;
2682 my @diff_tree = qw(diff-tree -z -r);
2683 if ($_cp_similarity) {
2684 push @diff_tree, "-C$_cp_similarity";
2686 push @diff_tree, '-C';
2688 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2689 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2690 push @diff_tree, $tree_a, $tree_b;
2691 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2695 while (<$diff_fh>) {
2696 chomp $_; # this gets rid of the trailing "\0"
2697 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2698 $::sha1\s($::sha1)\s
2699 ([MTCRAD])\d*$/xo) {
2700 push @mods, { mode_a => $1, mode_b => $2,
2701 sha1_b => $3, chg => $4 };
2702 if ($4 =~ /^(?:C|R)$/) {
2707 } elsif ($state eq 'file_a') {
2708 my $x = $mods[$#mods] or croak "Empty array\n";
2709 if ($x->{chg} !~ /^(?:C|R)$/) {
2710 croak "Error parsing $_, $x->{chg}\n";
2714 } elsif ($state eq 'file_b') {
2715 my $x = $mods[$#mods] or croak "Empty array\n";
2716 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2717 croak "Error parsing $_, $x->{chg}\n";
2719 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2720 croak "Error parsing $_, $x->{chg}\n";
2725 croak "Error parsing $_\n";
2728 command_close_pipe($diff_fh, $ctx);
2732 sub check_diff_paths {
2733 my ($ra, $pfx, $rev, $mods) = @_;
2735 $pfx .= '/' if length $pfx;
2737 sub type_diff_paths {
2738 my ($ra, $types, $path, $rev) = @_;
2739 my @p = split m#/+#, $path;
2741 unless (defined $types->{$c}) {
2742 $types->{$c} = $ra->check_path($c, $rev);
2745 $c .= '/' . shift @p;
2746 next if defined $types->{$c};
2747 $types->{$c} = $ra->check_path($c, $rev);
2751 foreach my $m (@$mods) {
2752 foreach my $f (qw/file_a file_b/) {
2753 next unless defined $m->{$f};
2754 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2755 if (length $pfx.$dir && ! defined $types{$dir}) {
2756 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2764 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2768 my ($self, $path) = @_;
2769 $self->{path_prefix}.(defined $path ? $path : '');
2773 my ($self, $path) = @_;
2774 if ($self->{url} =~ m#^https?://#) {
2775 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2777 $self->{url} . '/' . $self->repo_path($path);
2782 my $rm = $self->{rm};
2783 delete $rm->{''}; # we never delete the url we're tracking
2786 foreach (keys %$rm) {
2787 my @d = split m#/#, $_;
2791 $c .= '/' . shift @d;
2795 delete $rm->{$self->{svn_path}};
2796 delete $rm->{''}; # we never delete the url we're tracking
2799 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2804 my @dn = split m#/#, $_;
2806 delete $rm->{join '/', @dn};
2813 command_close_pipe($fh, $ctx);
2815 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2816 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2817 $self->close_directory($bat->{$d}, $p);
2818 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2819 print "\tD+\t$d/\n" unless $::_q;
2820 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2825 sub open_or_add_dir {
2826 my ($self, $full_path, $baton) = @_;
2827 my $t = $self->{types}->{$full_path};
2829 die "$full_path not known in r$self->{r} or we have a bug!\n";
2831 if ($t == $SVN::Node::none) {
2832 return $self->add_directory($full_path, $baton,
2833 undef, -1, $self->{pool});
2834 } elsif ($t == $SVN::Node::dir) {
2835 return $self->open_directory($full_path, $baton,
2836 $self->{r}, $self->{pool});
2838 print STDERR "$full_path already exists in repository at ",
2839 "r$self->{r} and it is not a directory (",
2840 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2845 my ($self, $path) = @_;
2846 my $bat = $self->{bat};
2847 my $repo_path = $self->repo_path($path);
2848 return $bat->{''} unless (length $repo_path);
2849 my @p = split m#/+#, $repo_path;
2851 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2854 $c .= '/' . shift @p;
2855 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2861 my ($self, $m) = @_;
2862 my ($dir, $file) = split_path($m->{file_b});
2863 my $pbat = $self->ensure_path($dir);
2864 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2866 print "\tA\t$m->{file_b}\n" unless $::_q;
2867 $self->chg_file($fbat, $m);
2868 $self->close_file($fbat,undef,$self->{pool});
2872 my ($self, $m) = @_;
2873 my ($dir, $file) = split_path($m->{file_b});
2874 my $pbat = $self->ensure_path($dir);
2875 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2876 $self->url_path($m->{file_a}), $self->{r});
2877 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2878 $self->chg_file($fbat, $m);
2879 $self->close_file($fbat,undef,$self->{pool});
2883 my ($self, $path, $pbat) = @_;
2884 my $rpath = $self->repo_path($path);
2885 my ($dir, $file) = split_path($rpath);
2886 $self->{rm}->{$dir} = 1;
2887 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2891 my ($self, $m) = @_;
2892 my ($dir, $file) = split_path($m->{file_b});
2893 my $pbat = $self->ensure_path($dir);
2894 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2895 $self->url_path($m->{file_a}), $self->{r});
2896 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2897 $self->chg_file($fbat, $m);
2898 $self->close_file($fbat,undef,$self->{pool});
2900 ($dir, $file) = split_path($m->{file_a});
2901 $pbat = $self->ensure_path($dir);
2902 $self->delete_entry($m->{file_a}, $pbat);
2906 my ($self, $m) = @_;
2907 my ($dir, $file) = split_path($m->{file_b});
2908 my $pbat = $self->ensure_path($dir);
2909 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2910 $pbat,$self->{r},$self->{pool});
2911 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2912 $self->chg_file($fbat, $m);
2913 $self->close_file($fbat,undef,$self->{pool});
2916 sub T { shift->M(@_) }
2918 sub change_file_prop {
2919 my ($self, $fbat, $pname, $pval) = @_;
2920 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2924 my ($self, $fbat, $m) = @_;
2925 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2926 $self->change_file_prop($fbat,'svn:executable','*');
2927 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2928 $self->change_file_prop($fbat,'svn:executable',undef);
2930 my $fh = IO::File->new_tmpfile or croak $!;
2931 if ($m->{mode_b} =~ /^120/) {
2932 print $fh 'link ' or croak $!;
2933 $self->change_file_prop($fbat,'svn:special','*');
2934 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2935 $self->change_file_prop($fbat,'svn:special',undef);
2937 defined(my $pid = fork) or croak $!;
2939 open STDOUT, '>&', $fh or croak $!;
2940 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2944 $fh->flush == 0 or croak $!;
2945 seek $fh, 0, 0 or croak $!;
2947 my $md5 = Digest::MD5->new;
2948 $md5->addfile($fh) or croak $!;
2949 seek $fh, 0, 0 or croak $!;
2951 my $exp = $md5->hexdigest;
2952 my $pool = SVN::Pool->new;
2953 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2954 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2955 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2958 close $fh or croak $!;
2962 my ($self, $m) = @_;
2963 my ($dir, $file) = split_path($m->{file_b});
2964 my $pbat = $self->ensure_path($dir);
2965 print "\tD\t$m->{file_b}\n" unless $::_q;
2966 $self->delete_entry($m->{file_b}, $pbat);
2971 my ($p,$bat) = ($self->{pool}, $self->{bat});
2972 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2974 $self->close_directory($bat->{$_}, $p);
2976 $self->close_directory($bat->{''}, $p);
2977 $self->SUPER::close_edit($p);
2983 $self->SUPER::abort_edit($self->{pool});
2988 $self->SUPER::DESTROY(@_);
2989 $self->{pool}->clear;
2992 # this drives the editor
2995 my $mods = $self->{mods};
2996 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2997 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2999 if (defined $o{$f}) {
3002 fatal("Invalid change type: $f\n");
3005 $self->rmdirs if $_rmdir;
3011 return scalar @$mods;
3014 package Git::SVN::Ra;
3015 use vars qw/@ISA $config_dir $_log_window_size/;
3018 my ($can_do_switch, %ignored_err, $RA);
3021 # enforce temporary pool usage for some simple functions
3023 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3024 my $SUPER = "SUPER::$f";
3027 my $pool = SVN::Pool->new;
3028 my @ret = $self->$SUPER(@_,$pool);
3030 wantarray ? @ret : $ret[0];
3036 my ($class, $url) = @_;
3038 return $RA if ($RA && $RA->{url} eq $url);
3040 SVN::_Core::svn_config_ensure($config_dir, undef);
3041 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
3042 SVN::Client::get_simple_provider(),
3043 SVN::Client::get_ssl_server_trust_file_provider(),
3044 SVN::Client::get_simple_prompt_provider(
3045 \&Git::SVN::Prompt::simple, 2),
3046 SVN::Client::get_ssl_client_cert_file_provider(),
3047 SVN::Client::get_ssl_client_cert_prompt_provider(
3048 \&Git::SVN::Prompt::ssl_client_cert, 2),
3049 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3050 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3051 SVN::Client::get_username_provider(),
3052 SVN::Client::get_ssl_server_trust_prompt_provider(
3053 \&Git::SVN::Prompt::ssl_server_trust),
3054 SVN::Client::get_username_prompt_provider(
3055 \&Git::SVN::Prompt::username, 2),
3057 my $config = SVN::Core::config_get_config($config_dir);
3059 my $self = SVN::Ra->new(url => $url, auth => $baton,
3061 pool => SVN::Pool->new,
3062 auth_provider_callbacks => $callbacks);
3063 $self->{svn_path} = $url;
3064 $self->{repos_root} = $self->get_repos_root;
3065 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3066 $self->{cache} = { check_path => { r => 0, data => {} },
3067 get_dir => { r => 0, data => {} } };
3068 $RA = bless $self, $class;
3072 my ($self, $path, $r) = @_;
3073 my $cache = $self->{cache}->{check_path};
3074 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3075 return $cache->{data}->{$path};
3077 my $pool = SVN::Pool->new;
3078 my $t = $self->SUPER::check_path($path, $r, $pool);
3080 if ($r != $cache->{r}) {
3081 %{$cache->{data}} = ();
3084 $cache->{data}->{$path} = $t;
3088 my ($self, $dir, $r) = @_;
3089 my $cache = $self->{cache}->{get_dir};
3090 if ($r == $cache->{r}) {
3091 if (my $x = $cache->{data}->{$dir}) {
3092 return wantarray ? @$x : $x->[0];
3095 my $pool = SVN::Pool->new;
3096 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3097 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3099 if ($r != $cache->{r}) {
3100 %{$cache->{data}} = ();
3103 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3104 wantarray ? (\%dirents, $r, $props) : \%dirents;
3108 # do not call the real DESTROY since we store ourselves in $RA
3112 my ($self, @args) = @_;
3113 my $pool = SVN::Pool->new;
3114 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3115 my $ret = $self->SUPER::get_log(@args, $pool);
3120 sub get_commit_editor {
3121 my ($self, $log, $cb, $pool) = @_;
3122 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3123 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3127 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3128 my $new = ($rev_a == $rev_b);
3129 my $path = $gs->{path};
3131 if ($new && -e $gs->{index}) {
3132 unlink $gs->{index} or die
3133 "Couldn't unlink index: $gs->{index}: $!\n";
3135 my $pool = SVN::Pool->new;
3136 $editor->set_path_strip($path);
3137 my (@pc) = split m#/#, $path;
3138 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3140 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3142 # Since we can't rely on svn_ra_reparent being available, we'll
3143 # just have to do some magic with set_path to make it so
3144 # we only want a partial path.
3146 my $final = join('/', @pc);
3148 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3149 $sp .= '/' if length $sp;
3152 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3154 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3156 $reporter->finish_report($pool);
3158 $editor->{git_commit_ok};
3161 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3162 # svn_ra_reparent didn't work before 1.4)
3164 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3165 my $path = $gs->{path};
3166 my $pool = SVN::Pool->new;
3168 my $full_url = $self->{url};
3169 my $old_url = $full_url;
3170 $full_url .= "/$path" if length $path;
3171 my ($ra, $reparented);
3172 if ($old_url ne $full_url) {
3173 if ($old_url !~ m#^svn(\+ssh)?://#) {
3174 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3176 $self->{url} = $full_url;
3179 $ra = Git::SVN::Ra->new($full_url);
3183 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3184 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3185 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3186 $reporter->finish_report($pool);
3189 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3190 $self->{url} = $old_url;
3194 $editor->{git_commit_ok};
3197 sub longest_common_path {
3198 my ($gsv, $globs) = @_;
3200 my $common_max = scalar @$gsv;
3202 foreach my $gs (@$gsv) {
3203 my @tmp = split m#/#, $gs->{path};
3206 $p .= length($p) ? "/$_" : $_;
3212 $common_max += scalar @$globs;
3213 foreach my $glob (@$globs) {
3214 my @tmp = split m#/#, $glob->{path}->{left};
3217 $p .= length($p) ? "/$_" : $_;
3223 my $longest_path = '';
3224 foreach (sort {length $b <=> length $a} keys %common) {
3225 if ($common{$_} == $common_max) {
3233 sub gs_fetch_loop_common {
3234 my ($self, $base, $head, $gsv, $globs) = @_;
3235 return if ($base > $head);
3236 my $inc = $_log_window_size;
3237 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3238 my $longest_path = longest_common_path($gsv, $globs);
3242 my $err_handler = $SVN::Error::handler;
3243 $SVN::Error::handler = sub {
3245 skip_unknown_revs($err);
3248 my ($paths, $r, $author, $date, $log) = @_;
3249 [ dup_changed_paths($paths),
3250 { author => $author, date => $date, log => $log } ];
3252 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3253 sub { $revs{$_[1]} = _cb(@_) });
3254 if ($err && $max >= $head) {
3255 print STDERR "Path '$longest_path' ",
3256 "was probably deleted:\n",
3257 $err->expanded_message,
3258 "\nWill attempt to follow ",
3259 "revisions r$min .. r$max ",
3260 "committed before the deletion\n";
3262 while (--$hi >= $min) {
3264 $self->get_log([$longest_path], $min, $hi,
3267 $revs{$_[1]} = _cb(@_) });
3269 print STDERR "r$min .. r$ok OK\n";
3274 $SVN::Error::handler = $err_handler;
3276 my %exists = map { $_->{path} => $_ } @$gsv;
3277 foreach my $r (sort {$a <=> $b} keys %revs) {
3278 my ($paths, $logged) = @{$revs{$r}};
3280 foreach my $gs ($self->match_globs(\%exists, $paths,
3282 if ($gs->rev_db_max >= $r) {
3285 next unless $gs->match_paths($paths, $r);
3286 $gs->{logged_rev_props} = $logged;
3287 if (my $last_commit = $gs->last_commit) {
3288 $gs->assert_index_clean($last_commit);
3290 my $log_entry = $gs->do_fetch($paths, $r);
3292 $gs->do_git_commit($log_entry);
3295 foreach my $g (@$globs) {
3296 my $k = "svn-remote.$g->{remote}." .
3298 Git::SVN::tmp_config($k, $r);
3301 # pre-fill the .rev_db since it'll eventually get filled in
3302 # with '0' x40 if something new gets committed
3303 foreach my $gs (@$gsv) {
3304 next if defined $gs->rev_db_get($max);
3305 $gs->rev_db_set($max, 0 x40);
3307 foreach my $g (@$globs) {
3308 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3309 Git::SVN::tmp_config($k, $max);
3311 last if $max >= $head;
3314 $max = $head if ($max > $head);
3319 my ($self, $exists, $paths, $globs, $r) = @_;
3322 my ($self, $exists, $g, $r) = @_;
3323 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3324 return unless scalar @x == 3;
3325 my $dirents = $x[0];
3326 foreach my $de (keys %$dirents) {
3327 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3328 my $p = $g->{path}->full_path($de);
3329 next if $exists->{$p};
3330 next if (length $g->{path}->{right} &&
3331 ($self->check_path($p, $r) !=
3333 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3334 $g->{ref}->full_path($de), 1);
3337 foreach my $g (@$globs) {
3338 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3339 if ($path->{action} =~ /^[AR]$/) {
3340 get_dir_check($self, $exists, $g, $r);
3343 foreach (keys %$paths) {
3344 if (/$g->{path}->{left_regex}/ &&
3345 !/$g->{path}->{regex}/) {
3346 next if $paths->{$_}->{action} !~ /^[AR]$/;
3347 get_dir_check($self, $exists, $g, $r);
3349 next unless /$g->{path}->{regex}/;
3351 my $pathname = $g->{path}->full_path($p);
3352 next if $exists->{$pathname};
3353 next if ($self->check_path($pathname, $r) !=
3355 $exists->{$pathname} = Git::SVN->init(
3356 $self->{url}, $pathname, undef,
3357 $g->{ref}->full_path($p), 1);
3360 foreach (split m#/#, $g->{path}->{left}) {
3362 next unless ($paths->{$c} &&
3363 ($paths->{$c}->{action} =~ /^[AR]$/));
3364 get_dir_check($self, $exists, $g, $r);
3372 return $self->{url} if ($self->{url} eq $self->{repos_root});
3373 my $url = $self->{repos_root};
3374 my @components = split(m!/!, $self->{svn_path});
3377 $url .= "/$c" if length $c;
3378 eval { (ref $self)->new($url)->get_latest_revnum };
3379 } while ($@ && ($c = shift @components));
3385 unless (defined $can_do_switch) {
3386 my $pool = SVN::Pool->new;
3388 $self->do_switch(1, '', 0, $self->{url},
3389 SVN::Delta::Editor->new, $pool);
3394 $rep->abort_report($pool);
3402 sub skip_unknown_revs {
3404 my $errno = $err->apr_err();
3405 # Maybe the branch we're tracking didn't
3406 # exist when the repo started, so it's
3407 # not an error if it doesn't, just continue
3409 # Wonderfully consistent library, eh?
3410 # 160013 - svn:// and file://
3411 # 175002 - http(s)://
3412 # 175007 - http(s):// (this repo required authorization, too...)
3413 # More codes may be discovered later...
3414 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3415 my $err_key = $err->expanded_message;
3416 # revision numbers change every time, filter them out
3417 $err_key =~ s/\d+/\0/g;
3418 $err_key = "$errno\0$err_key";
3419 unless ($ignored_err{$err_key}) {
3420 warn "W: Ignoring error from SVN, path probably ",
3421 "does not exist: ($errno): ",
3422 $err->expanded_message,"\n";
3423 $ignored_err{$err_key} = 1;
3427 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3430 # svn_log_changed_path_t objects passed to get_log are likely to be
3431 # overwritten even if only the refs are copied to an external variable,
3432 # so we should dup the structures in their entirety. Using an externally
3433 # passed pool (instead of our temporary and quickly cleared pool in
3434 # Git::SVN::Ra) does not help matters at all...
3435 sub dup_changed_paths {
3437 return undef unless $paths;
3439 foreach my $p (keys %$paths) {
3440 my $i = $paths->{$p};
3441 my %s = map { $_ => $i->$_ }
3442 qw/copyfrom_path copyfrom_rev action/;
3448 package Git::SVN::Log;
3451 use POSIX qw/strftime/;
3452 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3453 %rusers $show_commit $incremental/;
3458 return 1 if defined $c->{r};
3460 # big commit message got truncated by the 16k pretty buffer in rev-list
3461 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3462 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3464 my @log = command(qw/cat-file commit/, $c->{c});
3466 # shift off the headers
3467 shift @log while ($log[0] ne '');
3470 # TODO: make $c->{l} not have a trailing newline in the future
3471 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3473 (undef, $c->{r}, undef) = ::extract_metadata(
3474 (grep(/^git-svn-id: /, @log))[-1]);
3476 return defined $c->{r};
3482 $dcvar = 'color.diff';
3483 $dc = `git-config --get $dcvar`;
3485 # nothing at all; fallback to "diff.color"
3486 $dcvar = 'diff.color';
3487 $dc = `git-config --get $dcvar`;
3490 if ($dc eq 'auto') {
3492 $pc = `git-config --get color.pager`;
3494 # does not have it -- fallback to pager.color
3495 $pc = `git-config --bool --get pager.color`;
3498 $pc = `git-config --bool --get color.pager`;
3504 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3505 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3509 return 0 if $dc eq 'never';
3510 return 1 if $dc eq 'always';
3511 chomp($dc = `git-config --bool --get $dcvar`);
3512 return ($dc eq 'true');
3515 sub git_svn_log_cmd {
3516 my ($r_min, $r_max, @args) = @_;
3518 my (@files, @log_opts);
3519 foreach my $x (@args) {
3520 if ($x eq '--' || @files) {
3523 if (::verify_ref("$x^0")) {
3531 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3532 $gs ||= Git::SVN->_new;
3533 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3535 push @cmd, '-r' unless $non_recursive;
3536 push @cmd, qw/--raw --name-status/ if $verbose;
3537 push @cmd, '--color' if log_use_color();
3538 push @cmd, @log_opts;
3539 if (defined $r_max && $r_max == $r_min) {
3540 push @cmd, '--max-count=1';
3541 if (my $c = $gs->rev_db_get($r_max)) {
3544 } elsif (defined $r_max) {
3545 my ($c_min, $c_max);
3546 $c_max = $gs->rev_db_get($r_max);
3547 $c_min = $gs->rev_db_get($r_min);
3548 if (defined $c_min && defined $c_max) {
3549 if ($r_max > $r_max) {
3550 push @cmd, "$c_min..$c_max";
3552 push @cmd, "$c_max..$c_min";
3554 } elsif ($r_max > $r_min) {
3560 return (@cmd, @files);
3563 # adapted from pager.c
3565 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3566 if (!defined $pager) {
3568 } elsif (length $pager == 0 || $pager eq 'cat') {
3574 return unless -t *STDOUT;
3575 pipe my $rfd, my $wfd or return;
3576 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3578 open STDOUT, '>&', $wfd or
3579 ::fatal "Can't redirect to stdout: $!\n";
3582 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3583 $ENV{LESS} ||= 'FRSX';
3584 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3587 sub tz_to_s_offset {
3590 return ($1 * 60) + ($tz * 3600);
3593 sub get_author_info {
3594 my ($dest, $author, $t, $tz) = @_;
3595 $author =~ s/(?:^\s*|\s*$)//g;
3596 $dest->{a_raw} = $author;
3599 $au = $rusers{$author} || undef;
3602 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3607 # Date::Parse isn't in the standard Perl distro :(
3608 if ($tz =~ s/^\+//) {
3609 $t += tz_to_s_offset($tz);
3610 } elsif ($tz =~ s/^\-//) {
3611 $t -= tz_to_s_offset($tz);
3613 $dest->{t_utc} = $t;
3616 sub process_commit {
3617 my ($c, $r_min, $r_max, $defer) = @_;
3618 if (defined $r_min && defined $r_max) {
3619 if ($r_min == $c->{r} && $r_min == $r_max) {
3623 return 1 if $r_min == $r_max;
3624 if ($r_min < $r_max) {
3625 # we need to reverse the print order
3626 return 0 if (defined $limit && --$limit < 0);
3630 if ($r_min != $r_max) {
3631 return 1 if ($r_min < $c->{r});
3632 return 1 if ($r_max > $c->{r});
3635 return 0 if (defined $limit && --$limit < 0);
3644 if (my $l = $c->{l}) {
3645 while ($l->[0] =~ /^\s*$/) { shift @$l }
3648 $l_fmt ||= 'A' . length($c->{r});
3649 print 'r',pack($l_fmt, $c->{r}),' | ';
3650 print "$c->{c} | " if $show_commit;
3653 show_commit_normal($c);
3657 sub show_commit_changed_paths {
3659 return unless $c->{changed};
3660 print "Changed paths:\n", @{$c->{changed}};
3663 sub show_commit_normal {
3665 print '-' x72, "\nr$c->{r} | ";
3666 print "$c->{c} | " if $show_commit;
3667 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3668 localtime($c->{t_utc})), ' | ';
3671 if (my $l = $c->{l}) {
3672 while ($l->[$#$l] eq "\n" && $#$l > 0
3673 && $l->[($#$l - 1)] eq "\n") {
3676 $nr_line = scalar @$l;
3678 print "1 line\n\n\n";
3680 if ($nr_line == 1) {
3681 $nr_line = '1 line';
3683 $nr_line .= ' lines';
3685 print $nr_line, "\n";
3686 show_commit_changed_paths($c);
3688 print $_ foreach @$l;
3692 show_commit_changed_paths($c);
3696 foreach my $x (qw/raw stat diff/) {
3699 print $_ foreach @{$c->{$x}}
3706 my ($r_min, $r_max);
3707 my $r_last = -1; # prevent dupes
3713 if (defined $::_revision) {
3714 if ($::_revision =~ /^(\d+):(\d+)$/) {
3715 ($r_min, $r_max) = ($1, $2);
3716 } elsif ($::_revision =~ /^\d+$/) {
3717 $r_min = $r_max = $::_revision;
3719 ::fatal "-r$::_revision is not supported, use ",
3720 "standard \'git log\' arguments instead\n";
3725 @args = git_svn_log_cmd($r_min, $r_max, @args);
3726 my $log = command_output_pipe(@args);
3728 my (@k, $c, $d, $stat);
3729 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3731 if (/^${esc_color}commit ($::sha1_short)/o) {
3733 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3735 process_commit($c, $r_min, $r_max, \@k) or
3740 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3741 get_author_info($c, $1, $2, $3);
3742 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3744 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3745 push @{$c->{raw}}, $_;
3746 } elsif (/^${esc_color}[ACRMDT]\t/) {
3747 # we could add $SVN->{svn_path} here, but that requires
3748 # remote access at the moment (repo_path_split)...
3749 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3750 push @{$c->{changed}}, $_;
3751 } elsif (/^${esc_color}diff /o) {
3753 push @{$c->{diff}}, $_;
3755 push @{$c->{diff}}, $_;
3756 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3757 $esc_color*[\+\-]*$esc_color$/x) {
3759 push @{$c->{stat}}, $_;
3760 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3761 push @{$c->{stat}}, $_;
3763 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3764 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3765 } elsif (s/^${esc_color} //o) {
3766 push @{$c->{l}}, $_;
3769 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3771 process_commit($c, $r_min, $r_max, \@k);
3777 process_commit($_, $r_min, $r_max) foreach reverse @k;
3781 print '-' x72,"\n" unless $incremental || $oneline;
3784 package Git::SVN::Migration;
3785 # these version numbers do NOT correspond to actual version numbers
3786 # of git nor git-svn. They are just relative.
3788 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3790 # v1 layout: .git/$id/info/url, refs/remotes/$id
3792 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3794 # v3 layout: .git/svn/$id, refs/remotes/$id
3795 # - info/url may remain for backwards compatibility
3796 # - this is what we migrate up to this layout automatically,
3797 # - this will be used by git svn init on single branches
3798 # v3.1 layout (auto migrated):
3799 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3800 # for backwards compatibility
3802 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3803 # - this is only created for newly multi-init-ed
3804 # repositories. Similar in spirit to the
3805 # --use-separate-remotes option in git-clone (now default)
3806 # - we do not automatically migrate to this (following
3807 # the example set by core git)
3811 use File::Path qw/mkpath/;
3812 use File::Basename qw/dirname basename/;
3813 use vars qw/$_minimize/;
3815 sub migrate_from_v0 {
3816 my $git_dir = $ENV{GIT_DIR};
3817 return undef unless -d $git_dir;
3818 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3822 my ($id, $orig_ref) = ($_, $_);
3823 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3824 next unless -f "$git_dir/$id/info/url";
3825 my $new_ref = "refs/remotes/$id";
3826 if (::verify_ref("$new_ref^0")) {
3827 print STDERR "W: $orig_ref is probably an old ",
3828 "branch used by an ancient version of ",
3830 "However, $new_ref also exists.\n",
3831 "We will not be able ",
3832 "to use this branch until this ",
3833 "ambiguity is resolved.\n";
3836 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3837 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3838 command_noisy('update-ref', $new_ref, $orig_ref);
3839 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3842 command_close_pipe($fh, $ctx);
3843 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3847 sub migrate_from_v1 {
3848 my $git_dir = $ENV{GIT_DIR};
3850 return $migrated unless -d $git_dir;
3851 my $svn_dir = "$git_dir/svn";
3853 # just in case somebody used 'svn' as their $id at some point...
3854 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3856 print STDERR "Migrating from a git-svn v1 layout...\n";
3858 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3859 "$svn_dir\n\t(required for this version ",
3860 "($::VERSION) of git-svn) does not. exist\n";
3861 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3864 next unless $x =~ s#^refs/remotes/##;
3866 next unless -f "$git_dir/$x/info/url";
3867 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3869 my $dn = dirname("$git_dir/svn/$x");
3870 mkpath([$dn]) unless -d $dn;
3871 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3872 mkpath(["$git_dir/svn/svn"]);
3873 print STDERR " - $git_dir/$x/info => ",
3874 "$git_dir/svn/$x/info\n";
3875 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3877 # don't worry too much about these, they probably
3878 # don't exist with repos this old (save for index,
3879 # and we can easily regenerate that)
3880 foreach my $f (qw/unhandled.log index .rev_db/) {
3881 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3884 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3885 rename "$git_dir/$x", "$git_dir/svn/$x" or
3890 command_close_pipe($fh, $ctx);
3891 print STDERR "Done migrating from a git-svn v1 layout\n";
3896 my ($l_map, $pfx, $path) = @_;
3898 foreach (<$path/*>) {
3899 if (-r "$_/info/url") {
3900 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3901 my $ref_id = $pfx . basename $_;
3902 my $url = ::file_to_s("$_/info/url");
3903 $l_map->{$ref_id} = $url;
3910 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3911 read_old_urls($l_map, $x, $_);
3915 sub migrate_from_v2 {
3916 my @cfg = command(qw/config -l/);
3917 return if grep /^svn-remote\..+\.url=/, @cfg;
3919 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3922 foreach my $ref_id (sort keys %l_map) {
3923 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3925 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3932 sub minimize_connections {
3933 my $r = Git::SVN::read_all_remotes();
3935 my $root_repos = {};
3936 foreach my $repo_id (keys %$r) {
3937 my $url = $r->{$repo_id}->{url} or next;
3938 my $fetch = $r->{$repo_id}->{fetch} or next;
3939 my $ra = Git::SVN::Ra->new($url);
3941 # skip existing cases where we already connect to the root
3942 if (($ra->{url} eq $ra->{repos_root}) ||
3943 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3945 $root_repos->{$ra->{url}} = $repo_id;
3949 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3950 my $root_path = $ra->{url};
3951 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3952 foreach my $path (keys %$fetch) {
3953 my $ref_id = $fetch->{$path};
3954 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3956 # make sure we can read when connecting to
3957 # a higher level of a repository
3958 my ($last_rev, undef) = $gs->last_rev_commit;
3959 if (!defined $last_rev) {
3961 $root_ra->get_latest_revnum;
3965 my $new = $root_path;
3966 $new .= length $path ? "/$path" : '';
3968 $root_ra->get_log([$new], $last_rev, $last_rev,
3972 $new_urls->{$ra->{repos_root}}->{$new} =
3973 { ref_id => $ref_id,
3974 old_repo_id => $repo_id,
3975 old_path => $path };
3980 foreach my $url (keys %$new_urls) {
3981 # see if we can re-use an existing [svn-remote "repo_id"]
3982 # instead of creating a(n ugly) new section:
3983 my $repo_id = $root_repos->{$url} ||
3984 Git::SVN::sanitize_remote_name($url);
3986 my $fetch = $new_urls->{$url};
3987 foreach my $path (keys %$fetch) {
3988 my $x = $fetch->{$path};
3989 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3990 my $pfx = "svn-remote.$x->{old_repo_id}";
3992 my $old_fetch = quotemeta("$x->{old_path}:".
3993 "refs/remotes/$x->{ref_id}");
3994 command_noisy(qw/config --unset/,
3995 "$pfx.fetch", '^'. $old_fetch . '$');
3996 delete $r->{$x->{old_repo_id}}->
3997 {fetch}->{$x->{old_path}};
3998 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3999 command_noisy(qw/config --unset/,
4001 push @emptied, $x->{old_repo_id}
4006 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4007 "$ENV{GIT_DIR}/config";
4009 The following [svn-remote] sections in your config file ($file) are empty
4010 and can be safely removed:
4012 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4016 sub migration_check {
4020 minimize_connections() if $_minimize;
4023 package Git::IndexInfo;
4026 use Git qw/command_input_pipe command_close_pipe/;
4030 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4031 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4035 my ($self, $path) = @_;
4036 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4037 return ++$self->{nr};
4043 my ($self, $mode, $hash, $path) = @_;
4044 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4045 return ++$self->{nr};
4052 command_close_pipe($self->{gui}, $self->{ctx});
4055 package Git::SVN::GlobSpec;
4060 my ($class, $glob) = @_;
4062 $re =~ s!/+$!!g; # no need for trailing slashes
4063 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4064 my ($left, $right) = ($1, $2);
4066 die "Only one '*' wildcard expansion ",
4067 "is supported (got $nr): '$glob'\n";
4068 } elsif ($nr == 0) {
4069 die "One '*' is needed for glob: '$glob'\n";
4071 $re = quotemeta($left) . $re . quotemeta($right);
4072 if (length $left && !($left =~ s!/+$!!g)) {
4073 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4075 if (length $right && !($right =~ s!^/+!!g)) {
4076 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4078 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4079 bless { left => $left, right => $right, left_regex => $left_re,
4080 regex => qr/$re/, glob => $glob }, $class;
4084 my ($self, $path) = @_;
4085 return (length $self->{left} ? "$self->{left}/" : '') .
4086 $path . (length $self->{right} ? "/$self->{right}" : '');
4094 $remotes = { # returned by read_all_remotes()
4096 # svn-remote.svn.url=https://svn.musicpd.org
4097 url => 'https://svn.musicpd.org',
4098 # svn-remote.svn.fetch=mpd/trunk:trunk
4100 'mpd/trunk' => 'trunk',
4102 # svn-remote.svn.tags=mpd/tags/*:tags/*
4107 regex => qr!mpd/tags/([^/]+)$!,
4113 regex => qr!tags/([^/]+)$!,
4120 $log_entry hashref as returned by libsvn_log_entry()
4122 log => 'whitespace-formatted log entry
4123 ', # trailing newline is preserved
4124 revision => '8', # integer
4125 date => '2004-02-24T17:01:44.108345Z', # commit date
4126 author => 'committer name'
4130 # this is generated by generate_diff();
4131 @mods = array of diff-index line hashes, each element represents one line
4132 of diff-index output
4134 diff-index line ($m hash)
4136 mode_a => first column of diff-index output, no leading ':',
4137 mode_b => second column of diff-index output,
4138 sha1_b => sha1sum of the final blob,
4139 chg => change type [MCRADT],
4140 file_a => original file name of a file (iff chg is 'C' or 'R')
4141 file_b => new/current file name of a file (any chg)
4145 # retval of read_url_paths{,_all}();
4147 # repository root url
4148 'https://svn.musicpd.org' => {
4149 # repository path # GIT_SVN_ID
4150 'mpd/trunk' => 'trunk',
4151 'mpd/tags/0.11.5' => 'tags/0.11.5',
4156 I don't trust the each() function on unless I created %hash myself
4157 because the internal iterator may not have started at base.