2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 $ENV{GIT_DIR} ||= '.git';
13 $Git::SVN::default_repo_id = 'svn';
14 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
15 $Git::SVN::Ra::_log_window_size = 100;
17 $Git::SVN::Log::TZ = $ENV{TZ};
19 $| = 1; # unbuffer STDOUT
21 sub fatal (@) { print STDERR @_; exit 1 }
22 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
25 if ($SVN::Core::VERSION lt '1.1.0') {
26 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
28 push @Git::SVN::Ra::ISA, 'SVN::Ra';
29 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
30 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
33 use File::Basename qw/dirname basename/;
34 use File::Path qw/mkpath/;
35 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
41 foreach (qw/command command_oneline command_noisy command_output_pipe
42 command_input_pipe command_close_pipe/) {
43 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
44 "*Git::SVN::Migration::$_ = ".
45 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
52 $sha1 = qr/[a-f\d]{40}/;
53 $sha1_short = qr/[a-f\d]{4,40}/;
54 my ($_stdin, $_help, $_edit,
57 $_version, $_fetch_all,
58 $_merge, $_strategy, $_dry_run,
59 $_prefix, $_no_checkout, $_verbose);
60 $Git::SVN::_follow_parent = 1;
61 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
62 'config-dir=s' => \$Git::SVN::Ra::config_dir,
63 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
64 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
65 'authors-file|A=s' => \$_authors,
66 'repack:i' => \$Git::SVN::_repack,
67 'noMetadata' => \$Git::SVN::_no_metadata,
68 'useSvmProps' => \$Git::SVN::_use_svm_props,
69 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
70 'no-checkout' => \$_no_checkout,
72 'repack-flags|repack-args|repack-opts=s' =>
73 \$Git::SVN::_repack_flags,
76 my ($_trunk, $_tags, $_branches);
77 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
78 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
79 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
81 my %cmt_opts = ( 'edit|e' => \$_edit,
82 'rmdir' => \$SVN::Git::Editor::_rmdir,
83 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
84 'l=i' => \$SVN::Git::Editor::_rename_limit,
85 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
89 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
90 { 'revision|r=s' => \$_revision,
91 'fetch-all|all' => \$_fetch_all,
93 clone => [ \&cmd_clone, "Initialize and fetch revisions",
94 { 'revision|r=s' => \$_revision,
95 %fc_opts, %init_opts } ],
96 init => [ \&cmd_init, "Initialize a repo for tracking" .
97 " (requires URL argument)",
99 'multi-init' => [ \&cmd_multi_init,
100 "Deprecated alias for ".
101 "'$0 init -T<trunk> -b<branches> -t<tags>'",
103 dcommit => [ \&cmd_dcommit,
104 'Commit several diffs to merge with upstream',
105 { 'merge|m|M' => \$_merge,
106 'strategy|s=s' => \$_strategy,
107 'verbose|v' => \$_verbose,
108 'dry-run|n' => \$_dry_run,
109 'fetch-all|all' => \$_fetch_all,
110 %cmt_opts, %fc_opts } ],
111 'set-tree' => [ \&cmd_set_tree,
112 "Set an SVN repository to a git tree-ish",
113 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
114 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
115 { 'revision|r=i' => \$_revision } ],
116 'multi-fetch' => [ \&cmd_multi_fetch,
117 "Deprecated alias for $0 fetch --all",
118 { 'revision|r=s' => \$_revision, %fc_opts } ],
119 'migrate' => [ sub { },
120 # no-op, we automatically run this anyways,
121 'Migrate configuration/metadata/layout from
122 previous versions of git-svn',
123 { 'minimize' => \$Git::SVN::Migration::_minimize,
125 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
126 { 'limit=i' => \$Git::SVN::Log::limit,
127 'revision|r=s' => \$_revision,
128 'verbose|v' => \$Git::SVN::Log::verbose,
129 'incremental' => \$Git::SVN::Log::incremental,
130 'oneline' => \$Git::SVN::Log::oneline,
131 'show-commit' => \$Git::SVN::Log::show_commit,
132 'non-recursive' => \$Git::SVN::Log::non_recursive,
133 'authors-file|A=s' => \$_authors,
134 'color' => \$Git::SVN::Log::color,
135 'pager=s' => \$Git::SVN::Log::pager,
137 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
138 { 'merge|m|M' => \$_merge,
139 'verbose|v' => \$_verbose,
140 'strategy|s=s' => \$_strategy,
141 'fetch-all|all' => \$_fetch_all,
143 'commit-diff' => [ \&cmd_commit_diff,
144 'Commit a diff between two trees',
145 { 'message|m=s' => \$_message,
146 'file|F=s' => \$_file,
147 'revision|r=s' => \$_revision,
152 for (my $i = 0; $i < @ARGV; $i++) {
153 if (defined $cmd{$ARGV[$i]}) {
160 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
162 read_repo_config(\%opts);
163 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
164 'minimize-connections' => \$Git::SVN::Migration::_minimize,
165 'id|i=s' => \$Git::SVN::default_ref_id,
166 'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
167 exit 1 if (!$rv && $cmd ne 'log');
170 version() if $_version;
171 usage(1) unless defined $cmd;
172 load_authors() if $_authors;
173 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
174 Git::SVN::Migration::migration_check();
176 Git::SVN::init_vars();
178 Git::SVN::verify_remotes_sanity();
179 $cmd{$cmd}->[0]->(@ARGV);
182 post_fetch_checkout();
185 ####################### primary functions ######################
187 my $exit = shift || 0;
188 my $fd = $exit ? \*STDERR : \*STDOUT;
190 git-svn - bidirectional operations between a single Subversion tree and git
191 Usage: $0 <command> [options] [arguments]\n
193 print $fd "Available commands:\n" unless $cmd;
195 foreach (sort keys %cmd) {
196 next if $cmd && $cmd ne $_;
197 next if /^multi-/; # don't show deprecated commands
198 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
199 foreach (keys %{$cmd{$_}->[2]}) {
200 # prints out arguments as they should be passed:
201 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
202 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
204 split /\|/,$_)," $x\n";
208 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
209 arbitrary identifier if you're tracking multiple SVN branches/repositories in
210 one git repository and want to keep them separate. See git-svn(1) for more
217 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
222 unless (-d $ENV{GIT_DIR}) {
223 my @init_db = ('init');
224 push @init_db, "--template=$_template" if defined $_template;
225 if (defined $_shared) {
226 if ($_shared =~ /[a-z]/) {
227 push @init_db, "--shared=$_shared";
229 push @init_db, "--shared";
232 command_noisy(@init_db);
237 my $repo_path = shift or return;
238 mkpath([$repo_path]) unless -d $repo_path;
239 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
240 $ENV{GIT_DIR} = $repo_path . "/.git";
244 my ($url, $path) = @_;
245 if (!defined $path &&
246 (defined $_trunk || defined $_branches || defined $_tags) &&
247 $url !~ m#^[a-z\+]+://#) {
250 warn "--path: $path\n" if defined $path;
251 $path = basename($url) if !defined $path || !length $path;
252 warn "++path: $path\n" if defined $path;
254 chdir $path or die "Couldn't chdir to $path\n";
256 Git::SVN::fetch_all($Git::SVN::default_repo_id);
260 if (defined $_trunk || defined $_branches || defined $_tags) {
261 return cmd_multi_init(@_);
263 my $url = shift or die "SVN repository location required ",
264 "as a command-line argument\n";
268 Git::SVN->init($url);
272 if (grep /^\d+=./, @_) {
273 die "'<rev>=<commit>' fetch arguments are ",
274 "no longer supported.\n";
278 die "Usage: $0 fetch [--all] [svn-remote]\n";
280 $remote ||= $Git::SVN::default_repo_id;
284 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
290 if ($_stdin || !@commits) {
291 print "Reading from stdin...\n";
294 if (/\b($sha1_short)\b/o) {
295 unshift @commits, $1;
300 foreach my $c (@commits) {
301 my @tmp = command('rev-parse',$c);
302 if (scalar @tmp == 1) {
304 } elsif (scalar @tmp > 1) {
305 push @revs, reverse(command('rev-list',@tmp));
307 fatal "Failed to rev-parse $c\n";
310 my $gs = Git::SVN->new;
311 my ($r_last, $cmt_last) = $gs->last_rev_commit;
313 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
314 fatal "There are new revisions that were fetched ",
315 "and need to be merged (or acknowledged) ",
316 "before committing.\nlast rev: $r_last\n",
317 " current: $gs->{last_rev}\n";
319 $gs->set_tree($_) foreach @revs;
320 print "Done committing ",scalar @revs," revisions to SVN\n";
327 my ($url, $rev, $uuid) = working_head_info($head, \@refs);
329 unless (defined $url && defined $rev && defined $uuid) {
330 die "Unable to determine upstream SVN information from ",
333 my $gs = Git::SVN->find_by_url($url);
335 foreach my $d (@refs) {
336 if (!verify_ref("$d~1")) {
338 "has no parent commit, and therefore ",
339 "nothing to diff against.\n",
340 "You should be working from a repository ",
341 "originally created by git-svn\n";
343 unless (defined $last_rev) {
344 (undef, $last_rev, undef) = cmt_metadata("$d~1");
345 unless (defined $last_rev) {
346 fatal "Unable to extract revision information ",
347 "from commit $d~1\n";
351 print "diff-tree $d~1 $d\n";
353 my %ed_opts = ( r => $last_rev,
354 log => get_commit_entry($d)->{log},
355 ra => Git::SVN::Ra->new($url),
359 print "Committed r$_[0]\n";
360 $last_rev = $_[0]; },
362 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
363 print "No changes\n$d~1 == $d\n";
369 warn "Could not determine fetch information for $url\n",
370 "Will not attempt to fetch and rebase commits.\n",
371 "This probably means you have useSvmProps and should\n",
372 "now resync your SVN::Mirror repository.\n";
375 $_fetch_all ? $gs->fetch_all : $gs->fetch;
376 # we always want to rebase against the current HEAD, not any
377 # head that was passed to us
378 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
381 @finish = rebase_cmd();
382 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
383 "using @finish:\n", "@diff";
385 print "No changes between current HEAD and ",
386 $gs->refname, "\nResetting to the latest ",
388 @finish = qw/reset --mixed/;
390 command_noisy(@finish, $gs->refname);
394 command_noisy(qw/update-index --refresh/);
395 my $url = (working_head_info('HEAD'))[0];
397 die "Unable to determine upstream SVN information from ",
398 "working tree history\n";
401 my $gs = Git::SVN->find_by_url($url);
402 if (command(qw/diff-index HEAD --/)) {
403 print STDERR "Cannot rebase with uncommited changes:\n";
404 command_noisy('status');
407 $_fetch_all ? $gs->fetch_all : $gs->fetch;
408 command_noisy(rebase_cmd(), $gs->refname);
411 sub cmd_show_ignore {
412 my $gs = Git::SVN->new;
413 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
414 $gs->traverse_ignore(\*STDOUT, '', $r);
419 unless (defined $_trunk || defined $_branches || defined $_tags) {
423 $_prefix = '' unless defined $_prefix;
428 if (defined $_trunk) {
429 my $trunk_ref = $_prefix . 'trunk';
430 # try both old-style and new-style lookups:
431 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
433 my ($trunk_url, $trunk_path) =
434 complete_svn_url($url, $_trunk);
435 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
439 return unless defined $_branches || defined $_tags;
440 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
441 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
442 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
445 sub cmd_multi_fetch {
446 my $remotes = Git::SVN::read_all_remotes();
447 foreach my $repo_id (sort keys %$remotes) {
448 if ($remotes->{$repo_id}->{url}) {
449 Git::SVN::fetch_all($repo_id, $remotes);
454 # this command is special because it requires no metadata
455 sub cmd_commit_diff {
456 my ($ta, $tb, $url) = @_;
457 my $usage = "Usage: $0 commit-diff -r<revision> ".
458 "<tree-ish> <tree-ish> [<URL>]\n";
459 fatal($usage) if (!defined $ta || !defined $tb);
462 my $gs = eval { Git::SVN->new };
464 fatal("Needed URL or usable git-svn --id in ",
465 "the command-line\n", $usage);
468 $svn_path = $gs->{path};
470 unless (defined $_revision) {
471 fatal("-r|--revision is a required argument\n", $usage);
473 if (defined $_message && defined $_file) {
474 fatal("Both --message/-m and --file/-F specified ",
475 "for the commit message.\n",
476 "I have no idea what you mean\n");
478 if (defined $_file) {
479 $_message = file_to_s($_file);
481 $_message ||= get_commit_entry($tb)->{log};
483 my $ra ||= Git::SVN::Ra->new($url);
484 $svn_path ||= $ra->{svn_path};
487 $r = $ra->get_latest_revnum;
488 } elsif ($r !~ /^\d+$/) {
489 die "revision argument: $r not understood by git-svn\n";
491 my %ed_opts = ( r => $r,
496 editor_cb => sub { print "Committed r$_[0]\n" },
497 svn_path => $svn_path );
498 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
499 print "No changes\n$ta == $tb\n";
503 ########################### utility functions #########################
506 my @cmd = qw/rebase/;
507 push @cmd, '-v' if $_verbose;
508 push @cmd, qw/--merge/ if $_merge;
509 push @cmd, "--strategy=$_strategy" if $_strategy;
513 sub post_fetch_checkout {
514 return if $_no_checkout;
515 my $gs = $Git::SVN::_head or return;
516 return if verify_ref('refs/heads/master^0');
518 my $valid_head = verify_ref('HEAD^0');
519 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
520 return if ($valid_head || !verify_ref('HEAD^0'));
522 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
523 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
526 chomp(my $bare = `git config --bool --get core.bare`);
527 return if $bare eq 'true';
528 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
529 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
530 print STDERR "Checked out HEAD:\n ",
531 $gs->full_url, " r", $gs->last_rev, "\n";
534 sub complete_svn_url {
535 my ($url, $path) = @_;
537 if ($path !~ m#^[a-z\+]+://#) {
538 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
539 fatal("E: '$path' is not a complete URL ",
540 "and a separate URL is not specified\n");
542 return ($url, $path);
547 sub complete_url_ls_init {
548 my ($ra, $repo_path, $switch, $pfx) = @_;
549 unless ($repo_path) {
550 print STDERR "W: $switch not specified\n";
553 $repo_path =~ s#/+$##;
554 if ($repo_path =~ m#^[a-z\+]+://#) {
555 $ra = Git::SVN::Ra->new($repo_path);
558 $repo_path =~ s#^/+##;
560 fatal("E: '$repo_path' is not a complete URL ",
561 "and a separate URL is not specified\n");
564 my $url = $ra->{url};
565 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
566 my $k = "svn-remote.$gs->{repo_id}.url";
567 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
568 if ($orig_url && ($orig_url ne $gs->{url})) {
569 die "$k already set: $orig_url\n",
570 "wanted to set to: $gs->{url}\n";
572 command_oneline('config', $k, $gs->{url}) unless $orig_url;
573 my $remote_path = "$ra->{svn_path}/$repo_path/*";
574 $remote_path =~ s#/+#/#g;
575 $remote_path =~ s#^/##g;
576 my ($n) = ($switch =~ /^--(\w+)/);
577 if (length $pfx && $pfx !~ m#/$#) {
578 die "--prefix='$pfx' must have a trailing slash '/'\n";
580 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
581 "$remote_path:refs/remotes/$pfx*");
586 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
590 sub get_tree_from_treeish {
592 # $treeish can be a symbolic ref, too:
593 my $type = command_oneline(qw/cat-file -t/, $treeish);
595 while ($type eq 'tag') {
596 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
598 if ($type eq 'commit') {
599 $expected = (grep /^tree /, command(qw/cat-file commit/,
601 ($expected) = ($expected =~ /^tree ($sha1)$/o);
602 die "Unable to get tree from $treeish\n" unless $expected;
603 } elsif ($type eq 'tree') {
604 $expected = $treeish;
606 die "$treeish is a $type, expected tree, tag or commit\n";
611 sub get_commit_entry {
612 my ($treeish) = shift;
613 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
614 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
615 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
616 open my $log_fh, '>', $commit_editmsg or croak $!;
618 my $type = command_oneline(qw/cat-file -t/, $treeish);
619 if ($type eq 'commit' || $type eq 'tag') {
620 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
625 $in_msg = 1 if (/^\s*$/);
626 } elsif (/^git-svn-id: /) {
627 # skip this for now, we regenerate the
628 # correct one on re-fetch anyways
629 # TODO: set *:merge properties or like...
631 print $log_fh $_ or croak $!;
634 command_close_pipe($msg_fh, $ctx);
636 close $log_fh or croak $!;
638 if ($_edit || ($type eq 'tree')) {
639 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
640 # TODO: strip out spaces, comments, like git-commit.sh
641 system($editor, $commit_editmsg);
643 rename $commit_editmsg, $commit_msg or croak $!;
644 open $log_fh, '<', $commit_msg or croak $!;
645 { local $/; chomp($log_entry{log} = <$log_fh>); }
646 close $log_fh or croak $!;
652 my ($str, $file, $mode) = @_;
653 open my $fd,'>',$file or croak $!;
654 print $fd $str,"\n" or croak $!;
655 close $fd or croak $!;
656 chmod ($mode &~ umask, $file) if (defined $mode);
661 open my $fd,'<',$file or croak "$!: file: $file\n";
664 close $fd or croak $!;
669 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
671 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
672 my $log = $cmd eq 'log';
675 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
676 my ($user, $name, $email) = ($1, $2, $3);
678 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
680 $users{$user} = [$name, $email];
683 close $authors or croak $!;
686 # convert GetOpt::Long specs for use by git-config
687 sub read_repo_config {
688 return unless -d $ENV{GIT_DIR};
691 foreach my $o (keys %$opts) {
692 # if we have mixedCase and a long option-only, then
693 # it's a config-only variable that we don't need for
695 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
697 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
699 my $arg = 'git-config';
700 $arg .= ' --int' if ($o =~ /[:=]i$/);
701 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
702 if (ref $v eq 'ARRAY') {
703 chomp(my @tmp = `$arg --get-all svn.$key`);
706 chomp(my $tmp = `$arg --get svn.$key`);
707 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
712 delete @$opts{@config_only} if @config_only;
715 sub extract_metadata {
716 my $id = shift or return (undef, undef, undef);
717 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
719 if (!defined $rev || !$uuid || !$url) {
720 # some of the original repositories I made had
721 # identifiers like this:
722 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
724 return ($url, $rev, $uuid);
728 return extract_metadata((grep(/^git-svn-id: /,
729 command(qw/cat-file commit/, shift)))[-1]);
732 sub working_head_info {
733 my ($head, $refs) = @_;
734 my ($url, $rev, $uuid);
735 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
738 ($url, $rev, $uuid) = cmt_metadata($_);
739 last if (defined $url && defined $rev && defined $uuid);
740 unshift @$refs, $_ if $refs;
742 close $fh; # break the pipe
749 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
750 $_repack $_repack_flags $_use_svm_props $_head/;
752 use File::Path qw/mkpath/;
753 use File::Copy qw/copy/;
757 # properties that we do not log:
760 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
761 svn:special svn:executable
762 svn:entry:committed-rev
763 svn:entry:last-author
765 svn:entry:committed-date/;
767 # some options are read globally, but can be overridden locally
768 # per [svn-remote "..."] section. Command-line options will *NOT*
769 # override options set in an [svn-remote "..."] section
771 foreach (qw/follow_parent no_metadata use_svm_props/) {
776 return \$self->{-$_} if exists \$self->{-$_};
777 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
778 eval { command_oneline(qw/config --get/, \$k) };
780 \$self->{-$_} = \$Git::SVN::_$_;
782 my \$v = command_oneline(qw/config --bool/,\$k);
783 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
785 return \$self->{-$_} }\n";
792 END { unlink keys %LOCKFILES if %LOCKFILES }
794 sub resolve_local_globs {
795 my ($url, $fetch, $glob_spec) = @_;
796 return unless defined $glob_spec;
797 my $ref = $glob_spec->{ref};
798 my $path = $glob_spec->{path};
799 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
800 next unless m#^refs/remotes/$ref->{regex}$#;
802 my $pathname = $path->full_path($p);
803 my $refname = $ref->full_path($p);
804 if (my $existing = $fetch->{$pathname}) {
805 if ($existing ne $refname) {
806 die "Refspec conflict:\n",
807 "existing: refs/remotes/$existing\n",
808 " globbed: refs/remotes/$refname\n";
810 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
811 $u =~ s!^\Q$url\E(/|$)!! or die
812 "refs/remotes/$refname: '$url' not found in '$u'\n";
813 if ($pathname ne $u) {
814 warn "W: Refspec glob conflict ",
815 "(ref: refs/remotes/$refname):\n",
816 "expected path: $pathname\n",
818 "Continuing ahead with $u\n";
822 $fetch->{$pathname} = $refname;
827 sub parse_revision_argument {
828 my ($base, $head) = @_;
829 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
830 return ($base, $head);
832 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
833 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
834 return ($head, $head) if ($::_revision eq 'HEAD');
835 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
836 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
837 die "revision argument: $::_revision not understood by git-svn\n";
841 my ($repo_id, $remotes) = @_;
845 $repo_id = $gs->{repo_id};
847 $remotes ||= read_all_remotes();
848 my $remote = $remotes->{$repo_id} or
849 die "[svn-remote \"$repo_id\"] unknown\n";
850 my $fetch = $remote->{fetch};
851 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
853 my $ra = Git::SVN::Ra->new($url);
854 my $uuid = $ra->get_uuid;
855 my $head = $ra->get_latest_revnum;
856 my $base = defined $fetch ? $head : 0;
858 # read the max revs for wildcard expansion (branches/*, tags/*)
859 foreach my $t (qw/branches tags/) {
860 defined $remote->{$t} or next;
861 push @globs, $remote->{$t};
862 my $max_rev = eval { tmp_config(qw/--int --get/,
863 "svn-remote.$repo_id.${t}-maxRev") };
864 if (defined $max_rev && ($max_rev < $base)) {
866 } elsif (!defined $max_rev) {
872 foreach my $p (sort keys %$fetch) {
873 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
874 my $lr = $gs->rev_db_max;
876 $base = $lr if ($lr < $base);
882 ($base, $head) = parse_revision_argument($base, $head);
883 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
886 sub read_all_remotes {
888 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
889 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
890 $r->{$1}->{fetch}->{$2} = $3;
891 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
892 $r->{$1}->{url} = $2;
893 } elsif (m!^(.+)\.(branches|tags)=
894 (.*):refs/remotes/(.+)\s*$/!x) {
895 my ($p, $g) = ($3, $4);
896 my $rs = $r->{$1}->{$2} = {
899 path => Git::SVN::GlobSpec->new($p),
900 ref => Git::SVN::GlobSpec->new($g) };
901 if (length($rs->{ref}->{right}) != 0) {
902 die "The '*' glob character must be the last ",
903 "character of '$g'\n";
911 if (defined $_repack) {
912 $_repack = 1000 if ($_repack <= 0);
913 $_repack_nr = $_repack;
914 $_repack_flags ||= '-d';
918 sub verify_remotes_sanity {
919 return unless -d $ENV{GIT_DIR};
921 foreach (command(qw/config -l/)) {
922 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
924 die "Remote ref refs/remote/$1 is tracked by",
925 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
926 "Please resolve this ambiguity in ",
927 "your git configuration file before ",
935 # we allow more chars than remotes2config.sh...
936 sub sanitize_remote_name {
938 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
942 sub find_existing_remote {
943 my ($url, $remotes) = @_;
945 foreach my $repo_id (keys %$remotes) {
946 my $u = $remotes->{$repo_id}->{url} or next;
948 $existing = $repo_id;
954 sub init_remote_config {
955 my ($self, $url, $no_write) = @_;
956 $url =~ s!/+$!!; # strip trailing slash
957 my $r = read_all_remotes();
958 my $existing = find_existing_remote($url, $r);
961 print STDERR "Using existing ",
962 "[svn-remote \"$existing\"]\n";
964 $self->{repo_id} = $existing;
966 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
967 $existing = find_existing_remote($min_url, $r);
970 print STDERR "Using existing ",
971 "[svn-remote \"$existing\"]\n";
973 $self->{repo_id} = $existing;
975 if ($min_url ne $url) {
977 print STDERR "Using higher level of URL: ",
978 "$url => $min_url\n";
980 my $old_path = $self->{path};
981 $self->{path} = $url;
982 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
983 if (length $old_path) {
984 $self->{path} .= "/$old_path";
991 # verify that we aren't overwriting anything:
993 command_oneline('config', '--get',
994 "svn-remote.$self->{repo_id}.url")
996 if ($orig_url && ($orig_url ne $url)) {
997 die "svn-remote.$self->{repo_id}.url already set: ",
998 "$orig_url\nwanted to set to: $url\n";
1001 my ($xrepo_id, $xpath) = find_ref($self->refname);
1002 if (defined $xpath) {
1003 die "svn-remote.$xrepo_id.fetch already set to track ",
1004 "$xpath:refs/remotes/", $self->refname, "\n";
1006 unless ($no_write) {
1007 command_noisy('config',
1008 "svn-remote.$self->{repo_id}.url", $url);
1009 command_noisy('config', '--add',
1010 "svn-remote.$self->{repo_id}.fetch",
1011 "$self->{path}:".$self->refname);
1013 $self->{url} = $url;
1016 sub find_by_url { # repos_root and, path are optional
1017 my ($class, $full_url, $repos_root, $path) = @_;
1018 my $remotes = read_all_remotes();
1019 if (defined $full_url && defined $repos_root && !defined $path) {
1021 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1023 foreach my $repo_id (keys %$remotes) {
1024 my $u = $remotes->{$repo_id}->{url} or next;
1025 next if defined $repos_root && $repos_root ne $u;
1027 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1028 foreach (qw/branches tags/) {
1029 resolve_local_globs($u, $fetch,
1030 $remotes->{$repo_id}->{$_});
1033 unless (defined $p) {
1035 $p =~ s#^\Q$u\E(?:/|$)## or next;
1037 foreach my $f (keys %$fetch) {
1039 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1046 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1047 my $self = _new($class, $repo_id, $ref_id, $path);
1049 $self->init_remote_config($url, $no_write);
1056 foreach (command(qw/config -l/)) {
1057 next unless m!^svn-remote\.(.+)\.fetch=
1058 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1059 my ($repo_id, $path, $ref) = ($1, $2, $3);
1060 if ($ref eq $ref_id) {
1061 $path = '' if ($path =~ m#^\./?#);
1062 return ($repo_id, $path);
1065 (undef, undef, undef);
1069 my ($class, $ref_id, $repo_id, $path) = @_;
1070 if (defined $ref_id && !defined $repo_id && !defined $path) {
1071 ($repo_id, $path) = find_ref($ref_id);
1072 if (!defined $repo_id) {
1073 die "Could not find a \"svn-remote.*.fetch\" key ",
1074 "in the repository configuration matching: ",
1075 "refs/remotes/$ref_id\n";
1078 my $self = _new($class, $repo_id, $ref_id, $path);
1079 if (!defined $self->{path} || !length $self->{path}) {
1080 my $fetch = command_oneline('config', '--get',
1081 "svn-remote.$repo_id.fetch",
1082 ":refs/remotes/$ref_id\$") or
1083 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1084 "\":refs/remotes/$ref_id\$\" in config\n";
1085 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1087 $self->{url} = command_oneline('config', '--get',
1088 "svn-remote.$repo_id.url") or
1089 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1094 sub refname { "refs/remotes/$_[0]->{ref_id}" }
1098 return $self->{svm}->{uuid} if $self->svm;
1100 unless ($self->{svm}) {
1101 die "SVM UUID not cached, and reading remotely failed\n";
1103 $self->{svm}->{uuid};
1108 return $self->{svm} if $self->{svm};
1110 # see if we have it in our config, first:
1112 my $section = "svn-remote.$self->{repo_id}";
1114 source => tmp_config('--get', "$section.svm-source"),
1115 uuid => tmp_config('--get', "$section.svm-uuid"),
1118 $self->{svm} = $svm if ($svm && $svm->{source} && $svm->{uuid});
1123 my ($self, $ra) = @_;
1124 return $ra if $self->svm;
1126 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1127 "(svm:source, svm:mirror, svm:mirror) ",
1128 "from the following URLs:\n" );
1129 sub read_svm_props {
1130 my ($self, $props) = @_;
1131 my $src = $props->{'svm:source'};
1132 my $mirror = $props->{'svm:mirror'};
1133 my $uuid = $props->{'svm:uuid'};
1134 return undef if (!$src || !$mirror || !$uuid);
1136 chomp($src, $mirror, $uuid);
1138 $uuid =~ m{^[0-9a-f\-]{30,}$}
1139 or die "doesn't look right - svm:uuid is '$uuid'\n";
1140 # don't know what a '!' is there for, also the
1141 # username is of no interest
1142 $src =~ s{/?!$}{$mirror};
1143 $src =~ s{/+$}{}; # no trailing slashes please
1144 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1146 my $section = "svn-remote.$self->{repo_id}";
1147 tmp_config('--add', "$section.svm-source", $src);
1148 tmp_config('--add', "$section.svm-uuid", $uuid);
1149 $self->{svm} = { source => $src , uuid => $uuid };
1153 my $r = $ra->get_latest_revnum;
1154 my $path = $self->{path};
1155 my @tried_a = ($path);
1156 while (length $path) {
1157 if ($self->read_svm_props(($ra->get_dir($path, $r))[2])) {
1160 $path =~ s#/?[^/]+$## && push @tried_a, $path;
1162 if ($self->read_svm_props(($ra->get_dir('', $r))[2])) {
1166 if ($ra->{repos_root} eq $self->{url}) {
1167 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n";
1170 # nope, make sure we're connected to the repository root:
1173 $path = $ra->{svn_path};
1174 $path =~ s#/?[^/]+$##; # we already tried this one above
1175 $ra = Git::SVN::Ra->new($ra->{repos_root});
1176 while (length $path) {
1177 $ok = $self->read_svm_props(($ra->get_dir($path, $r))[2]);
1179 $path =~ s#/?[^/]+$## && push @tried_b, $path;
1181 $ok = $self->read_svm_props(($ra->get_dir('', $r))[2]) unless $ok;
1183 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n",
1184 map { " $ra->{url}/$_\n" } @tried_b, "\n"
1186 Git::SVN::Ra->new($self->{url});
1189 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1190 # remote lookup (useful for 'git svn log').
1193 unless ($self->{ra_uuid}) {
1194 my $key = "svn-remote.$self->{repo_id}.uuid";
1195 my $uuid = eval { tmp_config('--get', $key) };
1196 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1197 $self->{ra_uuid} = $uuid;
1199 die "ra_uuid called without URL\n" unless $self->{url};
1200 $self->{ra_uuid} = $self->ra->get_uuid;
1201 tmp_config('--add', $key, $self->{ra_uuid});
1209 my $ra = Git::SVN::Ra->new($self->{url});
1210 if ($self->use_svm_props && !$self->{svm}) {
1211 if ($self->no_metadata) {
1212 die "Can't have both 'noMetadata' and ",
1213 "'useSvmProps' options set!\n";
1215 $ra = $self->_set_svm_vars($ra);
1216 $self->{-want_revprops} = 1;
1223 my $repos_root = $self->ra->{repos_root};
1224 return $self->{path} if ($self->{url} eq $repos_root);
1225 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
1226 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
1229 sub traverse_ignore {
1230 my ($self, $fh, $path, $r) = @_;
1233 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
1235 $p =~ s#^\Q$ra->{svn_path}\E/##;
1236 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1237 if (my $s = $props->{'svn:ignore'}) {
1238 $s =~ s/[\r\n]+/\n/g;
1240 if (length $p == 0) {
1244 $s =~ s#\n#\n/$p/#g;
1245 print $fh "/$p/$s\n";
1248 foreach (sort keys %$dirent) {
1249 next if $dirent->{$_}->kind != $SVN::Node::dir;
1250 $self->traverse_ignore($fh, "$path/$_", $r);
1254 sub last_rev { ($_[0]->last_rev_commit)[0] }
1255 sub last_commit { ($_[0]->last_rev_commit)[1] }
1257 # returns the newest SVN revision number and newest commit SHA1
1258 sub last_rev_commit {
1260 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1261 return ($self->{last_rev}, $self->{last_commit});
1263 my $c = ::verify_ref($self->refname.'^0');
1264 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1265 my $rev = (::cmt_metadata($c))[1];
1267 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1271 my $db_path = $self->db_path;
1272 unless (-e $db_path) {
1273 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1274 return (undef, undef);
1276 my $offset = -41; # from tail
1278 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1279 sysseek($fh, $offset, 2); # don't care for errors
1280 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1282 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1284 sysseek($fh, $offset, 2); # don't care for errors
1285 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1288 if ($c && $c ne $rl) {
1289 die "$db_path and ", $self->refname,
1290 " inconsistent!:\n$c != $rl\n";
1292 my $rev = sysseek($fh, 0, 1) or croak $!;
1293 $rev = ($rev - 41) / 41;
1294 close $fh or croak $!;
1295 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1299 sub get_fetch_range {
1300 my ($self, $min, $max) = @_;
1301 $max ||= $self->ra->get_latest_revnum;
1302 $min ||= $self->rev_db_max;
1308 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1309 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1310 if (-e $old_def_config && ! -e $config) {
1311 rename $old_def_config, $config or
1312 die "Failed rename $old_def_config => $config: $!\n";
1314 my $old_config = $ENV{GIT_CONFIG};
1315 $ENV{GIT_CONFIG} = $config;
1318 unless (-f $config) {
1320 open my $fh, '>', $config or
1321 die "Can't open $config: $!\n";
1322 print $fh "; This file is used internally by ",
1324 "Couldn't write to $config: $!\n";
1325 print $fh "; You should not have to edit it\n" or
1326 die "Couldn't write to $config: $!\n";
1327 close $fh or die "Couldn't close $config: $!\n";
1329 command('config', @args);
1332 if (defined $old_config) {
1333 $ENV{GIT_CONFIG} = $old_config;
1335 delete $ENV{GIT_CONFIG};
1338 wantarray ? @ret : $ret[0];
1342 my ($self, $sub) = @_;
1343 my $old_index = $ENV{GIT_INDEX_FILE};
1344 $ENV{GIT_INDEX_FILE} = $self->{index};
1347 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1348 mkpath([$dir]) unless -d $dir;
1352 if (defined $old_index) {
1353 $ENV{GIT_INDEX_FILE} = $old_index;
1355 delete $ENV{GIT_INDEX_FILE};
1358 wantarray ? @ret : $ret[0];
1361 sub assert_index_clean {
1362 my ($self, $treeish) = @_;
1364 $self->tmp_index_do(sub {
1365 command_noisy('read-tree', $treeish) unless -e $self->{index};
1366 my $x = command_oneline('write-tree');
1367 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1368 /^tree ($::sha1)/mo);
1371 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1372 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1373 command_noisy('read-tree', $treeish);
1374 $x = command_oneline('write-tree');
1376 ::fatal "trees ($treeish) $y != $x\n",
1377 "Something is seriously wrong...\n";
1382 sub get_commit_parents {
1383 my ($self, $log_entry) = @_;
1384 my (%seen, @ret, @tmp);
1385 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1386 if (my $ip = $self->{inject_parents}) {
1387 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1391 if (my $cur = ::verify_ref($self->refname.'^0')) {
1394 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1395 while (my $p = shift @tmp) {
1399 # MAXPARENT is defined to 16 in commit-tree.c:
1403 die "r$log_entry->{revision}: No room for parents:\n\t",
1404 join("\n\t", @tmp), "\n";
1411 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1412 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1413 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1416 if ($rwr !~ m#^[a-z\+]+://#) {
1417 die "$rwr is not a valid URL (key: $k)\n";
1420 $self->{-rewrite_root} = $rwr;
1425 ($self->rewrite_root || $self->{url}) .
1426 (length $self->{path} ? '/' . $self->{path} : '');
1431 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1435 my ($self, $log_entry) = @_;
1436 my $lr = $self->last_rev;
1437 if (defined $lr && $lr >= $log_entry->{revision}) {
1438 die "Last fetched revision of ", $self->refname,
1439 " was r$lr, but we are about to fetch: ",
1440 "r$log_entry->{revision}!\n";
1442 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1443 croak "$log_entry->{revision} = $c already exists! ",
1444 "Why are we refetching it?\n";
1446 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1447 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1448 $log_entry->{email};
1449 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1451 my $tree = $log_entry->{tree};
1452 if (!defined $tree) {
1453 $tree = $self->tmp_index_do(sub {
1454 command_oneline('write-tree') });
1456 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1458 my @exec = ('git-commit-tree', $tree);
1459 foreach ($self->get_commit_parents($log_entry)) {
1460 push @exec, '-p', $_;
1462 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1464 print $msg_fh $log_entry->{log} or croak $!;
1465 unless ($self->no_metadata) {
1466 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1469 $msg_fh->flush == 0 or croak $!;
1470 close $msg_fh or croak $!;
1471 chomp(my $commit = do { local $/; <$out_fh> });
1472 close $out_fh or croak $!;
1475 if ($commit !~ /^$::sha1$/o) {
1476 die "Failed to commit, invalid sha1: $commit\n";
1479 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1481 $self->{last_rev} = $log_entry->{revision};
1482 $self->{last_commit} = $commit;
1483 print "r$log_entry->{revision}";
1484 if (defined $log_entry->{svm_revision}) {
1485 print " (\@$log_entry->{svm_revision})";
1486 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1487 0, $self->svm_uuid);
1489 print " = $commit ($self->{ref_id})\n";
1490 if (defined $_repack && (--$_repack_nr == 0)) {
1491 $_repack_nr = $_repack;
1492 # repack doesn't use any arguments with spaces in them, does it?
1493 print "Running git repack $_repack_flags ...\n";
1494 command_noisy('repack', split(/\s+/, $_repack_flags));
1495 print "Done repacking\n";
1501 my ($self, $paths, $r) = @_;
1502 return 1 if $self->{path} eq '';
1503 if (my $path = $paths->{"/$self->{path}"}) {
1504 return ($path->{action} eq 'D') ? 0 : 1;
1506 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1507 if (grep /$self->{path_regex}/, keys %$paths) {
1511 foreach (split m#/#, $self->{path}) {
1513 next unless ($paths->{$c} &&
1514 ($paths->{$c}->{action} =~ /^[AR]$/));
1515 if ($self->ra->check_path($self->{path}, $r) ==
1523 sub find_parent_branch {
1524 my ($self, $paths, $rev) = @_;
1525 return undef unless $self->follow_parent;
1526 unless (defined $paths) {
1527 my $err_handler = $SVN::Error::handler;
1528 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1529 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1531 Git::SVN::Ra::dup_changed_paths($_[0]) });
1532 $SVN::Error::handler = $err_handler;
1534 return undef unless defined $paths;
1536 # look for a parent from another branch:
1537 my @b_path_components = split m#/#, $self->rel_path;
1538 my @a_path_components;
1540 while (@b_path_components) {
1541 $i = $paths->{'/'.join('/', @b_path_components)};
1542 last if $i && defined $i->{copyfrom_path};
1543 unshift(@a_path_components, pop(@b_path_components));
1545 return undef unless defined $i && defined $i->{copyfrom_path};
1546 my $branch_from = $i->{copyfrom_path};
1547 if (@a_path_components) {
1548 print STDERR "branch_from: $branch_from => ";
1549 $branch_from .= '/'.join('/', @a_path_components);
1550 print STDERR $branch_from, "\n";
1552 my $r = $i->{copyfrom_rev};
1553 my $repos_root = $self->ra->{repos_root};
1554 my $url = $self->ra->{url};
1555 my $new_url = $repos_root . $branch_from;
1556 print STDERR "Found possible branch point: ",
1557 "$new_url => ", $self->full_url, ", $r\n";
1558 $branch_from =~ s#^/##;
1559 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1561 my $ref_id = $self->{ref_id};
1562 $ref_id =~ s/\@\d+$//;
1564 # just grow a tail if we're not unique enough :x
1565 $ref_id .= '-' while find_ref($ref_id);
1566 print STDERR "Initializing parent: $ref_id\n";
1567 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1569 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1570 if (!defined $r0 || !defined $parent) {
1572 ($r0, $parent) = $gs->last_rev_commit;
1574 if (defined $r0 && defined $parent) {
1575 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
1576 $self->assert_index_clean($parent);
1578 if ($self->ra->can_do_switch) {
1579 print STDERR "Following parent with do_switch\n";
1580 # do_switch works with svn/trunk >= r22312, but that
1581 # is not included with SVN 1.4.3 (the latest version
1582 # at the moment), so we can't rely on it
1583 $self->{last_commit} = $parent;
1584 $ed = SVN::Git::Fetcher->new($self);
1585 $gs->ra->gs_do_switch($r0, $rev, $gs,
1586 $self->full_url, $ed)
1587 or die "SVN connection failed somewhere...\n";
1589 print STDERR "Following parent with do_update\n";
1590 $ed = SVN::Git::Fetcher->new($self);
1591 $self->ra->gs_do_update($rev, $rev, $self, $ed)
1592 or die "SVN connection failed somewhere...\n";
1594 print STDERR "Successfully followed parent\n";
1595 return $self->make_log_entry($rev, [$parent], $ed);
1601 my ($self, $paths, $rev) = @_;
1603 my ($last_rev, @parents);
1604 if (my $lc = $self->last_commit) {
1605 # we can have a branch that was deleted, then re-added
1606 # under the same name but copied from another path, in
1607 # which case we'll have multiple parents (we don't
1608 # want to break the original ref, nor lose copypath info):
1609 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1610 push @{$log_entry->{parents}}, $lc;
1613 $ed = SVN::Git::Fetcher->new($self);
1614 $last_rev = $self->{last_rev};
1619 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1622 $ed = SVN::Git::Fetcher->new($self);
1624 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
1625 die "SVN connection failed somewhere...\n";
1627 $self->make_log_entry($rev, \@parents, $ed);
1631 my ($self, $ed) = @_;
1633 my $h = $ed->{empty};
1634 foreach (sort keys %$h) {
1635 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
1636 push @out, " $act: " . uri_encode($_);
1637 warn "W: $act: $_\n";
1639 foreach my $t (qw/dir_prop file_prop/) {
1640 $h = $ed->{$t} or next;
1641 foreach my $path (sort keys %$h) {
1642 my $ppath = $path eq '' ? '.' : $path;
1643 foreach my $prop (sort keys %{$h->{$path}}) {
1644 next if $SKIP_PROP{$prop};
1645 my $v = $h->{$path}->{$prop};
1646 my $t_ppath_prop = "$t: " .
1647 uri_encode($ppath) . ' ' .
1650 push @out, " +$t_ppath_prop " .
1653 push @out, " -$t_ppath_prop";
1658 foreach my $t (qw/absent_file absent_directory/) {
1659 $h = $ed->{$t} or next;
1660 foreach my $parent (sort keys %$h) {
1661 foreach my $path (sort @{$h->{$parent}}) {
1662 push @out, " $t: " .
1663 uri_encode("$parent/$path");
1664 warn "W: $t: $parent/$path ",
1665 "Insufficient permissions?\n";
1672 sub parse_svn_date {
1673 my $date = shift || return '+0000 1970-01-01 00:00:00';
1674 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1675 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1676 croak "Unable to parse date: $date\n";
1677 "+0000 $Y-$m-$d $H:$M:$S";
1682 if (!defined $author || length $author == 0) {
1683 $author = '(no author)';
1685 if (defined $::_authors && ! defined $::users{$author}) {
1686 die "Author: $author not defined in $::_authors file\n";
1691 sub make_log_entry {
1692 my ($self, $rev, $parents, $ed) = @_;
1693 my $untracked = $self->get_untracked($ed);
1695 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
1696 print $un "r$rev\n" or croak $!;
1697 print $un $_, "\n" foreach @$untracked;
1698 my %log_entry = ( parents => $parents || [], revision => $rev,
1702 my $logged = delete $self->{logged_rev_props};
1703 if (!$logged || $self->{-want_revprops}) {
1704 my $rp = $self->ra->rev_proplist($rev);
1705 foreach (sort keys %$rp) {
1707 if (/^svn:(author|date|log)$/) {
1708 $log_entry{$1} = $v;
1709 } elsif ($_ eq 'svm:headrev') {
1712 print $un " rev_prop: ", uri_encode($_), ' ',
1713 uri_encode($v), "\n";
1717 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
1719 close $un or croak $!;
1721 $log_entry{date} = parse_svn_date($log_entry{date});
1722 $log_entry{log} .= "\n";
1723 my $author = $log_entry{author} = check_author($log_entry{author});
1724 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1726 if (defined $headrev && $self->use_svm_props) {
1727 if ($self->rewrite_root) {
1728 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1731 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1732 if ($uuid ne $self->{svm}->{uuid}) {
1733 die "UUID mismatch on SVM path:\n",
1734 "expected: $self->{svm}->{uuid}\n",
1737 my $full_url = $self->{svm}->{source};
1738 $full_url .= "/$self->{path}" if length $self->{path};
1739 $log_entry{metadata} = "$full_url\@$r $uuid";
1740 $log_entry{svm_revision} = $r;
1741 $email ||= "$author\@$uuid"
1743 $log_entry{metadata} = $self->metadata_url. "\@$rev " .
1744 $self->ra->get_uuid;
1745 $email ||= "$author\@" . $self->ra->get_uuid;
1747 $log_entry{name} = $name;
1748 $log_entry{email} = $email;
1753 my ($self, $min_rev, $max_rev, @parents) = @_;
1754 my ($last_rev, $last_commit) = $self->last_rev_commit;
1755 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
1756 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
1760 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1761 $self->{inject_parents} = { $rev => $tree };
1762 $self->fetch(undef, undef);
1766 my ($self, $tree) = (shift, shift);
1767 my $log_entry = ::get_commit_entry($tree);
1768 unless ($self->{last_rev}) {
1769 fatal("Must have an existing revision to commit\n");
1771 my %ed_opts = ( r => $self->{last_rev},
1772 log => $log_entry->{log},
1774 tree_a => $self->{last_commit},
1777 $self->set_tree_cb($log_entry, $tree, @_) },
1778 svn_path => $self->{path} );
1779 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1780 print "No changes\nr$self->{last_rev} = $tree\n";
1786 my $db_path = $self->db_path;
1787 return if (-e $db_path && ! -z $db_path);
1788 return unless ::verify_ref($self->refname.'^0');
1789 if (-f $self->{db_root}) {
1790 rename $self->{db_root}, $db_path or die
1791 "rename $self->{db_root} => $db_path failed: $!\n";
1792 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1793 symlink $base, $self->{db_root} or die
1794 "symlink $base => $self->{db_root} failed: $!\n";
1797 print "Rebuilding $db_path ...\n";
1798 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1800 my $full_url = $self->full_url;
1802 while (<$rev_list>) {
1805 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1806 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1808 # ignore merges (from set-tree)
1809 next if (!defined $rev || !$uuid);
1811 # if we merged or otherwise started elsewhere, this is
1812 # how we break out of it
1813 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1814 ($full_url && $url && ($url ne $full_url))) {
1818 $svn_uuid ||= $uuid;
1820 $self->rev_db_set($rev, $c);
1821 print "r$rev = $c\n";
1823 command_close_pipe($rev_list, $ctx);
1824 print "Done rebuilding $db_path\n";
1828 # Tie::File seems to be prone to offset errors if revisions get sparse,
1829 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
1830 # one of my favorite modules is out :< Next up would be one of the DBM
1831 # modules, but I'm not sure which is most portable... So I'll just
1832 # go with something that's plain-text, but still capable of
1833 # being randomly accessed. So here's my ultra-simple fixed-width
1834 # database. All records are 40 characters + "\n", so it's easy to seek
1835 # to a revision: (41 * rev) is the byte offset.
1836 # A record of 40 0s denotes an empty revision.
1837 # And yes, it's still pretty fast (faster than Tie::File).
1838 # These files are disposable unless noMetadata or useSvmProps is set
1841 my ($fh, $rev, $commit) = @_;
1842 my $offset = $rev * 41;
1843 # assume that append is the common case:
1844 seek $fh, 0, 2 or croak $!;
1846 if ($pos < $offset) {
1847 for (1 .. (($offset - $pos) / 41)) {
1848 print $fh (('0' x 40),"\n") or croak $!;
1851 seek $fh, $offset, 0 or croak $!;
1852 print $fh $commit,"\n" or croak $!;
1858 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1859 mkpath([$dir]) unless -d $dir;
1860 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1861 close $fh or die "Couldn't close (create) $path: $!\n";
1866 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1867 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1868 my $db = $self->db_path($uuid);
1869 my $db_lock = "$db.lock";
1872 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1873 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1877 $LOCKFILES{$db_lock} = 1;
1879 # both of these options make our .rev_db file very, very important
1880 # and we can't afford to lose it because rebuild() won't work
1881 if ($self->use_svm_props || $self->no_metadata) {
1883 copy($db, $db_lock) or die "rev_db_set(@_): ",
1885 "$db => $db_lock ($!)\n";
1887 rename $db, $db_lock or die "rev_db_set(@_): ",
1888 "Failed to rename: ",
1889 "$db => $db_lock ($!)\n";
1891 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
1892 _rev_db_set($fh, $rev, $commit);
1894 $fh->flush or die "Couldn't flush $db_lock: $!\n";
1895 $fh->sync or die "Couldn't sync $db_lock: $!\n";
1897 close $fh or croak $!;
1900 command_noisy('update-ref', '-m', "r$rev",
1901 $self->refname, $commit);
1903 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1904 "$db_lock => $db ($!)\n";
1905 delete $LOCKFILES{$db_lock};
1907 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1908 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1909 kill $sig, $$ if defined $sig;
1916 my $db_path = $self->db_path;
1917 my @stat = stat $db_path or return 0;
1918 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
1919 my $max = $stat[7] / 41;
1920 (($max > 0) ? $max - 1 : 0);
1924 my ($self, $rev, $uuid) = @_;
1926 my $offset = $rev * 41;
1927 my $db_path = $self->db_path($uuid);
1928 return undef unless -e $db_path;
1929 open my $fh, '<', $db_path or croak $!;
1930 if (sysseek($fh, $offset, 0) == $offset) {
1931 my $read = sysread($fh, $ret, 40);
1932 $ret = undef if ($read != 40 || $ret eq ('0'x40));
1934 close $fh or croak $!;
1938 sub find_rev_before {
1939 my ($self, $rev, $eq_ok) = @_;
1940 --$rev unless $eq_ok;
1942 if (my $c = $self->rev_db_get($rev)) {
1947 return (undef, undef);
1951 my ($class, $repo_id, $ref_id, $path) = @_;
1952 unless (defined $repo_id && length $repo_id) {
1953 $repo_id = $Git::SVN::default_repo_id;
1955 unless (defined $ref_id && length $ref_id) {
1956 $_[2] = $ref_id = $Git::SVN::default_ref_id;
1958 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1959 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1960 $_[3] = $path = '' unless (defined $path);
1961 mkpath(["$ENV{GIT_DIR}/svn"]);
1963 ref_id => $ref_id, dir => $dir, index => "$dir/index",
1964 path => $path, config => "$ENV{GIT_DIR}/svn/config",
1965 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
1969 my ($self, $uuid) = @_;
1970 $uuid ||= $self->ra_uuid;
1971 "$self->{db_root}.$uuid";
1976 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1980 package Git::SVN::Prompt;
1984 use vars qw/$_no_auth_cache $_username/;
1987 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1988 $may_save = undef if $_no_auth_cache;
1989 $default_username = $_username if defined $_username;
1990 if (defined $default_username && length $default_username) {
1991 if (defined $realm && length $realm) {
1992 print STDERR "Authentication realm: $realm\n";
1995 $cred->username($default_username);
1997 username($cred, $realm, $may_save, $pool);
1999 $cred->password(_read_password("Password for '" .
2000 $cred->username . "': ", $realm));
2001 $cred->may_save($may_save);
2002 $SVN::_Core::SVN_NO_ERROR;
2005 sub ssl_server_trust {
2006 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2007 $may_save = undef if $_no_auth_cache;
2008 print STDERR "Error validating server certificate for '$realm':\n";
2009 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2010 print STDERR " - The certificate is not issued by a trusted ",
2011 "authority. Use the\n",
2012 " fingerprint to validate the certificate manually!\n";
2014 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2015 print STDERR " - The certificate hostname does not match.\n";
2017 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2018 print STDERR " - The certificate is not yet valid.\n";
2020 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2021 print STDERR " - The certificate has expired.\n";
2023 if ($failures & $SVN::Auth::SSL::OTHER) {
2024 print STDERR " - The certificate has an unknown error.\n";
2027 "Certificate information:\n".
2028 " - Hostname: %s\n".
2029 " - Valid: from %s until %s\n".
2031 " - Fingerprint: %s\n",
2032 map $cert_info->$_, qw(hostname valid_from valid_until
2033 issuer_dname fingerprint);
2036 print STDERR $may_save ?
2037 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2038 "(R)eject or accept (t)emporarily? ";
2040 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2041 if ($choice =~ /^t$/i) {
2042 $cred->may_save(undef);
2043 } elsif ($choice =~ /^r$/i) {
2045 } elsif ($may_save && $choice =~ /^p$/i) {
2046 $cred->may_save($may_save);
2050 $cred->accepted_failures($failures);
2051 $SVN::_Core::SVN_NO_ERROR;
2054 sub ssl_client_cert {
2055 my ($cred, $realm, $may_save, $pool) = @_;
2056 $may_save = undef if $_no_auth_cache;
2057 print STDERR "Client certificate filename: ";
2059 chomp(my $filename = <STDIN>);
2060 $cred->cert_file($filename);
2061 $cred->may_save($may_save);
2062 $SVN::_Core::SVN_NO_ERROR;
2065 sub ssl_client_cert_pw {
2066 my ($cred, $realm, $may_save, $pool) = @_;
2067 $may_save = undef if $_no_auth_cache;
2068 $cred->password(_read_password("Password: ", $realm));
2069 $cred->may_save($may_save);
2070 $SVN::_Core::SVN_NO_ERROR;
2074 my ($cred, $realm, $may_save, $pool) = @_;
2075 $may_save = undef if $_no_auth_cache;
2076 if (defined $realm && length $realm) {
2077 print STDERR "Authentication realm: $realm\n";
2080 if (defined $_username) {
2081 $username = $_username;
2083 print STDERR "Username: ";
2085 chomp($username = <STDIN>);
2087 $cred->username($username);
2088 $cred->may_save($may_save);
2089 $SVN::_Core::SVN_NO_ERROR;
2092 sub _read_password {
2093 my ($prompt, $realm) = @_;
2094 print STDERR $prompt;
2096 require Term::ReadKey;
2097 Term::ReadKey::ReadMode('noecho');
2099 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2100 last if $key =~ /[\012\015]/; # \n\r
2103 Term::ReadKey::ReadMode('restore');
2112 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2113 $SVN::Node::dir.$SVN::Node::unknown.
2114 $SVN::Node::none.$SVN::Node::file.
2115 $SVN::Node::dir.$SVN::Node::unknown.
2116 $SVN::Auth::SSL::CNMISMATCH.
2117 $SVN::Auth::SSL::NOTYETVALID.
2118 $SVN::Auth::SSL::EXPIRED.
2119 $SVN::Auth::SSL::UNKNOWNCA.
2120 $SVN::Auth::SSL::OTHER;
2123 package SVN::Git::Fetcher;
2131 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2133 my ($class, $git_svn) = @_;
2134 my $self = SVN::Delta::Editor->new;
2135 bless $self, $class;
2136 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2137 $self->{empty} = {};
2138 $self->{dir_prop} = {};
2139 $self->{file_prop} = {};
2140 $self->{absent_dir} = {};
2141 $self->{absent_file} = {};
2142 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2146 sub set_path_strip {
2147 my ($self, $path) = @_;
2148 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2155 sub open_directory {
2156 my ($self, $path, $pb, $rev) = @_;
2161 my ($self, $path) = @_;
2162 if ($self->{path_strip}) {
2163 $path =~ s!$self->{path_strip}!! or
2164 die "Failed to strip path '$path' ($self->{path_strip})\n";
2170 my ($self, $path, $rev, $pb) = @_;
2172 my $gpath = $self->git_path($path);
2173 return undef if ($gpath eq '');
2175 # remove entire directories.
2176 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2177 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2179 $self->{c}, '--', $gpath);
2183 $self->{gii}->remove($_);
2184 print "\tD\t$_\n" unless $::_q;
2186 print "\tD\t$gpath/\n" unless $::_q;
2187 command_close_pipe($ls, $ctx);
2188 $self->{empty}->{$path} = 0
2190 $self->{gii}->remove($gpath);
2191 print "\tD\t$gpath\n" unless $::_q;
2197 my ($self, $path, $pb, $rev) = @_;
2198 my $gpath = $self->git_path($path);
2199 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2200 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2201 unless (defined $mode && defined $blob) {
2202 die "$path was not found in commit $self->{c} (r$rev)\n";
2204 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2205 pool => SVN::Pool->new, action => 'M' };
2209 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2210 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2211 delete $self->{empty}->{$dir};
2212 { path => $path, mode_a => 100644, mode_b => 100644,
2213 pool => SVN::Pool->new, action => 'A' };
2217 my ($self, $path, $cp_path, $cp_rev) = @_;
2218 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2219 delete $self->{empty}->{$dir};
2220 $self->{empty}->{$path} = 1;
2224 sub change_dir_prop {
2225 my ($self, $db, $prop, $value) = @_;
2226 $self->{dir_prop}->{$db->{path}} ||= {};
2227 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2231 sub absent_directory {
2232 my ($self, $path, $pb) = @_;
2233 $self->{absent_dir}->{$pb->{path}} ||= [];
2234 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2239 my ($self, $path, $pb) = @_;
2240 $self->{absent_file}->{$pb->{path}} ||= [];
2241 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2245 sub change_file_prop {
2246 my ($self, $fb, $prop, $value) = @_;
2247 if ($prop eq 'svn:executable') {
2248 if ($fb->{mode_b} != 120000) {
2249 $fb->{mode_b} = defined $value ? 100755 : 100644;
2251 } elsif ($prop eq 'svn:special') {
2252 $fb->{mode_b} = defined $value ? 120000 : 100644;
2254 $self->{file_prop}->{$fb->{path}} ||= {};
2255 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2260 sub apply_textdelta {
2261 my ($self, $fb, $exp) = @_;
2262 my $fh = IO::File->new_tmpfile;
2264 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2265 # (but $base does not,) so dup() it for reading in close_file
2266 open my $dup, '<&', $fh or croak $!;
2267 my $base = IO::File->new_tmpfile;
2268 $base->autoflush(1);
2270 defined (my $pid = fork) or croak $!;
2272 open STDOUT, '>&', $base or croak $!;
2273 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2274 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2280 seek $base, 0, 0 or croak $!;
2281 my $md5 = Digest::MD5->new;
2282 $md5->addfile($base);
2283 my $got = $md5->hexdigest;
2284 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2286 " got: $got\n" if ($got ne $exp);
2289 seek $base, 0, 0 or croak $!;
2291 $fb->{base} = $base;
2292 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2296 my ($self, $fb, $exp) = @_;
2298 my $path = $self->git_path($fb->{path});
2299 if (my $fh = $fb->{fh}) {
2300 seek($fh, 0, 0) or croak $!;
2301 my $md5 = Digest::MD5->new;
2303 my $got = $md5->hexdigest;
2304 die "Checksum mismatch: $path\n",
2305 "expected: $exp\n got: $got\n" if ($got ne $exp);
2306 seek($fh, 0, 0) or croak $!;
2307 if ($fb->{mode_b} == 120000) {
2308 read($fh, my $buf, 5) == 5 or croak $!;
2309 $buf eq 'link ' or die "$path has mode 120000",
2310 "but is not a link\n";
2312 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2314 open STDIN, '<&', $fh or croak $!;
2315 exec qw/git-hash-object -w --stdin/ or croak $!;
2317 chomp($hash = do { local $/; <$out> });
2318 close $out or croak $!;
2319 close $fh or croak $!;
2320 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2321 close $fb->{base} or croak $!;
2323 $hash = $fb->{blob} or die "no blob information\n";
2326 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2327 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2333 $self->{nr} = $self->{gii}->{nr};
2334 delete $self->{gii};
2335 $self->SUPER::abort_edit(@_);
2340 $self->{git_commit_ok} = 1;
2341 $self->{nr} = $self->{gii}->{nr};
2342 delete $self->{gii};
2343 $self->SUPER::close_edit(@_);
2346 package SVN::Git::Editor;
2347 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2355 my ($class, $opts) = @_;
2356 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2357 die "$_ required!\n" unless (defined $opts->{$_});
2360 my $pool = SVN::Pool->new;
2361 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2362 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2365 # $opts->{ra} functions should not be used after this:
2366 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2367 $opts->{editor_cb}, $pool);
2368 my $self = SVN::Delta::Editor->new(@ce, $pool);
2369 bless $self, $class;
2370 foreach (qw/svn_path r tree_a tree_b/) {
2371 $self->{$_} = $opts->{$_};
2373 $self->{url} = $opts->{ra}->{url};
2374 $self->{mods} = $mods;
2375 $self->{types} = $types;
2376 $self->{pool} = $pool;
2377 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2379 $self->{path_prefix} = length $self->{svn_path} ?
2380 "$self->{svn_path}/" : '';
2385 my ($tree_a, $tree_b) = @_;
2386 my @diff_tree = qw(diff-tree -z -r);
2387 if ($_cp_similarity) {
2388 push @diff_tree, "-C$_cp_similarity";
2390 push @diff_tree, '-C';
2392 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2393 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2394 push @diff_tree, $tree_a, $tree_b;
2395 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2399 while (<$diff_fh>) {
2400 chomp $_; # this gets rid of the trailing "\0"
2401 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2402 $::sha1\s($::sha1)\s
2403 ([MTCRAD])\d*$/xo) {
2404 push @mods, { mode_a => $1, mode_b => $2,
2405 sha1_b => $3, chg => $4 };
2406 if ($4 =~ /^(?:C|R)$/) {
2411 } elsif ($state eq 'file_a') {
2412 my $x = $mods[$#mods] or croak "Empty array\n";
2413 if ($x->{chg} !~ /^(?:C|R)$/) {
2414 croak "Error parsing $_, $x->{chg}\n";
2418 } elsif ($state eq 'file_b') {
2419 my $x = $mods[$#mods] or croak "Empty array\n";
2420 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2421 croak "Error parsing $_, $x->{chg}\n";
2423 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2424 croak "Error parsing $_, $x->{chg}\n";
2429 croak "Error parsing $_\n";
2432 command_close_pipe($diff_fh, $ctx);
2436 sub check_diff_paths {
2437 my ($ra, $pfx, $rev, $mods) = @_;
2439 $pfx .= '/' if length $pfx;
2441 sub type_diff_paths {
2442 my ($ra, $types, $path, $rev) = @_;
2443 my @p = split m#/+#, $path;
2445 unless (defined $types->{$c}) {
2446 $types->{$c} = $ra->check_path($c, $rev);
2449 $c .= '/' . shift @p;
2450 next if defined $types->{$c};
2451 $types->{$c} = $ra->check_path($c, $rev);
2455 foreach my $m (@$mods) {
2456 foreach my $f (qw/file_a file_b/) {
2457 next unless defined $m->{$f};
2458 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2459 if (length $pfx.$dir && ! defined $types{$dir}) {
2460 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2468 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2472 my ($self, $path) = @_;
2473 $self->{path_prefix}.(defined $path ? $path : '');
2477 my ($self, $path) = @_;
2478 $self->{url} . '/' . $self->repo_path($path);
2483 my $rm = $self->{rm};
2484 delete $rm->{''}; # we never delete the url we're tracking
2487 foreach (keys %$rm) {
2488 my @d = split m#/#, $_;
2492 $c .= '/' . shift @d;
2496 delete $rm->{$self->{svn_path}};
2497 delete $rm->{''}; # we never delete the url we're tracking
2500 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2505 my @dn = split m#/#, $_;
2507 delete $rm->{join '/', @dn};
2514 command_close_pipe($fh, $ctx);
2516 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2517 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2518 $self->close_directory($bat->{$d}, $p);
2519 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2520 print "\tD+\t$d/\n" unless $::_q;
2521 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2526 sub open_or_add_dir {
2527 my ($self, $full_path, $baton) = @_;
2528 my $t = $self->{types}->{$full_path};
2530 die "$full_path not known in r$self->{r} or we have a bug!\n";
2532 if ($t == $SVN::Node::none) {
2533 return $self->add_directory($full_path, $baton,
2534 undef, -1, $self->{pool});
2535 } elsif ($t == $SVN::Node::dir) {
2536 return $self->open_directory($full_path, $baton,
2537 $self->{r}, $self->{pool});
2539 print STDERR "$full_path already exists in repository at ",
2540 "r$self->{r} and it is not a directory (",
2541 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2546 my ($self, $path) = @_;
2547 my $bat = $self->{bat};
2548 my $repo_path = $self->repo_path($path);
2549 return $bat->{''} unless (length $repo_path);
2550 my @p = split m#/+#, $repo_path;
2552 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2555 $c .= '/' . shift @p;
2556 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2562 my ($self, $m) = @_;
2563 my ($dir, $file) = split_path($m->{file_b});
2564 my $pbat = $self->ensure_path($dir);
2565 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2567 print "\tA\t$m->{file_b}\n" unless $::_q;
2568 $self->chg_file($fbat, $m);
2569 $self->close_file($fbat,undef,$self->{pool});
2573 my ($self, $m) = @_;
2574 my ($dir, $file) = split_path($m->{file_b});
2575 my $pbat = $self->ensure_path($dir);
2576 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2577 $self->url_path($m->{file_a}), $self->{r});
2578 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2579 $self->chg_file($fbat, $m);
2580 $self->close_file($fbat,undef,$self->{pool});
2584 my ($self, $path, $pbat) = @_;
2585 my $rpath = $self->repo_path($path);
2586 my ($dir, $file) = split_path($rpath);
2587 $self->{rm}->{$dir} = 1;
2588 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2592 my ($self, $m) = @_;
2593 my ($dir, $file) = split_path($m->{file_b});
2594 my $pbat = $self->ensure_path($dir);
2595 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2596 $self->url_path($m->{file_a}), $self->{r});
2597 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
2598 $self->chg_file($fbat, $m);
2599 $self->close_file($fbat,undef,$self->{pool});
2601 ($dir, $file) = split_path($m->{file_a});
2602 $pbat = $self->ensure_path($dir);
2603 $self->delete_entry($m->{file_a}, $pbat);
2607 my ($self, $m) = @_;
2608 my ($dir, $file) = split_path($m->{file_b});
2609 my $pbat = $self->ensure_path($dir);
2610 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2611 $pbat,$self->{r},$self->{pool});
2612 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
2613 $self->chg_file($fbat, $m);
2614 $self->close_file($fbat,undef,$self->{pool});
2617 sub T { shift->M(@_) }
2619 sub change_file_prop {
2620 my ($self, $fbat, $pname, $pval) = @_;
2621 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2625 my ($self, $fbat, $m) = @_;
2626 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2627 $self->change_file_prop($fbat,'svn:executable','*');
2628 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2629 $self->change_file_prop($fbat,'svn:executable',undef);
2631 my $fh = IO::File->new_tmpfile or croak $!;
2632 if ($m->{mode_b} =~ /^120/) {
2633 print $fh 'link ' or croak $!;
2634 $self->change_file_prop($fbat,'svn:special','*');
2635 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2636 $self->change_file_prop($fbat,'svn:special',undef);
2638 defined(my $pid = fork) or croak $!;
2640 open STDOUT, '>&', $fh or croak $!;
2641 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2645 $fh->flush == 0 or croak $!;
2646 seek $fh, 0, 0 or croak $!;
2648 my $md5 = Digest::MD5->new;
2649 $md5->addfile($fh) or croak $!;
2650 seek $fh, 0, 0 or croak $!;
2652 my $exp = $md5->hexdigest;
2653 my $pool = SVN::Pool->new;
2654 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2655 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
2656 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
2659 close $fh or croak $!;
2663 my ($self, $m) = @_;
2664 my ($dir, $file) = split_path($m->{file_b});
2665 my $pbat = $self->ensure_path($dir);
2666 print "\tD\t$m->{file_b}\n" unless $::_q;
2667 $self->delete_entry($m->{file_b}, $pbat);
2672 my ($p,$bat) = ($self->{pool}, $self->{bat});
2673 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2674 $self->close_directory($bat->{$_}, $p);
2676 $self->SUPER::close_edit($p);
2682 $self->SUPER::abort_edit($self->{pool});
2687 $self->SUPER::DESTROY(@_);
2688 $self->{pool}->clear;
2691 # this drives the editor
2694 my $mods = $self->{mods};
2695 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
2696 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
2698 if (defined $o{$f}) {
2701 fatal("Invalid change type: $f\n");
2704 $self->rmdirs if $_rmdir;
2710 return scalar @$mods;
2713 package Git::SVN::Ra;
2714 use vars qw/@ISA $config_dir $_log_window_size/;
2717 my ($can_do_switch);
2721 # enforce temporary pool usage for some simple functions
2723 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
2726 my \$pool = SVN::Pool->new;
2727 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2729 wantarray ? \@ret : \$ret[0]; }\n";
2732 # get_dir needs $pool held in cache for dirents to work,
2733 # check_path is cacheable and rev_proplist is close enough
2735 foreach (qw/check_path get_dir rev_proplist/) {
2736 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2739 my \$k = join(\"\\0\", \@_);
2740 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2741 return wantarray ? \@\$x : \$x->[0];
2743 my \$pool = SVN::Pool->new;
2744 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2745 if (\$r != \$${_}_rev) {
2746 \%${_}_cache = ( pool => [] );
2749 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2750 push \@{\$${_}_cache{pool}}, \$pool;
2751 wantarray ? \@ret : \$ret[0]; }\n";
2758 my ($class, $url) = @_;
2760 return $RA if ($RA && $RA->{url} eq $url);
2762 SVN::_Core::svn_config_ensure($config_dir, undef);
2763 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2764 SVN::Client::get_simple_provider(),
2765 SVN::Client::get_ssl_server_trust_file_provider(),
2766 SVN::Client::get_simple_prompt_provider(
2767 \&Git::SVN::Prompt::simple, 2),
2768 SVN::Client::get_ssl_client_cert_prompt_provider(
2769 \&Git::SVN::Prompt::ssl_client_cert, 2),
2770 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2771 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2772 SVN::Client::get_username_provider(),
2773 SVN::Client::get_ssl_server_trust_prompt_provider(
2774 \&Git::SVN::Prompt::ssl_server_trust),
2775 SVN::Client::get_username_prompt_provider(
2776 \&Git::SVN::Prompt::username, 2),
2778 my $config = SVN::Core::config_get_config($config_dir);
2779 my $self = SVN::Ra->new(url => $url, auth => $baton,
2781 pool => SVN::Pool->new,
2782 auth_provider_callbacks => $callbacks);
2783 $self->{svn_path} = $url;
2784 $self->{repos_root} = $self->get_repos_root;
2785 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
2786 $RA = bless $self, $class;
2790 # do not call the real DESTROY since we store ourselves in $RA
2794 my ($self, @args) = @_;
2795 my $pool = SVN::Pool->new;
2796 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2797 my $ret = $self->SUPER::get_log(@args, $pool);
2802 sub get_commit_editor {
2803 my ($self, $log, $cb, $pool) = @_;
2804 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
2805 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
2809 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2810 my $new = ($rev_a == $rev_b);
2811 my $path = $gs->{path};
2813 my $pool = SVN::Pool->new;
2814 $editor->set_path_strip($path);
2815 my (@pc) = split m#/#, $path;
2816 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2818 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2820 # Since we can't rely on svn_ra_reparent being available, we'll
2821 # just have to do some magic with set_path to make it so
2822 # we only want a partial path.
2824 my $final = join('/', @pc);
2826 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2827 $sp .= '/' if length $sp;
2830 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2832 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2834 $reporter->finish_report($pool);
2836 $editor->{git_commit_ok};
2839 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2840 # svn_ra_reparent didn't work before 1.4)
2842 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2843 my $path = $gs->{path};
2844 my $pool = SVN::Pool->new;
2846 my $full_url = $self->{url};
2847 my $old_url = $full_url;
2848 $full_url .= "/$path" if length $path;
2849 my ($ra, $reparented);
2850 if ($old_url ne $full_url) {
2851 if ($old_url !~ m#^svn(\+ssh)?://#) {
2852 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2854 $self->{url} = $full_url;
2857 $ra = Git::SVN::Ra->new($full_url);
2861 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
2862 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2863 $reporter->set_path('', $rev_a, 0, @lock, $pool);
2864 $reporter->finish_report($pool);
2867 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2868 $self->{url} = $old_url;
2872 $editor->{git_commit_ok};
2875 sub gs_fetch_loop_common {
2876 my ($self, $base, $head, $gsv, $globs) = @_;
2877 return if ($base > $head);
2878 my $inc = $_log_window_size;
2879 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
2881 my $common_max = scalar @$gsv;
2883 foreach my $gs (@$gsv) {
2884 my @tmp = split m#/#, $gs->{path};
2887 $p .= length($p) ? "/$_" : $_;
2893 $common_max += scalar @$globs;
2894 foreach my $glob (@$globs) {
2895 my @tmp = split m#/#, $glob->{path}->{left};
2898 $p .= length($p) ? "/$_" : $_;
2904 my $longest_path = '';
2905 foreach (sort {length $b <=> length $a} keys %common) {
2906 if ($common{$_} == $common_max) {
2914 my $err_handler = $SVN::Error::handler;
2915 $SVN::Error::handler = sub {
2917 skip_unknown_revs($err);
2920 my ($paths, $r, $author, $date, $log) = @_;
2921 [ dup_changed_paths($paths),
2922 { author => $author, date => $date, log => $log } ];
2924 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2925 sub { $revs{$_[1]} = _cb(@_) });
2926 if ($err && $max >= $head) {
2927 print STDERR "Path '$longest_path' ",
2928 "was probably deleted:\n",
2929 $err->expanded_message,
2930 "\nWill attempt to follow ",
2931 "revisions r$min .. r$max ",
2932 "committed before the deletion\n";
2934 while (--$hi >= $min) {
2936 $self->get_log([$longest_path], $min, $hi,
2939 $revs{$_[1]} = _cb(@_) });
2941 print STDERR "r$min .. r$ok OK\n";
2946 $SVN::Error::handler = $err_handler;
2948 my %exists = map { $_->{path} => $_ } @$gsv;
2949 foreach my $r (sort {$a <=> $b} keys %revs) {
2950 my ($paths, $logged) = @{$revs{$r}};
2952 foreach my $gs ($self->match_globs(\%exists, $paths,
2954 if ($gs->rev_db_max >= $r) {
2957 next unless $gs->match_paths($paths, $r);
2958 $gs->{logged_rev_props} = $logged;
2959 if (my $last_commit = $gs->last_commit) {
2960 $gs->assert_index_clean($last_commit);
2962 my $log_entry = $gs->do_fetch($paths, $r);
2964 $gs->do_git_commit($log_entry);
2967 foreach my $g (@$globs) {
2968 my $k = "svn-remote.$g->{remote}." .
2970 Git::SVN::tmp_config($k, $r);
2973 # pre-fill the .rev_db since it'll eventually get filled in
2974 # with '0' x40 if something new gets committed
2975 foreach my $gs (@$gsv) {
2976 next if defined $gs->rev_db_get($max);
2977 $gs->rev_db_set($max, 0 x40);
2979 foreach my $g (@$globs) {
2980 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
2981 Git::SVN::tmp_config($k, $max);
2983 last if $max >= $head;
2986 $max = $head if ($max > $head);
2991 my ($self, $exists, $paths, $globs, $r) = @_;
2994 my ($self, $exists, $g, $r) = @_;
2995 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2996 return unless scalar @x == 3;
2997 my $dirents = $x[0];
2998 foreach my $de (keys %$dirents) {
2999 next if $dirents->{$de}->kind != $SVN::Node::dir;
3000 my $p = $g->{path}->full_path($de);
3001 next if $exists->{$p};
3002 next if (length $g->{path}->{right} &&
3003 ($self->check_path($p, $r) !=
3005 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3006 $g->{ref}->full_path($de), 1);
3009 foreach my $g (@$globs) {
3010 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3011 if ($path->{action} =~ /^[AR]$/) {
3012 get_dir_check($self, $exists, $g, $r);
3015 foreach (keys %$paths) {
3016 if (/$g->{path}->{left_regex}/ &&
3017 !/$g->{path}->{regex}/) {
3018 next if $paths->{$_}->{action} !~ /^[AR]$/;
3019 get_dir_check($self, $exists, $g, $r);
3021 next unless /$g->{path}->{regex}/;
3023 my $pathname = $g->{path}->full_path($p);
3024 next if $exists->{$pathname};
3025 $exists->{$pathname} = Git::SVN->init(
3026 $self->{url}, $pathname, undef,
3027 $g->{ref}->full_path($p), 1);
3030 foreach (split m#/#, $g->{path}->{left}) {
3032 next unless ($paths->{$c} &&
3033 ($paths->{$c}->{action} =~ /^[AR]$/));
3034 get_dir_check($self, $exists, $g, $r);
3042 return $self->{url} if ($self->{url} eq $self->{repos_root});
3043 my $url = $self->{repos_root};
3044 my @components = split(m!/!, $self->{svn_path});
3047 $url .= "/$c" if length $c;
3048 eval { (ref $self)->new($url)->get_latest_revnum };
3049 } while ($@ && ($c = shift @components));
3055 unless (defined $can_do_switch) {
3056 my $pool = SVN::Pool->new;
3058 $self->do_switch(1, '', 0, $self->{url},
3059 SVN::Delta::Editor->new, $pool);
3064 $rep->abort_report($pool);
3072 sub skip_unknown_revs {
3074 my $errno = $err->apr_err();
3075 # Maybe the branch we're tracking didn't
3076 # exist when the repo started, so it's
3077 # not an error if it doesn't, just continue
3079 # Wonderfully consistent library, eh?
3080 # 160013 - svn:// and file://
3081 # 175002 - http(s)://
3082 # 175007 - http(s):// (this repo required authorization, too...)
3083 # More codes may be discovered later...
3084 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3085 warn "W: Ignoring error from SVN, path probably ",
3086 "does not exist: ($errno): ",
3087 $err->expanded_message,"\n";
3090 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3093 # svn_log_changed_path_t objects passed to get_log are likely to be
3094 # overwritten even if only the refs are copied to an external variable,
3095 # so we should dup the structures in their entirety. Using an externally
3096 # passed pool (instead of our temporary and quickly cleared pool in
3097 # Git::SVN::Ra) does not help matters at all...
3098 sub dup_changed_paths {
3100 return undef unless $paths;
3102 foreach my $p (keys %$paths) {
3103 my $i = $paths->{$p};
3104 my %s = map { $_ => $i->$_ }
3105 qw/copyfrom_path copyfrom_rev action/;
3111 package Git::SVN::Log;
3114 use POSIX qw/strftime/;
3115 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3116 %rusers $show_commit $incremental/;
3121 return 1 if defined $c->{r};
3122 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3123 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3124 my @log = command(qw/cat-file commit/, $c->{c});
3125 shift @log while ($log[0] ne "\n");
3127 @{$c->{l}} = grep !/^git-svn-id: /, @log;
3129 (undef, $c->{r}, undef) = ::extract_metadata(
3130 (grep(/^git-svn-id: /, @log))[-1]);
3132 return defined $c->{r};
3138 $dcvar = 'color.diff';
3139 $dc = `git-config --get $dcvar`;
3141 # nothing at all; fallback to "diff.color"
3142 $dcvar = 'diff.color';
3143 $dc = `git-config --get $dcvar`;
3146 if ($dc eq 'auto') {
3148 $pc = `git-config --get color.pager`;
3150 # does not have it -- fallback to pager.color
3151 $pc = `git-config --bool --get pager.color`;
3154 $pc = `git-config --bool --get color.pager`;
3160 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3161 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3165 return 0 if $dc eq 'never';
3166 return 1 if $dc eq 'always';
3167 chomp($dc = `git-config --bool --get $dcvar`);
3168 return ($dc eq 'true');
3171 sub git_svn_log_cmd {
3172 my ($r_min, $r_max, @args) = @_;
3174 foreach my $x (@args) {
3176 next unless ::verify_ref("$x^0");
3181 my $url = (::working_head_info($head))[0];
3182 my $gs = Git::SVN->find_by_url($url) || Git::SVN->_new;
3183 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3185 push @cmd, '-r' unless $non_recursive;
3186 push @cmd, qw/--raw --name-status/ if $verbose;
3187 push @cmd, '--color' if log_use_color();
3188 return @cmd unless defined $r_max;
3189 if ($r_max == $r_min) {
3190 push @cmd, '--max-count=1';
3191 if (my $c = $gs->rev_db_get($r_max)) {
3195 my ($c_min, $c_max);
3196 $c_max = $gs->rev_db_get($r_max);
3197 $c_min = $gs->rev_db_get($r_min);
3198 if (defined $c_min && defined $c_max) {
3199 if ($r_max > $r_max) {
3200 push @cmd, "$c_min..$c_max";
3202 push @cmd, "$c_max..$c_min";
3204 } elsif ($r_max > $r_min) {
3213 # adapted from pager.c
3215 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3216 if (!defined $pager) {
3218 } elsif (length $pager == 0 || $pager eq 'cat') {
3224 return unless -t *STDOUT;
3225 pipe my $rfd, my $wfd or return;
3226 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3228 open STDOUT, '>&', $wfd or
3229 ::fatal "Can't redirect to stdout: $!\n";
3232 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3233 $ENV{LESS} ||= 'FRSX';
3234 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3237 sub tz_to_s_offset {
3240 return ($1 * 60) + ($tz * 3600);
3243 sub get_author_info {
3244 my ($dest, $author, $t, $tz) = @_;
3245 $author =~ s/(?:^\s*|\s*$)//g;
3246 $dest->{a_raw} = $author;
3249 $au = $rusers{$author} || undef;
3252 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3257 # Date::Parse isn't in the standard Perl distro :(
3258 if ($tz =~ s/^\+//) {
3259 $t += tz_to_s_offset($tz);
3260 } elsif ($tz =~ s/^\-//) {
3261 $t -= tz_to_s_offset($tz);
3263 $dest->{t_utc} = $t;
3266 sub process_commit {
3267 my ($c, $r_min, $r_max, $defer) = @_;
3268 if (defined $r_min && defined $r_max) {
3269 if ($r_min == $c->{r} && $r_min == $r_max) {
3273 return 1 if $r_min == $r_max;
3274 if ($r_min < $r_max) {
3275 # we need to reverse the print order
3276 return 0 if (defined $limit && --$limit < 0);
3280 if ($r_min != $r_max) {
3281 return 1 if ($r_min < $c->{r});
3282 return 1 if ($r_max > $c->{r});
3285 return 0 if (defined $limit && --$limit < 0);
3294 if (my $l = $c->{l}) {
3295 while ($l->[0] =~ /^\s*$/) { shift @$l }
3298 $l_fmt ||= 'A' . length($c->{r});
3299 print 'r',pack($l_fmt, $c->{r}),' | ';
3300 print "$c->{c} | " if $show_commit;
3303 show_commit_normal($c);
3307 sub show_commit_changed_paths {
3309 return unless $c->{changed};
3310 print "Changed paths:\n", @{$c->{changed}};
3313 sub show_commit_normal {
3315 print '-' x72, "\nr$c->{r} | ";
3316 print "$c->{c} | " if $show_commit;
3317 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3318 localtime($c->{t_utc})), ' | ';
3321 if (my $l = $c->{l}) {
3322 while ($l->[$#$l] eq "\n" && $#$l > 0
3323 && $l->[($#$l - 1)] eq "\n") {
3326 $nr_line = scalar @$l;
3328 print "1 line\n\n\n";
3330 if ($nr_line == 1) {
3331 $nr_line = '1 line';
3333 $nr_line .= ' lines';
3335 print $nr_line, "\n";
3336 show_commit_changed_paths($c);
3338 print $_ foreach @$l;
3342 show_commit_changed_paths($c);
3346 foreach my $x (qw/raw stat diff/) {
3349 print $_ foreach @{$c->{$x}}
3356 my ($r_min, $r_max);
3357 my $r_last = -1; # prevent dupes
3363 if (defined $::_revision) {
3364 if ($::_revision =~ /^(\d+):(\d+)$/) {
3365 ($r_min, $r_max) = ($1, $2);
3366 } elsif ($::_revision =~ /^\d+$/) {
3367 $r_min = $r_max = $::_revision;
3369 ::fatal "-r$::_revision is not supported, use ",
3370 "standard \'git log\' arguments instead\n";
3375 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
3376 my $log = command_output_pipe(@args);
3378 my (@k, $c, $d, $stat);
3379 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3381 if (/^${esc_color}commit ($::sha1_short)/o) {
3383 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3385 process_commit($c, $r_min, $r_max, \@k) or
3390 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3391 get_author_info($c, $1, $2, $3);
3392 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3394 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3395 push @{$c->{raw}}, $_;
3396 } elsif (/^${esc_color}[ACRMDT]\t/) {
3397 # we could add $SVN->{svn_path} here, but that requires
3398 # remote access at the moment (repo_path_split)...
3399 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3400 push @{$c->{changed}}, $_;
3401 } elsif (/^${esc_color}diff /o) {
3403 push @{$c->{diff}}, $_;
3405 push @{$c->{diff}}, $_;
3406 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3407 $esc_color*[\+\-]*$esc_color$/x) {
3409 push @{$c->{stat}}, $_;
3410 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3411 push @{$c->{stat}}, $_;
3413 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3414 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3415 } elsif (s/^${esc_color} //o) {
3416 push @{$c->{l}}, $_;
3419 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3421 process_commit($c, $r_min, $r_max, \@k);
3427 process_commit($_, $r_min, $r_max) foreach reverse @k;
3431 print '-' x72,"\n" unless $incremental || $oneline;
3434 package Git::SVN::Migration;
3435 # these version numbers do NOT correspond to actual version numbers
3436 # of git nor git-svn. They are just relative.
3438 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3440 # v1 layout: .git/$id/info/url, refs/remotes/$id
3442 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3444 # v3 layout: .git/svn/$id, refs/remotes/$id
3445 # - info/url may remain for backwards compatibility
3446 # - this is what we migrate up to this layout automatically,
3447 # - this will be used by git svn init on single branches
3448 # v3.1 layout (auto migrated):
3449 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3450 # for backwards compatibility
3452 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3453 # - this is only created for newly multi-init-ed
3454 # repositories. Similar in spirit to the
3455 # --use-separate-remotes option in git-clone (now default)
3456 # - we do not automatically migrate to this (following
3457 # the example set by core git)
3461 use File::Path qw/mkpath/;
3462 use File::Basename qw/dirname basename/;
3463 use vars qw/$_minimize/;
3465 sub migrate_from_v0 {
3466 my $git_dir = $ENV{GIT_DIR};
3467 return undef unless -d $git_dir;
3468 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3472 my ($id, $orig_ref) = ($_, $_);
3473 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3474 next unless -f "$git_dir/$id/info/url";
3475 my $new_ref = "refs/remotes/$id";
3476 if (::verify_ref("$new_ref^0")) {
3477 print STDERR "W: $orig_ref is probably an old ",
3478 "branch used by an ancient version of ",
3480 "However, $new_ref also exists.\n",
3481 "We will not be able ",
3482 "to use this branch until this ",
3483 "ambiguity is resolved.\n";
3486 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3487 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3488 command_noisy('update-ref', $new_ref, $orig_ref);
3489 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3492 command_close_pipe($fh, $ctx);
3493 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3497 sub migrate_from_v1 {
3498 my $git_dir = $ENV{GIT_DIR};
3500 return $migrated unless -d $git_dir;
3501 my $svn_dir = "$git_dir/svn";
3503 # just in case somebody used 'svn' as their $id at some point...
3504 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3506 print STDERR "Migrating from a git-svn v1 layout...\n";
3508 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3509 "$svn_dir\n\t(required for this version ",
3510 "($::VERSION) of git-svn) does not. exist\n";
3511 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3514 next unless $x =~ s#^refs/remotes/##;
3516 next unless -f "$git_dir/$x/info/url";
3517 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3519 my $dn = dirname("$git_dir/svn/$x");
3520 mkpath([$dn]) unless -d $dn;
3521 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3522 mkpath(["$git_dir/svn/svn"]);
3523 print STDERR " - $git_dir/$x/info => ",
3524 "$git_dir/svn/$x/info\n";
3525 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3527 # don't worry too much about these, they probably
3528 # don't exist with repos this old (save for index,
3529 # and we can easily regenerate that)
3530 foreach my $f (qw/unhandled.log index .rev_db/) {
3531 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3534 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3535 rename "$git_dir/$x", "$git_dir/svn/$x" or
3540 command_close_pipe($fh, $ctx);
3541 print STDERR "Done migrating from a git-svn v1 layout\n";
3546 my ($l_map, $pfx, $path) = @_;
3548 foreach (<$path/*>) {
3549 if (-r "$_/info/url") {
3550 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3551 my $ref_id = $pfx . basename $_;
3552 my $url = ::file_to_s("$_/info/url");
3553 $l_map->{$ref_id} = $url;
3560 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3561 read_old_urls($l_map, $x, $_);
3565 sub migrate_from_v2 {
3566 my @cfg = command(qw/config -l/);
3567 return if grep /^svn-remote\..+\.url=/, @cfg;
3569 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3572 foreach my $ref_id (sort keys %l_map) {
3573 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3575 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3582 sub minimize_connections {
3583 my $r = Git::SVN::read_all_remotes();
3585 my $root_repos = {};
3586 foreach my $repo_id (keys %$r) {
3587 my $url = $r->{$repo_id}->{url} or next;
3588 my $fetch = $r->{$repo_id}->{fetch} or next;
3589 my $ra = Git::SVN::Ra->new($url);
3591 # skip existing cases where we already connect to the root
3592 if (($ra->{url} eq $ra->{repos_root}) ||
3593 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3595 $root_repos->{$ra->{url}} = $repo_id;
3599 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3600 my $root_path = $ra->{url};
3601 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
3602 foreach my $path (keys %$fetch) {
3603 my $ref_id = $fetch->{$path};
3604 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3606 # make sure we can read when connecting to
3607 # a higher level of a repository
3608 my ($last_rev, undef) = $gs->last_rev_commit;
3609 if (!defined $last_rev) {
3611 $root_ra->get_latest_revnum;
3615 my $new = $root_path;
3616 $new .= length $path ? "/$path" : '';
3618 $root_ra->get_log([$new], $last_rev, $last_rev,
3622 $new_urls->{$ra->{repos_root}}->{$new} =
3623 { ref_id => $ref_id,
3624 old_repo_id => $repo_id,
3625 old_path => $path };
3630 foreach my $url (keys %$new_urls) {
3631 # see if we can re-use an existing [svn-remote "repo_id"]
3632 # instead of creating a(n ugly) new section:
3633 my $repo_id = $root_repos->{$url} ||
3634 Git::SVN::sanitize_remote_name($url);
3636 my $fetch = $new_urls->{$url};
3637 foreach my $path (keys %$fetch) {
3638 my $x = $fetch->{$path};
3639 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3640 my $pfx = "svn-remote.$x->{old_repo_id}";
3642 my $old_fetch = quotemeta("$x->{old_path}:".
3643 "refs/remotes/$x->{ref_id}");
3644 command_noisy(qw/config --unset/,
3645 "$pfx.fetch", '^'. $old_fetch . '$');
3646 delete $r->{$x->{old_repo_id}}->
3647 {fetch}->{$x->{old_path}};
3648 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
3649 command_noisy(qw/config --unset/,
3651 push @emptied, $x->{old_repo_id}
3656 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3657 "$ENV{GIT_DIR}/config";
3659 The following [svn-remote] sections in your config file ($file) are empty
3660 and can be safely removed:
3662 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3666 sub migration_check {
3670 minimize_connections() if $_minimize;
3673 package Git::IndexInfo;
3676 use Git qw/command_input_pipe command_close_pipe/;
3680 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3681 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3685 my ($self, $path) = @_;
3686 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3687 return ++$self->{nr};
3693 my ($self, $mode, $hash, $path) = @_;
3694 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3695 return ++$self->{nr};
3702 command_close_pipe($self->{gui}, $self->{ctx});
3705 package Git::SVN::GlobSpec;
3710 my ($class, $glob) = @_;
3712 $re =~ s!/+$!!g; # no need for trailing slashes
3713 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
3714 my ($left, $right) = ($1, $2);
3716 die "Only one '*' wildcard expansion ",
3717 "is supported (got $nr): '$glob'\n";
3718 } elsif ($nr == 0) {
3719 die "One '*' is needed for glob: '$glob'\n";
3721 $re = quotemeta($left) . $re . quotemeta($right);
3722 if (length $left && !($left =~ s!/+$!!g)) {
3723 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3725 if (length $right && !($right =~ s!^/+!!g)) {
3726 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3728 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3729 bless { left => $left, right => $right, left_regex => $left_re,
3730 regex => qr/$re/, glob => $glob }, $class;
3734 my ($self, $path) = @_;
3735 return (length $self->{left} ? "$self->{left}/" : '') .
3736 $path . (length $self->{right} ? "/$self->{right}" : '');
3744 $remotes = { # returned by read_all_remotes()
3746 # svn-remote.svn.url=https://svn.musicpd.org
3747 url => 'https://svn.musicpd.org',
3748 # svn-remote.svn.fetch=mpd/trunk:trunk
3750 'mpd/trunk' => 'trunk',
3752 # svn-remote.svn.tags=mpd/tags/*:tags/*
3757 regex => qr!mpd/tags/([^/]+)$!,
3763 regex => qr!tags/([^/]+)$!,
3770 $log_entry hashref as returned by libsvn_log_entry()
3772 log => 'whitespace-formatted log entry
3773 ', # trailing newline is preserved
3774 revision => '8', # integer
3775 date => '2004-02-24T17:01:44.108345Z', # commit date
3776 author => 'committer name'
3780 # this is generated by generate_diff();
3781 @mods = array of diff-index line hashes, each element represents one line
3782 of diff-index output
3784 diff-index line ($m hash)
3786 mode_a => first column of diff-index output, no leading ':',
3787 mode_b => second column of diff-index output,
3788 sha1_b => sha1sum of the final blob,
3789 chg => change type [MCRADT],
3790 file_a => original file name of a file (iff chg is 'C' or 'R')
3791 file_b => new/current file name of a file (any chg)
3795 # retval of read_url_paths{,_all}();
3797 # repository root url
3798 'https://svn.musicpd.org' => {
3799 # repository path # GIT_SVN_ID
3800 'mpd/trunk' => 'trunk',
3801 'mpd/tags/0.11.5' => 'tags/0.11.5',
3806 I don't trust the each() function on unless I created %hash myself
3807 because the internal iterator may not have started at base.