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 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
39 use File::Basename qw/dirname basename/;
40 use File::Path qw/mkpath/;
41 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
46 # import functions from Git into our packages, en masse
48 foreach (qw/command command_oneline command_noisy command_output_pipe
49 command_input_pipe command_close_pipe/) {
50 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
51 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 *{"${package}::$_"} = \&{"Git::$_"};
60 $sha1 = qr/[a-f\d]{40}/;
61 $sha1_short = qr/[a-f\d]{4,40}/;
62 my ($_stdin, $_help, $_edit,
65 $_version, $_fetch_all, $_no_rebase,
66 $_merge, $_strategy, $_dry_run, $_local,
67 $_prefix, $_no_checkout, $_verbose);
68 $Git::SVN::_follow_parent = 1;
69 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
70 'config-dir=s' => \$Git::SVN::Ra::config_dir,
71 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
72 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
73 'authors-file|A=s' => \$_authors,
74 'repack:i' => \$Git::SVN::_repack,
75 'noMetadata' => \$Git::SVN::_no_metadata,
76 'useSvmProps' => \$Git::SVN::_use_svm_props,
77 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
78 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
79 'no-checkout' => \$_no_checkout,
81 'repack-flags|repack-args|repack-opts=s' =>
82 \$Git::SVN::_repack_flags,
85 my ($_trunk, $_tags, $_branches, $_stdlayout);
87 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
88 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
89 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
90 'stdlayout|s' => \$_stdlayout,
91 'minimize-url|m' => \$Git::SVN::_minimize_url,
92 'no-metadata' => sub { $icv{noMetadata} = 1 },
93 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
94 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
95 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
97 my %cmt_opts = ( 'edit|e' => \$_edit,
98 'rmdir' => \$SVN::Git::Editor::_rmdir,
99 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
100 'l=i' => \$SVN::Git::Editor::_rename_limit,
101 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
105 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
106 { 'revision|r=s' => \$_revision,
107 'fetch-all|all' => \$_fetch_all,
109 clone => [ \&cmd_clone, "Initialize and fetch revisions",
110 { 'revision|r=s' => \$_revision,
111 %fc_opts, %init_opts } ],
112 init => [ \&cmd_init, "Initialize a repo for tracking" .
113 " (requires URL argument)",
115 'multi-init' => [ \&cmd_multi_init,
116 "Deprecated alias for ".
117 "'$0 init -T<trunk> -b<branches> -t<tags>'",
119 dcommit => [ \&cmd_dcommit,
120 'Commit several diffs to merge with upstream',
121 { 'merge|m|M' => \$_merge,
122 'strategy|s=s' => \$_strategy,
123 'verbose|v' => \$_verbose,
124 'dry-run|n' => \$_dry_run,
125 'fetch-all|all' => \$_fetch_all,
126 'no-rebase' => \$_no_rebase,
127 %cmt_opts, %fc_opts } ],
128 'set-tree' => [ \&cmd_set_tree,
129 "Set an SVN repository to a git tree-ish",
130 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
131 'create-ignore' => [ \&cmd_create_ignore,
132 'Create a .gitignore per svn:ignore',
133 { 'revision|r=i' => \$_revision
135 'propget' => [ \&cmd_propget,
136 'Print the value of a property on a file or directory',
137 { 'revision|r=i' => \$_revision } ],
138 'proplist' => [ \&cmd_proplist,
139 'List all properties of a file or directory',
140 { 'revision|r=i' => \$_revision } ],
141 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
142 { 'revision|r=i' => \$_revision
144 'multi-fetch' => [ \&cmd_multi_fetch,
145 "Deprecated alias for $0 fetch --all",
146 { 'revision|r=s' => \$_revision, %fc_opts } ],
147 'migrate' => [ sub { },
148 # no-op, we automatically run this anyways,
149 'Migrate configuration/metadata/layout from
150 previous versions of git-svn',
151 { 'minimize' => \$Git::SVN::Migration::_minimize,
153 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
154 { 'limit=i' => \$Git::SVN::Log::limit,
155 'revision|r=s' => \$_revision,
156 'verbose|v' => \$Git::SVN::Log::verbose,
157 'incremental' => \$Git::SVN::Log::incremental,
158 'oneline' => \$Git::SVN::Log::oneline,
159 'show-commit' => \$Git::SVN::Log::show_commit,
160 'non-recursive' => \$Git::SVN::Log::non_recursive,
161 'authors-file|A=s' => \$_authors,
162 'color' => \$Git::SVN::Log::color,
163 'pager=s' => \$Git::SVN::Log::pager
165 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
167 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
168 { 'merge|m|M' => \$_merge,
169 'verbose|v' => \$_verbose,
170 'strategy|s=s' => \$_strategy,
171 'local|l' => \$_local,
172 'fetch-all|all' => \$_fetch_all,
174 'commit-diff' => [ \&cmd_commit_diff,
175 'Commit a diff between two trees',
176 { 'message|m=s' => \$_message,
177 'file|F=s' => \$_file,
178 'revision|r=s' => \$_revision,
183 for (my $i = 0; $i < @ARGV; $i++) {
184 if (defined $cmd{$ARGV[$i]}) {
191 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
193 read_repo_config(\%opts);
194 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
195 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
196 'minimize-connections' => \$Git::SVN::Migration::_minimize,
197 'id|i=s' => \$Git::SVN::default_ref_id,
198 'svn-remote|remote|R=s' => sub {
199 $Git::SVN::no_reuse_existing = 1;
200 $Git::SVN::default_repo_id = $_[1] });
201 exit 1 if (!$rv && $cmd && $cmd ne 'log');
204 version() if $_version;
205 usage(1) unless defined $cmd;
206 load_authors() if $_authors;
208 # make sure we're always running
209 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
210 unless (-d $ENV{GIT_DIR}) {
211 if ($git_dir_user_set) {
212 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
213 "but it is not a directory\n";
215 my $git_dir = delete $ENV{GIT_DIR};
216 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
217 unless (length $cdup) {
218 die "Already at toplevel, but $git_dir ",
219 "not found '$cdup'\n";
221 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
222 unless (-d $git_dir) {
223 die "$git_dir still not found after going to ",
226 $ENV{GIT_DIR} = $git_dir;
229 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
230 Git::SVN::Migration::migration_check();
232 Git::SVN::init_vars();
234 Git::SVN::verify_remotes_sanity();
235 $cmd{$cmd}->[0]->(@ARGV);
238 post_fetch_checkout();
241 ####################### primary functions ######################
243 my $exit = shift || 0;
244 my $fd = $exit ? \*STDERR : \*STDOUT;
246 git-svn - bidirectional operations between a single Subversion tree and git
247 Usage: $0 <command> [options] [arguments]\n
249 print $fd "Available commands:\n" unless $cmd;
251 foreach (sort keys %cmd) {
252 next if $cmd && $cmd ne $_;
253 next if /^multi-/; # don't show deprecated commands
254 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
255 foreach (sort keys %{$cmd{$_}->[2]}) {
256 # mixed-case options are for .git/config only
257 next if /[A-Z]/ && /^[a-z]+$/i;
258 # prints out arguments as they should be passed:
259 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
260 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
262 split /\|/,$_)," $x\n";
266 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
267 arbitrary identifier if you're tracking multiple SVN branches/repositories in
268 one git repository and want to keep them separate. See git-svn(1) for more
275 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
280 unless (-d $ENV{GIT_DIR}) {
281 my @init_db = ('init');
282 push @init_db, "--template=$_template" if defined $_template;
283 if (defined $_shared) {
284 if ($_shared =~ /[a-z]/) {
285 push @init_db, "--shared=$_shared";
287 push @init_db, "--shared";
290 command_noisy(@init_db);
293 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
294 foreach my $i (keys %icv) {
295 die "'$set' and '$i' cannot both be set\n" if $set;
296 next unless defined $icv{$i};
297 command_noisy('config', "$pfx.$i", $icv{$i});
303 my $repo_path = shift or return;
304 mkpath([$repo_path]) unless -d $repo_path;
305 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
306 $ENV{GIT_DIR} = '.git';
310 my ($url, $path) = @_;
311 if (!defined $path &&
312 (defined $_trunk || defined $_branches || defined $_tags ||
313 defined $_stdlayout) &&
314 $url !~ m#^[a-z\+]+://#) {
317 $path = basename($url) if !defined $path || !length $path;
318 cmd_init($url, $path);
319 Git::SVN::fetch_all($Git::SVN::default_repo_id);
323 if (defined $_stdlayout) {
324 $_trunk = 'trunk' if (!defined $_trunk);
325 $_tags = 'tags' if (!defined $_tags);
326 $_branches = 'branches' if (!defined $_branches);
328 if (defined $_trunk || defined $_branches || defined $_tags) {
329 return cmd_multi_init(@_);
331 my $url = shift or die "SVN repository location required ",
332 "as a command-line argument\n";
336 Git::SVN->init($url);
340 if (grep /^\d+=./, @_) {
341 die "'<rev>=<commit>' fetch arguments are ",
342 "no longer supported.\n";
346 die "Usage: $0 fetch [--all] [svn-remote]\n";
348 $remote ||= $Git::SVN::default_repo_id;
352 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
358 if ($_stdin || !@commits) {
359 print "Reading from stdin...\n";
362 if (/\b($sha1_short)\b/o) {
363 unshift @commits, $1;
368 foreach my $c (@commits) {
369 my @tmp = command('rev-parse',$c);
370 if (scalar @tmp == 1) {
372 } elsif (scalar @tmp > 1) {
373 push @revs, reverse(command('rev-list',@tmp));
375 fatal "Failed to rev-parse $c";
378 my $gs = Git::SVN->new;
379 my ($r_last, $cmt_last) = $gs->last_rev_commit;
381 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
382 fatal "There are new revisions that were fetched ",
383 "and need to be merged (or acknowledged) ",
384 "before committing.\nlast rev: $r_last\n",
385 " current: $gs->{last_rev}";
387 $gs->set_tree($_) foreach @revs;
388 print "Done committing ",scalar @revs," revisions to SVN\n";
393 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
394 'Cannot dcommit with a dirty index. Commit your changes first'
395 . "or stash them with `git stash'.\n";
398 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
399 print "Committing to $url ...\n";
401 die "Unable to determine upstream SVN information from ",
405 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
406 if ($_no_rebase && scalar(@$linear_refs) > 1) {
407 warn "Attempting to commit more than one change while ",
408 "--no-rebase is enabled.\n",
409 "If these changes depend on each other, re-running ",
410 "without --no-rebase will be required."
413 my $d = shift @$linear_refs or last;
414 unless (defined $last_rev) {
415 (undef, $last_rev, undef) = cmt_metadata("$d~1");
416 unless (defined $last_rev) {
417 fatal "Unable to extract revision information ",
422 print "diff-tree $d~1 $d\n";
425 my %ed_opts = ( r => $last_rev,
426 log => get_commit_entry($d)->{log},
427 ra => Git::SVN::Ra->new($gs->full_url),
431 print "Committed r$_[0]\n";
435 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
436 print "No changes\n$d~1 == $d\n";
437 } elsif ($parents->{$d} && @{$parents->{$d}}) {
438 $gs->{inject_parents_dcommit}->{$cmt_rev} =
441 $_fetch_all ? $gs->fetch_all : $gs->fetch;
444 # we always want to rebase against the current HEAD,
445 # not any head that was passed to us
446 my @diff = command('diff-tree', $d,
450 @finish = rebase_cmd();
451 print STDERR "W: $d and ", $gs->refname,
452 " differ, using @finish:\n",
453 join("\n", @diff), "\n";
455 print "No changes between current HEAD and ",
457 "\nResetting to the latest ",
459 @finish = qw/reset --mixed/;
461 command_noisy(@finish, $gs->refname);
464 my ($url_, $rev_, $uuid_, $gs_) =
465 working_head_info($head, \@refs);
466 my ($linear_refs_, $parents_) =
467 linearize_history($gs_, \@refs);
468 if (scalar(@$linear_refs) !=
469 scalar(@$linear_refs_)) {
470 fatal "# of revisions changed ",
472 join("\n", @$linear_refs),
474 join("\n", @$linear_refs_), "\n",
475 'If you are attempting to commit ',
476 "merges, try running:\n\t",
477 'git rebase --interactive',
478 '--preserve-merges ',
480 "\nBefore dcommitting";
483 fatal "URL mismatch after rebase: ",
486 if ($uuid_ ne $uuid) {
487 fatal "uuid mismatch after rebase: ",
492 for ($i = 0; $i < scalar @$linear_refs; $i++) {
493 my $new = $linear_refs_->[$i] or next;
495 $parents->{$linear_refs->[$i]};
501 $last_rev = $cmt_rev;
507 my $revision_or_hash = shift;
509 if ($revision_or_hash =~ /^r\d+$/) {
513 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
515 die "Unable to determine upstream SVN information from ",
518 my $desired_revision = substr($revision_or_hash, 1);
519 $result = $gs->rev_db_get($desired_revision);
521 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
524 print "$result\n" if $result;
528 command_noisy(qw/update-index --refresh/);
529 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
531 die "Unable to determine upstream SVN information from ",
532 "working tree history\n";
534 if (command(qw/diff-index HEAD --/)) {
535 print STDERR "Cannot rebase with uncommited changes:\n";
536 command_noisy('status');
540 $_fetch_all ? $gs->fetch_all : $gs->fetch;
542 command_noisy(rebase_cmd(), $gs->refname);
545 sub cmd_show_ignore {
546 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
547 $gs ||= Git::SVN->new;
548 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
549 $gs->prop_walk($gs->{path}, $r, sub {
550 my ($gs, $path, $props) = @_;
551 print STDOUT "\n# $path\n";
552 my $s = $props->{'svn:ignore'} or return;
553 $s =~ s/[\r\n]+/\n/g;
560 sub cmd_create_ignore {
561 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
562 $gs ||= Git::SVN->new;
563 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
564 $gs->prop_walk($gs->{path}, $r, sub {
565 my ($gs, $path, $props) = @_;
566 # $path is of the form /path/to/dir/
567 my $ignore = '.' . $path . '.gitignore';
568 my $s = $props->{'svn:ignore'} or return;
569 open(GITIGNORE, '>', $ignore)
570 or fatal("Failed to open `$ignore' for writing: $!");
571 $s =~ s/[\r\n]+/\n/g;
573 # Prefix all patterns so that the ignore doesn't apply
574 # to sub-directories.
576 print GITIGNORE "$s\n";
578 or fatal("Failed to close `$ignore': $!");
579 command_noisy('add', $ignore);
585 # Helper for cmd_propget and cmd_proplist below.
588 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
589 $gs ||= Git::SVN->new;
591 # prefix THE PATH by the sub-directory from which the user
593 $path = $cmd_dir_prefix . $path;
594 fatal("No such file or directory: $path") unless -e $path;
595 my $is_dir = -d $path ? 1 : 0;
596 $path = $gs->{path} . '/' . $path;
598 # canonicalize the path (otherwise libsvn will abort or fail to
600 # File::Spec->canonpath doesn't collapse x/../y into y (for a
601 # good reason), so let's do this manually.
603 $path =~ s#/\.(?:/|$)#/#g;
604 $path =~ s#/[^/]+/\.\.##g;
607 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
610 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
613 (undef, $props) = $gs->ra->get_file($path, $r, undef);
618 # cmd_propget (PROP, PATH)
619 # ------------------------
620 # Print the SVN property PROP for PATH.
622 my ($prop, $path) = @_;
623 $path = '.' if not defined $path;
624 usage(1) if not defined $prop;
625 my $props = get_svnprops($path);
626 if (not defined $props->{$prop}) {
627 fatal("`$path' does not have a `$prop' SVN property.");
629 print $props->{$prop} . "\n";
632 # cmd_proplist (PATH)
633 # -------------------
634 # Print the list of SVN properties for PATH.
637 $path = '.' if not defined $path;
638 my $props = get_svnprops($path);
639 print "Properties on '$path':\n";
640 foreach (sort keys %{$props}) {
647 unless (defined $_trunk || defined $_branches || defined $_tags) {
651 # there are currently some bugs that prevent multi-init/multi-fetch
652 # setups from working well without this.
653 $Git::SVN::_minimize_url = 1;
655 $_prefix = '' unless defined $_prefix;
661 if (defined $_trunk) {
662 my $trunk_ref = $_prefix . 'trunk';
663 # try both old-style and new-style lookups:
664 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
666 my ($trunk_url, $trunk_path) =
667 complete_svn_url($url, $_trunk);
668 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
672 return unless defined $_branches || defined $_tags;
673 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
674 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
675 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
678 sub cmd_multi_fetch {
679 my $remotes = Git::SVN::read_all_remotes();
680 foreach my $repo_id (sort keys %$remotes) {
681 if ($remotes->{$repo_id}->{url}) {
682 Git::SVN::fetch_all($repo_id, $remotes);
687 # this command is special because it requires no metadata
688 sub cmd_commit_diff {
689 my ($ta, $tb, $url) = @_;
690 my $usage = "Usage: $0 commit-diff -r<revision> ".
691 "<tree-ish> <tree-ish> [<URL>]";
692 fatal($usage) if (!defined $ta || !defined $tb);
695 my $gs = eval { Git::SVN->new };
697 fatal("Needed URL or usable git-svn --id in ",
698 "the command-line\n", $usage);
701 $svn_path = $gs->{path};
703 unless (defined $_revision) {
704 fatal("-r|--revision is a required argument\n", $usage);
706 if (defined $_message && defined $_file) {
707 fatal("Both --message/-m and --file/-F specified ",
708 "for the commit message.\n",
709 "I have no idea what you mean");
711 if (defined $_file) {
712 $_message = file_to_s($_file);
714 $_message ||= get_commit_entry($tb)->{log};
716 my $ra ||= Git::SVN::Ra->new($url);
717 $svn_path ||= $ra->{svn_path};
720 $r = $ra->get_latest_revnum;
721 } elsif ($r !~ /^\d+$/) {
722 die "revision argument: $r not understood by git-svn\n";
724 my %ed_opts = ( r => $r,
729 editor_cb => sub { print "Committed r$_[0]\n" },
730 svn_path => $svn_path );
731 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
732 print "No changes\n$ta == $tb\n";
736 ########################### utility functions #########################
739 my @cmd = qw/rebase/;
740 push @cmd, '-v' if $_verbose;
741 push @cmd, qw/--merge/ if $_merge;
742 push @cmd, "--strategy=$_strategy" if $_strategy;
746 sub post_fetch_checkout {
747 return if $_no_checkout;
748 my $gs = $Git::SVN::_head or return;
749 return if verify_ref('refs/heads/master^0');
751 my $valid_head = verify_ref('HEAD^0');
752 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
753 return if ($valid_head || !verify_ref('HEAD^0'));
755 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
756 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
759 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
760 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
761 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
762 print STDERR "Checked out HEAD:\n ",
763 $gs->full_url, " r", $gs->last_rev, "\n";
766 sub complete_svn_url {
767 my ($url, $path) = @_;
769 if ($path !~ m#^[a-z\+]+://#) {
770 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
771 fatal("E: '$path' is not a complete URL ",
772 "and a separate URL is not specified");
774 return ($url, $path);
779 sub complete_url_ls_init {
780 my ($ra, $repo_path, $switch, $pfx) = @_;
781 unless ($repo_path) {
782 print STDERR "W: $switch not specified\n";
785 $repo_path =~ s#/+$##;
786 if ($repo_path =~ m#^[a-z\+]+://#) {
787 $ra = Git::SVN::Ra->new($repo_path);
790 $repo_path =~ s#^/+##;
792 fatal("E: '$repo_path' is not a complete URL ",
793 "and a separate URL is not specified");
796 my $url = $ra->{url};
797 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
798 my $k = "svn-remote.$gs->{repo_id}.url";
799 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
800 if ($orig_url && ($orig_url ne $gs->{url})) {
801 die "$k already set: $orig_url\n",
802 "wanted to set to: $gs->{url}\n";
804 command_oneline('config', $k, $gs->{url}) unless $orig_url;
805 my $remote_path = "$ra->{svn_path}/$repo_path/*";
806 $remote_path =~ s#/+#/#g;
807 $remote_path =~ s#^/##g;
808 my ($n) = ($switch =~ /^--(\w+)/);
809 if (length $pfx && $pfx !~ m#/$#) {
810 die "--prefix='$pfx' must have a trailing slash '/'\n";
812 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
813 "$remote_path:refs/remotes/$pfx*");
818 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
822 sub get_tree_from_treeish {
824 # $treeish can be a symbolic ref, too:
825 my $type = command_oneline(qw/cat-file -t/, $treeish);
827 while ($type eq 'tag') {
828 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
830 if ($type eq 'commit') {
831 $expected = (grep /^tree /, command(qw/cat-file commit/,
833 ($expected) = ($expected =~ /^tree ($sha1)$/o);
834 die "Unable to get tree from $treeish\n" unless $expected;
835 } elsif ($type eq 'tree') {
836 $expected = $treeish;
838 die "$treeish is a $type, expected tree, tag or commit\n";
843 sub get_commit_entry {
844 my ($treeish) = shift;
845 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
846 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
847 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
848 open my $log_fh, '>', $commit_editmsg or croak $!;
850 my $type = command_oneline(qw/cat-file -t/, $treeish);
851 if ($type eq 'commit' || $type eq 'tag') {
852 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
857 $in_msg = 1 if (/^\s*$/);
858 } elsif (/^git-svn-id: /) {
859 # skip this for now, we regenerate the
860 # correct one on re-fetch anyways
861 # TODO: set *:merge properties or like...
863 print $log_fh $_ or croak $!;
866 command_close_pipe($msg_fh, $ctx);
868 close $log_fh or croak $!;
870 if ($_edit || ($type eq 'tree')) {
871 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
872 # TODO: strip out spaces, comments, like git-commit.sh
873 system($editor, $commit_editmsg);
875 rename $commit_editmsg, $commit_msg or croak $!;
876 open $log_fh, '<', $commit_msg or croak $!;
877 { local $/; chomp($log_entry{log} = <$log_fh>); }
878 close $log_fh or croak $!;
884 my ($str, $file, $mode) = @_;
885 open my $fd,'>',$file or croak $!;
886 print $fd $str,"\n" or croak $!;
887 close $fd or croak $!;
888 chmod ($mode &~ umask, $file) if (defined $mode);
893 open my $fd,'<',$file or croak "$!: file: $file\n";
896 close $fd or croak $!;
901 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
903 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
904 my $log = $cmd eq 'log';
907 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
908 my ($user, $name, $email) = ($1, $2, $3);
910 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
912 $users{$user} = [$name, $email];
915 close $authors or croak $!;
918 # convert GetOpt::Long specs for use by git-config
919 sub read_repo_config {
920 return unless -d $ENV{GIT_DIR};
923 foreach my $o (keys %$opts) {
924 # if we have mixedCase and a long option-only, then
925 # it's a config-only variable that we don't need for
927 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
929 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
931 my $arg = 'git-config';
932 $arg .= ' --int' if ($o =~ /[:=]i$/);
933 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
934 if (ref $v eq 'ARRAY') {
935 chomp(my @tmp = `$arg --get-all svn.$key`);
938 chomp(my $tmp = `$arg --get svn.$key`);
939 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
944 delete @$opts{@config_only} if @config_only;
947 sub extract_metadata {
948 my $id = shift or return (undef, undef, undef);
949 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
951 if (!defined $rev || !$uuid || !$url) {
952 # some of the original repositories I made had
953 # identifiers like this:
954 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
956 return ($url, $rev, $uuid);
960 return extract_metadata((grep(/^git-svn-id: /,
961 command(qw/cat-file commit/, shift)))[-1]);
964 sub working_head_info {
965 my ($head, $refs) = @_;
966 my @args = ('log', '--no-color', '--first-parent');
967 my ($fh, $ctx) = command_output_pipe(@args, $head);
971 if ( m{^commit ($::sha1)$} ) {
972 unshift @$refs, $hash if $hash and $refs;
976 next unless s{^\s*(git-svn-id:)}{$1};
977 my ($url, $rev, $uuid) = extract_metadata($_);
978 if (defined $url && defined $rev) {
979 next if $max{$url} and $max{$url} < $rev;
980 if (my $gs = Git::SVN->find_by_url($url)) {
981 my $c = $gs->rev_db_get($rev);
982 if ($c && $c eq $hash) {
983 close $fh; # break the pipe
984 return ($url, $rev, $uuid, $gs);
986 $max{$url} ||= $gs->rev_db_max;
991 command_close_pipe($fh, $ctx);
992 (undef, undef, undef, undef);
995 sub read_commit_parents {
996 my ($parents, $c) = @_;
997 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
998 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
999 @{$parents->{$c}} = split(/ /, $p);
1002 sub linearize_history {
1003 my ($gs, $refs) = @_;
1005 foreach my $c (@$refs) {
1006 read_commit_parents(\%parents, $c);
1011 my $last_svn_commit = $gs->last_commit;
1012 foreach my $c (reverse @$refs) {
1013 next if $c eq $last_svn_commit;
1016 unshift @linear_refs, $c;
1019 # we only want the first parent to diff against for linear
1020 # history, we save the rest to inject when we finalize the
1022 my $fp_a = verify_ref("$c~1");
1023 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1024 if (!$fp_a || !$fp_b) {
1026 "has no parent commit, and therefore ",
1027 "nothing to diff against.\n",
1028 "You should be working from a repository ",
1029 "originally created by git-svn\n";
1031 if ($fp_a ne $fp_b) {
1032 die "$c~1 = $fp_a, however parsing commit $c ",
1033 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1036 foreach my $p (@{$parents{$c}}) {
1040 (\@linear_refs, \%parents);
1046 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1047 $_repack $_repack_flags $_use_svm_props $_head
1048 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1050 use File::Path qw/mkpath/;
1051 use File::Copy qw/copy/;
1055 # properties that we do not log:
1058 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1059 svn:special svn:executable
1060 svn:entry:committed-rev
1061 svn:entry:last-author
1063 svn:entry:committed-date/;
1065 # some options are read globally, but can be overridden locally
1066 # per [svn-remote "..."] section. Command-line options will *NOT*
1067 # override options set in an [svn-remote "..."] section
1069 for my $option (qw/follow_parent no_metadata use_svm_props
1070 use_svnsync_props/) {
1073 my $prop = "-$option";
1076 return $self->{$prop} if exists $self->{$prop};
1077 my $k = "svn-remote.$self->{repo_id}.$key";
1078 eval { command_oneline(qw/config --get/, $k) };
1080 $self->{$prop} = ${"Git::SVN::_$option"};
1082 my $v = command_oneline(qw/config --bool/,$k);
1083 $self->{$prop} = $v eq 'false' ? 0 : 1;
1085 return $self->{$prop};
1091 END { unlink keys %LOCKFILES if %LOCKFILES }
1093 sub resolve_local_globs {
1094 my ($url, $fetch, $glob_spec) = @_;
1095 return unless defined $glob_spec;
1096 my $ref = $glob_spec->{ref};
1097 my $path = $glob_spec->{path};
1098 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1099 next unless m#^refs/remotes/$ref->{regex}$#;
1101 my $pathname = desanitize_refname($path->full_path($p));
1102 my $refname = desanitize_refname($ref->full_path($p));
1103 if (my $existing = $fetch->{$pathname}) {
1104 if ($existing ne $refname) {
1105 die "Refspec conflict:\n",
1106 "existing: refs/remotes/$existing\n",
1107 " globbed: refs/remotes/$refname\n";
1109 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1110 $u =~ s!^\Q$url\E(/|$)!! or die
1111 "refs/remotes/$refname: '$url' not found in '$u'\n";
1112 if ($pathname ne $u) {
1113 warn "W: Refspec glob conflict ",
1114 "(ref: refs/remotes/$refname):\n",
1115 "expected path: $pathname\n",
1117 "Continuing ahead with $u\n";
1121 $fetch->{$pathname} = $refname;
1126 sub parse_revision_argument {
1127 my ($base, $head) = @_;
1128 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1129 return ($base, $head);
1131 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1132 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1133 return ($head, $head) if ($::_revision eq 'HEAD');
1134 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1135 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1136 die "revision argument: $::_revision not understood by git-svn\n";
1140 my ($repo_id, $remotes) = @_;
1144 $repo_id = $gs->{repo_id};
1146 $remotes ||= read_all_remotes();
1147 my $remote = $remotes->{$repo_id} or
1148 die "[svn-remote \"$repo_id\"] unknown\n";
1149 my $fetch = $remote->{fetch};
1150 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1152 my $ra = Git::SVN::Ra->new($url);
1153 my $uuid = $ra->get_uuid;
1154 my $head = $ra->get_latest_revnum;
1155 my $base = defined $fetch ? $head : 0;
1157 # read the max revs for wildcard expansion (branches/*, tags/*)
1158 foreach my $t (qw/branches tags/) {
1159 defined $remote->{$t} or next;
1160 push @globs, $remote->{$t};
1161 my $max_rev = eval { tmp_config(qw/--int --get/,
1162 "svn-remote.$repo_id.${t}-maxRev") };
1163 if (defined $max_rev && ($max_rev < $base)) {
1165 } elsif (!defined $max_rev) {
1171 foreach my $p (sort keys %$fetch) {
1172 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1173 my $lr = $gs->rev_db_max;
1175 $base = $lr if ($lr < $base);
1181 ($base, $head) = parse_revision_argument($base, $head);
1182 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1185 sub read_all_remotes {
1187 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1188 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1189 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1190 $local_ref =~ s{^/}{};
1191 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1192 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1193 $r->{$1}->{url} = $2;
1194 } elsif (m!^(.+)\.(branches|tags)=
1195 (.*):refs/remotes/(.+)\s*$/!x) {
1196 my ($p, $g) = ($3, $4);
1197 my $rs = $r->{$1}->{$2} = {
1200 path => Git::SVN::GlobSpec->new($p),
1201 ref => Git::SVN::GlobSpec->new($g) };
1202 if (length($rs->{ref}->{right}) != 0) {
1203 die "The '*' glob character must be the last ",
1204 "character of '$g'\n";
1212 if (defined $_repack) {
1213 $_repack = 1000 if ($_repack <= 0);
1214 $_repack_nr = $_repack;
1215 $_repack_flags ||= '-d';
1219 sub verify_remotes_sanity {
1220 return unless -d $ENV{GIT_DIR};
1222 foreach (command(qw/config -l/)) {
1223 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1225 die "Remote ref refs/remote/$1 is tracked by",
1226 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1227 "Please resolve this ambiguity in ",
1228 "your git configuration file before ",
1236 # we allow more chars than remotes2config.sh...
1237 sub sanitize_remote_name {
1239 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1243 sub find_existing_remote {
1244 my ($url, $remotes) = @_;
1245 return undef if $no_reuse_existing;
1247 foreach my $repo_id (keys %$remotes) {
1248 my $u = $remotes->{$repo_id}->{url} or next;
1250 $existing = $repo_id;
1256 sub init_remote_config {
1257 my ($self, $url, $no_write) = @_;
1258 $url =~ s!/+$!!; # strip trailing slash
1259 my $r = read_all_remotes();
1260 my $existing = find_existing_remote($url, $r);
1262 unless ($no_write) {
1263 print STDERR "Using existing ",
1264 "[svn-remote \"$existing\"]\n";
1266 $self->{repo_id} = $existing;
1267 } elsif ($_minimize_url) {
1268 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1269 $existing = find_existing_remote($min_url, $r);
1271 unless ($no_write) {
1272 print STDERR "Using existing ",
1273 "[svn-remote \"$existing\"]\n";
1275 $self->{repo_id} = $existing;
1277 if ($min_url ne $url) {
1278 unless ($no_write) {
1279 print STDERR "Using higher level of URL: ",
1280 "$url => $min_url\n";
1282 my $old_path = $self->{path};
1283 $self->{path} = $url;
1284 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1285 if (length $old_path) {
1286 $self->{path} .= "/$old_path";
1293 # verify that we aren't overwriting anything:
1295 command_oneline('config', '--get',
1296 "svn-remote.$self->{repo_id}.url")
1298 if ($orig_url && ($orig_url ne $url)) {
1299 die "svn-remote.$self->{repo_id}.url already set: ",
1300 "$orig_url\nwanted to set to: $url\n";
1303 my ($xrepo_id, $xpath) = find_ref($self->refname);
1304 if (defined $xpath) {
1305 die "svn-remote.$xrepo_id.fetch already set to track ",
1306 "$xpath:refs/remotes/", $self->refname, "\n";
1308 unless ($no_write) {
1309 command_noisy('config',
1310 "svn-remote.$self->{repo_id}.url", $url);
1311 $self->{path} =~ s{^/}{};
1312 command_noisy('config', '--add',
1313 "svn-remote.$self->{repo_id}.fetch",
1314 "$self->{path}:".$self->refname);
1316 $self->{url} = $url;
1319 sub find_by_url { # repos_root and, path are optional
1320 my ($class, $full_url, $repos_root, $path) = @_;
1322 return undef unless defined $full_url;
1323 remove_username($full_url);
1324 remove_username($repos_root) if defined $repos_root;
1325 my $remotes = read_all_remotes();
1326 if (defined $full_url && defined $repos_root && !defined $path) {
1328 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1330 foreach my $repo_id (keys %$remotes) {
1331 my $u = $remotes->{$repo_id}->{url} or next;
1332 remove_username($u);
1333 next if defined $repos_root && $repos_root ne $u;
1335 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1336 foreach (qw/branches tags/) {
1337 resolve_local_globs($u, $fetch,
1338 $remotes->{$repo_id}->{$_});
1341 unless (defined $p) {
1343 $p =~ s#^\Q$u\E(?:/|$)## or next;
1345 foreach my $f (keys %$fetch) {
1347 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1354 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1355 my $self = _new($class, $repo_id, $ref_id, $path);
1357 $self->init_remote_config($url, $no_write);
1364 foreach (command(qw/config -l/)) {
1365 next unless m!^svn-remote\.(.+)\.fetch=
1366 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1367 my ($repo_id, $path, $ref) = ($1, $2, $3);
1368 if ($ref eq $ref_id) {
1369 $path = '' if ($path =~ m#^\./?#);
1370 return ($repo_id, $path);
1373 (undef, undef, undef);
1377 my ($class, $ref_id, $repo_id, $path) = @_;
1378 if (defined $ref_id && !defined $repo_id && !defined $path) {
1379 ($repo_id, $path) = find_ref($ref_id);
1380 if (!defined $repo_id) {
1381 die "Could not find a \"svn-remote.*.fetch\" key ",
1382 "in the repository configuration matching: ",
1383 "refs/remotes/$ref_id\n";
1386 my $self = _new($class, $repo_id, $ref_id, $path);
1387 if (!defined $self->{path} || !length $self->{path}) {
1388 my $fetch = command_oneline('config', '--get',
1389 "svn-remote.$repo_id.fetch",
1390 ":refs/remotes/$ref_id\$") or
1391 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1392 "\":refs/remotes/$ref_id\$\" in config\n";
1393 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1395 $self->{url} = command_oneline('config', '--get',
1396 "svn-remote.$repo_id.url") or
1397 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1403 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1405 # It cannot end with a slash /, we'll throw up on this because
1406 # SVN can't have directories with a slash in their name, either:
1407 if ($refname =~ m{/$}) {
1408 die "ref: '$refname' ends with a trailing slash, this is ",
1409 "not permitted by git nor Subversion\n";
1412 # It cannot have ASCII control character space, tilde ~, caret ^,
1413 # colon :, question-mark ?, asterisk *, space, or open bracket [
1416 # Additionally, % must be escaped because it is used for escaping
1417 # and we want our escaped refname to be reversible
1418 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1420 # no slash-separated component can begin with a dot .
1422 $refname =~ s{/\.}{/%2E}g;
1424 # It cannot have two consecutive dots .. anywhere
1426 $refname =~ s{\.\.}{%2E%2E}g;
1431 sub desanitize_refname {
1433 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1439 return $self->{svm}->{uuid} if $self->svm;
1441 unless ($self->{svm}) {
1442 die "SVM UUID not cached, and reading remotely failed\n";
1444 $self->{svm}->{uuid};
1449 return $self->{svm} if $self->{svm};
1451 # see if we have it in our config, first:
1453 my $section = "svn-remote.$self->{repo_id}";
1455 source => tmp_config('--get', "$section.svm-source"),
1456 uuid => tmp_config('--get', "$section.svm-uuid"),
1457 replace => tmp_config('--get', "$section.svm-replace"),
1460 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1461 $self->{svm} = $svm;
1467 my ($self, $ra) = @_;
1468 return $ra if $self->svm;
1470 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1471 "(svm:source, svm:uuid) ",
1472 "from the following URLs:\n" );
1473 sub read_svm_props {
1474 my ($self, $ra, $path, $r) = @_;
1475 my $props = ($ra->get_dir($path, $r))[2];
1476 my $src = $props->{'svm:source'};
1477 my $uuid = $props->{'svm:uuid'};
1478 return undef if (!$src || !$uuid);
1482 $uuid =~ m{^[0-9a-f\-]{30,}$}
1483 or die "doesn't look right - svm:uuid is '$uuid'\n";
1485 # the '!' is used to mark the repos_root!/relative/path
1486 $src =~ s{/?!/?}{/};
1487 $src =~ s{/+$}{}; # no trailing slashes please
1488 # username is of no interest
1489 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1491 my $replace = $ra->{url};
1492 $replace .= "/$path" if length $path;
1494 my $section = "svn-remote.$self->{repo_id}";
1495 tmp_config("$section.svm-source", $src);
1496 tmp_config("$section.svm-replace", $replace);
1497 tmp_config("$section.svm-uuid", $uuid);
1505 my $r = $ra->get_latest_revnum;
1506 my $path = $self->{path};
1508 while (length $path) {
1509 unless ($tried{"$self->{url}/$path"}) {
1510 return $ra if $self->read_svm_props($ra, $path, $r);
1511 $tried{"$self->{url}/$path"} = 1;
1513 $path =~ s#/?[^/]+$##;
1515 die "Path: '$path' should be ''\n" if $path ne '';
1516 return $ra if $self->read_svm_props($ra, $path, $r);
1517 $tried{"$self->{url}/$path"} = 1;
1519 if ($ra->{repos_root} eq $self->{url}) {
1520 die @err, (map { " $_\n" } keys %tried), "\n";
1523 # nope, make sure we're connected to the repository root:
1526 $path = $ra->{svn_path};
1527 $ra = Git::SVN::Ra->new($ra->{repos_root});
1528 while (length $path) {
1529 unless ($tried{"$ra->{url}/$path"}) {
1530 $ok = $self->read_svm_props($ra, $path, $r);
1532 $tried{"$ra->{url}/$path"} = 1;
1534 $path =~ s#/?[^/]+$##;
1536 die "Path: '$path' should be ''\n" if $path ne '';
1537 $ok ||= $self->read_svm_props($ra, $path, $r);
1538 $tried{"$ra->{url}/$path"} = 1;
1540 die @err, (map { " $_\n" } keys %tried), "\n";
1542 Git::SVN::Ra->new($self->{url});
1547 return $self->{svnsync} if $self->{svnsync};
1549 if ($self->no_metadata) {
1550 die "Can't have both 'noMetadata' and ",
1551 "'useSvnsyncProps' options set!\n";
1553 if ($self->rewrite_root) {
1554 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1559 # see if we have it in our config, first:
1561 my $section = "svn-remote.$self->{repo_id}";
1563 url => tmp_config('--get', "$section.svnsync-url"),
1564 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1567 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1568 return $self->{svnsync} = $svnsync;
1571 my $err = "useSvnsyncProps set, but failed to read " .
1572 "svnsync property: svn:sync-from-";
1573 my $rp = $self->ra->rev_proplist(0);
1575 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1576 $url =~ m{^[a-z\+]+://} or
1577 die "doesn't look right - svn:sync-from-url is '$url'\n";
1579 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1580 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1581 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1583 my $section = "svn-remote.$self->{repo_id}";
1584 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1585 tmp_config('--add', "$section.svnsync-url", $url);
1586 return $self->{svnsync} = { url => $url, uuid => $uuid };
1589 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1590 # remote lookup (useful for 'git svn log').
1593 unless ($self->{ra_uuid}) {
1594 my $key = "svn-remote.$self->{repo_id}.uuid";
1595 my $uuid = eval { tmp_config('--get', $key) };
1596 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1597 $self->{ra_uuid} = $uuid;
1599 die "ra_uuid called without URL\n" unless $self->{url};
1600 $self->{ra_uuid} = $self->ra->get_uuid;
1601 tmp_config('--add', $key, $self->{ra_uuid});
1609 my $ra = Git::SVN::Ra->new($self->{url});
1610 if ($self->use_svm_props && !$self->{svm}) {
1611 if ($self->no_metadata) {
1612 die "Can't have both 'noMetadata' and ",
1613 "'useSvmProps' options set!\n";
1614 } elsif ($self->use_svnsync_props) {
1615 die "Can't have both 'useSvnsyncProps' and ",
1616 "'useSvmProps' options set!\n";
1618 $ra = $self->_set_svm_vars($ra);
1619 $self->{-want_revprops} = 1;
1626 my $repos_root = $self->ra->{repos_root};
1627 return $self->{path} if ($self->{url} eq $repos_root);
1628 my $url = $self->{url} .
1629 (length $self->{path} ? "/$self->{path}" : $self->{path});
1630 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1634 # prop_walk(PATH, REV, SUB)
1635 # -------------------------
1636 # Recursively traverse PATH at revision REV and invoke SUB for each
1637 # directory that contains a SVN property. SUB will be invoked as
1638 # follows: &SUB(gs, path, props); where `gs' is this instance of
1639 # Git::SVN, `path' the path to the directory where the properties
1640 # `props' were found. The `path' will be relative to point of checkout,
1641 # that is, if url://repo/trunk is the current Git branch, and that
1642 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1643 # as `path' (note the trailing `/').
1645 my ($self, $path, $rev, $sub) = @_;
1647 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1650 # Strip the irrelevant part of the path.
1651 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1652 # Ensure the path is terminated by a `/'.
1655 # The properties contain all the internal SVN stuff nobody
1656 # (usually) cares about.
1657 my $interesting_props = 0;
1658 foreach (keys %{$props}) {
1659 # If it doesn't start with `svn:', it must be a
1660 # user-defined property.
1661 ++$interesting_props and next if $_ !~ /^svn:/;
1662 # FIXME: Fragile, if SVN adds new public properties,
1663 # this needs to be updated.
1664 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1665 |eol-style|mime-type
1666 |externals|needs-lock)$/x;
1668 &$sub($self, $p, $props) if $interesting_props;
1670 foreach (sort keys %$dirent) {
1671 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1672 $self->prop_walk($path . '/' . $_, $rev, $sub);
1676 sub last_rev { ($_[0]->last_rev_commit)[0] }
1677 sub last_commit { ($_[0]->last_rev_commit)[1] }
1679 # returns the newest SVN revision number and newest commit SHA1
1680 sub last_rev_commit {
1682 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1683 return ($self->{last_rev}, $self->{last_commit});
1685 my $c = ::verify_ref($self->refname.'^0');
1686 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1687 my $rev = (::cmt_metadata($c))[1];
1689 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1693 my $db_path = $self->db_path;
1694 unless (-e $db_path) {
1695 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1696 return (undef, undef);
1698 my $offset = -41; # from tail
1700 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1701 sysseek($fh, $offset, 2); # don't care for errors
1702 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1704 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1706 sysseek($fh, $offset, 2); # don't care for errors
1707 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1710 if ($c && $c ne $rl) {
1711 die "$db_path and ", $self->refname,
1712 " inconsistent!:\n$c != $rl\n";
1714 my $rev = sysseek($fh, 0, 1) or croak $!;
1715 $rev = ($rev - 41) / 41;
1716 close $fh or croak $!;
1717 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1721 sub get_fetch_range {
1722 my ($self, $min, $max) = @_;
1723 $max ||= $self->ra->get_latest_revnum;
1724 $min ||= $self->rev_db_max;
1730 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1731 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1732 if (! -f $config && -f $old_def_config) {
1733 rename $old_def_config, $config or
1734 die "Failed rename $old_def_config => $config: $!\n";
1736 my $old_config = $ENV{GIT_CONFIG};
1737 $ENV{GIT_CONFIG} = $config;
1740 unless (-f $config) {
1742 open my $fh, '>', $config or
1743 die "Can't open $config: $!\n";
1744 print $fh "; This file is used internally by ",
1746 "Couldn't write to $config: $!\n";
1747 print $fh "; You should not have to edit it\n" or
1748 die "Couldn't write to $config: $!\n";
1749 close $fh or die "Couldn't close $config: $!\n";
1751 command('config', @args);
1754 if (defined $old_config) {
1755 $ENV{GIT_CONFIG} = $old_config;
1757 delete $ENV{GIT_CONFIG};
1760 wantarray ? @ret : $ret[0];
1764 my ($self, $sub) = @_;
1765 my $old_index = $ENV{GIT_INDEX_FILE};
1766 $ENV{GIT_INDEX_FILE} = $self->{index};
1769 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1770 mkpath([$dir]) unless -d $dir;
1774 if (defined $old_index) {
1775 $ENV{GIT_INDEX_FILE} = $old_index;
1777 delete $ENV{GIT_INDEX_FILE};
1780 wantarray ? @ret : $ret[0];
1783 sub assert_index_clean {
1784 my ($self, $treeish) = @_;
1786 $self->tmp_index_do(sub {
1787 command_noisy('read-tree', $treeish) unless -e $self->{index};
1788 my $x = command_oneline('write-tree');
1789 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1790 /^tree ($::sha1)/mo);
1793 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1794 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1795 command_noisy('read-tree', $treeish);
1796 $x = command_oneline('write-tree');
1798 ::fatal "trees ($treeish) $y != $x\n",
1799 "Something is seriously wrong...";
1804 sub get_commit_parents {
1805 my ($self, $log_entry) = @_;
1806 my (%seen, @ret, @tmp);
1807 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1808 if (my $ip = $self->{inject_parents}) {
1809 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1813 if (my $cur = ::verify_ref($self->refname.'^0')) {
1816 if (my $ipd = $self->{inject_parents_dcommit}) {
1817 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1818 push @tmp, @$commit;
1821 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1822 while (my $p = shift @tmp) {
1826 # MAXPARENT is defined to 16 in commit-tree.c:
1830 die "r$log_entry->{revision}: No room for parents:\n\t",
1831 join("\n\t", @tmp), "\n";
1838 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1839 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1840 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1843 if ($rwr !~ m#^[a-z\+]+://#) {
1844 die "$rwr is not a valid URL (key: $k)\n";
1847 $self->{-rewrite_root} = $rwr;
1852 ($self->rewrite_root || $self->{url}) .
1853 (length $self->{path} ? '/' . $self->{path} : '');
1858 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1862 my ($self, $log_entry) = @_;
1863 my $lr = $self->last_rev;
1864 if (defined $lr && $lr >= $log_entry->{revision}) {
1865 die "Last fetched revision of ", $self->refname,
1866 " was r$lr, but we are about to fetch: ",
1867 "r$log_entry->{revision}!\n";
1869 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1870 croak "$log_entry->{revision} = $c already exists! ",
1871 "Why are we refetching it?\n";
1873 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1874 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1875 $log_entry->{email};
1876 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1878 my $tree = $log_entry->{tree};
1879 if (!defined $tree) {
1880 $tree = $self->tmp_index_do(sub {
1881 command_oneline('write-tree') });
1883 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1885 my @exec = ('git-commit-tree', $tree);
1886 foreach ($self->get_commit_parents($log_entry)) {
1887 push @exec, '-p', $_;
1889 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1891 print $msg_fh $log_entry->{log} or croak $!;
1892 unless ($self->no_metadata) {
1893 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1896 $msg_fh->flush == 0 or croak $!;
1897 close $msg_fh or croak $!;
1898 chomp(my $commit = do { local $/; <$out_fh> });
1899 close $out_fh or croak $!;
1902 if ($commit !~ /^$::sha1$/o) {
1903 die "Failed to commit, invalid sha1: $commit\n";
1906 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1908 $self->{last_rev} = $log_entry->{revision};
1909 $self->{last_commit} = $commit;
1910 print "r$log_entry->{revision}";
1911 if (defined $log_entry->{svm_revision}) {
1912 print " (\@$log_entry->{svm_revision})";
1913 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1914 0, $self->svm_uuid);
1916 print " = $commit ($self->{ref_id})\n";
1917 if (defined $_repack && (--$_repack_nr == 0)) {
1918 $_repack_nr = $_repack;
1919 # repack doesn't use any arguments with spaces in them, does it?
1920 print "Running git repack $_repack_flags ...\n";
1921 command_noisy('repack', split(/\s+/, $_repack_flags));
1922 print "Done repacking\n";
1928 my ($self, $paths, $r) = @_;
1929 return 1 if $self->{path} eq '';
1930 if (my $path = $paths->{"/$self->{path}"}) {
1931 return ($path->{action} eq 'D') ? 0 : 1;
1933 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1934 if (grep /$self->{path_regex}/, keys %$paths) {
1938 foreach (split m#/#, $self->{path}) {
1940 next unless ($paths->{$c} &&
1941 ($paths->{$c}->{action} =~ /^[AR]$/));
1942 if ($self->ra->check_path($self->{path}, $r) ==
1950 sub find_parent_branch {
1951 my ($self, $paths, $rev) = @_;
1952 return undef unless $self->follow_parent;
1953 unless (defined $paths) {
1954 my $err_handler = $SVN::Error::handler;
1955 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1956 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1958 Git::SVN::Ra::dup_changed_paths($_[0]) });
1959 $SVN::Error::handler = $err_handler;
1961 return undef unless defined $paths;
1963 # look for a parent from another branch:
1964 my @b_path_components = split m#/#, $self->rel_path;
1965 my @a_path_components;
1967 while (@b_path_components) {
1968 $i = $paths->{'/'.join('/', @b_path_components)};
1969 last if $i && defined $i->{copyfrom_path};
1970 unshift(@a_path_components, pop(@b_path_components));
1972 return undef unless defined $i && defined $i->{copyfrom_path};
1973 my $branch_from = $i->{copyfrom_path};
1974 if (@a_path_components) {
1975 print STDERR "branch_from: $branch_from => ";
1976 $branch_from .= '/'.join('/', @a_path_components);
1977 print STDERR $branch_from, "\n";
1979 my $r = $i->{copyfrom_rev};
1980 my $repos_root = $self->ra->{repos_root};
1981 my $url = $self->ra->{url};
1982 my $new_url = $repos_root . $branch_from;
1983 print STDERR "Found possible branch point: ",
1984 "$new_url => ", $self->full_url, ", $r\n";
1985 $branch_from =~ s#^/##;
1986 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1988 my $ref_id = $self->{ref_id};
1989 $ref_id =~ s/\@\d+$//;
1991 # just grow a tail if we're not unique enough :x
1992 $ref_id .= '-' while find_ref($ref_id);
1993 print STDERR "Initializing parent: $ref_id\n";
1994 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1996 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1997 if (!defined $r0 || !defined $parent) {
1998 my ($base, $head) = parse_revision_argument(0, $r);
2000 $gs->fetch($base, $r);
2002 ($r0, $parent) = $gs->last_rev_commit;
2004 if (defined $r0 && defined $parent) {
2005 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2007 if ($self->ra->can_do_switch) {
2008 $self->assert_index_clean($parent);
2009 print STDERR "Following parent with do_switch\n";
2010 # do_switch works with svn/trunk >= r22312, but that
2011 # is not included with SVN 1.4.3 (the latest version
2012 # at the moment), so we can't rely on it
2013 $self->{last_commit} = $parent;
2014 $ed = SVN::Git::Fetcher->new($self);
2015 $gs->ra->gs_do_switch($r0, $rev, $gs,
2016 $self->full_url, $ed)
2017 or die "SVN connection failed somewhere...\n";
2018 } elsif ($self->ra->trees_match($new_url, $r0,
2019 $self->full_url, $rev)) {
2020 print STDERR "Trees match:\n",
2022 " ${\$self->full_url}\@$rev\n",
2023 "Following parent with no changes\n";
2024 $self->tmp_index_do(sub {
2025 command_noisy('read-tree', $parent);
2027 $self->{last_commit} = $parent;
2029 print STDERR "Following parent with do_update\n";
2030 $ed = SVN::Git::Fetcher->new($self);
2031 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2032 or die "SVN connection failed somewhere...\n";
2034 print STDERR "Successfully followed parent\n";
2035 return $self->make_log_entry($rev, [$parent], $ed);
2041 my ($self, $paths, $rev) = @_;
2043 my ($last_rev, @parents);
2044 if (my $lc = $self->last_commit) {
2045 # we can have a branch that was deleted, then re-added
2046 # under the same name but copied from another path, in
2047 # which case we'll have multiple parents (we don't
2048 # want to break the original ref, nor lose copypath info):
2049 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2050 push @{$log_entry->{parents}}, $lc;
2053 $ed = SVN::Git::Fetcher->new($self);
2054 $last_rev = $self->{last_rev};
2059 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2062 $ed = SVN::Git::Fetcher->new($self);
2064 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2065 die "SVN connection failed somewhere...\n";
2067 $self->make_log_entry($rev, \@parents, $ed);
2071 my ($self, $ed) = @_;
2073 my $h = $ed->{empty};
2074 foreach (sort keys %$h) {
2075 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2076 push @out, " $act: " . uri_encode($_);
2077 warn "W: $act: $_\n";
2079 foreach my $t (qw/dir_prop file_prop/) {
2080 $h = $ed->{$t} or next;
2081 foreach my $path (sort keys %$h) {
2082 my $ppath = $path eq '' ? '.' : $path;
2083 foreach my $prop (sort keys %{$h->{$path}}) {
2084 next if $SKIP_PROP{$prop};
2085 my $v = $h->{$path}->{$prop};
2086 my $t_ppath_prop = "$t: " .
2087 uri_encode($ppath) . ' ' .
2090 push @out, " +$t_ppath_prop " .
2093 push @out, " -$t_ppath_prop";
2098 foreach my $t (qw/absent_file absent_directory/) {
2099 $h = $ed->{$t} or next;
2100 foreach my $parent (sort keys %$h) {
2101 foreach my $path (sort @{$h->{$parent}}) {
2102 push @out, " $t: " .
2103 uri_encode("$parent/$path");
2104 warn "W: $t: $parent/$path ",
2105 "Insufficient permissions?\n";
2112 sub parse_svn_date {
2113 my $date = shift || return '+0000 1970-01-01 00:00:00';
2114 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2115 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2116 croak "Unable to parse date: $date\n";
2117 "+0000 $Y-$m-$d $H:$M:$S";
2122 if (!defined $author || length $author == 0) {
2123 $author = '(no author)';
2125 if (defined $::_authors && ! defined $::users{$author}) {
2126 die "Author: $author not defined in $::_authors file\n";
2131 sub make_log_entry {
2132 my ($self, $rev, $parents, $ed) = @_;
2133 my $untracked = $self->get_untracked($ed);
2135 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2136 print $un "r$rev\n" or croak $!;
2137 print $un $_, "\n" foreach @$untracked;
2138 my %log_entry = ( parents => $parents || [], revision => $rev,
2142 my $logged = delete $self->{logged_rev_props};
2143 if (!$logged || $self->{-want_revprops}) {
2144 my $rp = $self->ra->rev_proplist($rev);
2145 foreach (sort keys %$rp) {
2147 if (/^svn:(author|date|log)$/) {
2148 $log_entry{$1} = $v;
2149 } elsif ($_ eq 'svm:headrev') {
2152 print $un " rev_prop: ", uri_encode($_), ' ',
2153 uri_encode($v), "\n";
2157 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2159 close $un or croak $!;
2161 $log_entry{date} = parse_svn_date($log_entry{date});
2162 $log_entry{log} .= "\n";
2163 my $author = $log_entry{author} = check_author($log_entry{author});
2164 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2166 if (defined $headrev && $self->use_svm_props) {
2167 if ($self->rewrite_root) {
2168 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2171 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2172 # we don't want "SVM: initializing mirror for junk" ...
2173 return undef if $r == 0;
2174 my $svm = $self->svm;
2175 if ($uuid ne $svm->{uuid}) {
2176 die "UUID mismatch on SVM path:\n",
2177 "expected: $svm->{uuid}\n",
2180 my $full_url = $self->full_url;
2181 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2182 die "Failed to replace '$svm->{replace}' with ",
2183 "'$svm->{source}' in $full_url\n";
2184 # throw away username for storing in records
2185 remove_username($full_url);
2186 $log_entry{metadata} = "$full_url\@$r $uuid";
2187 $log_entry{svm_revision} = $r;
2188 $email ||= "$author\@$uuid"
2189 } elsif ($self->use_svnsync_props) {
2190 my $full_url = $self->svnsync->{url};
2191 $full_url .= "/$self->{path}" if length $self->{path};
2192 remove_username($full_url);
2193 my $uuid = $self->svnsync->{uuid};
2194 $log_entry{metadata} = "$full_url\@$rev $uuid";
2195 $email ||= "$author\@$uuid"
2197 my $url = $self->metadata_url;
2198 remove_username($url);
2199 $log_entry{metadata} = "$url\@$rev " .
2200 $self->ra->get_uuid;
2201 $email ||= "$author\@" . $self->ra->get_uuid;
2203 $log_entry{name} = $name;
2204 $log_entry{email} = $email;
2209 my ($self, $min_rev, $max_rev, @parents) = @_;
2210 my ($last_rev, $last_commit) = $self->last_rev_commit;
2211 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2212 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2216 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2217 $self->{inject_parents} = { $rev => $tree };
2218 $self->fetch(undef, undef);
2222 my ($self, $tree) = (shift, shift);
2223 my $log_entry = ::get_commit_entry($tree);
2224 unless ($self->{last_rev}) {
2225 fatal("Must have an existing revision to commit");
2227 my %ed_opts = ( r => $self->{last_rev},
2228 log => $log_entry->{log},
2230 tree_a => $self->{last_commit},
2233 $self->set_tree_cb($log_entry, $tree, @_) },
2234 svn_path => $self->{path} );
2235 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2236 print "No changes\nr$self->{last_rev} = $tree\n";
2242 my $db_path = $self->db_path;
2243 return if (-e $db_path && ! -z $db_path);
2244 return unless ::verify_ref($self->refname.'^0');
2245 if (-f $self->{db_root}) {
2246 rename $self->{db_root}, $db_path or die
2247 "rename $self->{db_root} => $db_path failed: $!\n";
2248 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2249 symlink $base, $self->{db_root} or die
2250 "symlink $base => $self->{db_root} failed: $!\n";
2253 print "Rebuilding $db_path ...\n";
2254 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2256 my $full_url = $self->full_url;
2257 remove_username($full_url);
2261 if ( m{^commit ($::sha1)$} ) {
2265 next unless s{^\s*(git-svn-id:)}{$1};
2266 my ($url, $rev, $uuid) = ::extract_metadata($_);
2267 remove_username($url);
2269 # ignore merges (from set-tree)
2270 next if (!defined $rev || !$uuid);
2272 # if we merged or otherwise started elsewhere, this is
2273 # how we break out of it
2274 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2275 ($full_url && $url && ($url ne $full_url))) {
2279 $svn_uuid ||= $uuid;
2281 $self->rev_db_set($rev, $c);
2282 print "r$rev = $c\n";
2284 command_close_pipe($log, $ctx);
2285 print "Done rebuilding $db_path\n";
2289 # Tie::File seems to be prone to offset errors if revisions get sparse,
2290 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2291 # one of my favorite modules is out :< Next up would be one of the DBM
2292 # modules, but I'm not sure which is most portable... So I'll just
2293 # go with something that's plain-text, but still capable of
2294 # being randomly accessed. So here's my ultra-simple fixed-width
2295 # database. All records are 40 characters + "\n", so it's easy to seek
2296 # to a revision: (41 * rev) is the byte offset.
2297 # A record of 40 0s denotes an empty revision.
2298 # And yes, it's still pretty fast (faster than Tie::File).
2299 # These files are disposable unless noMetadata or useSvmProps is set
2302 my ($fh, $rev, $commit) = @_;
2303 my $offset = $rev * 41;
2304 # assume that append is the common case:
2305 seek $fh, 0, 2 or croak $!;
2307 if ($pos < $offset) {
2308 for (1 .. (($offset - $pos) / 41)) {
2309 print $fh (('0' x 40),"\n") or croak $!;
2312 seek $fh, $offset, 0 or croak $!;
2313 print $fh $commit,"\n" or croak $!;
2319 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2320 mkpath([$dir]) unless -d $dir;
2321 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2322 close $fh or die "Couldn't close (create) $path: $!\n";
2327 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2328 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2329 my $db = $self->db_path($uuid);
2330 my $db_lock = "$db.lock";
2333 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2334 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2338 $LOCKFILES{$db_lock} = 1;
2340 # both of these options make our .rev_db file very, very important
2341 # and we can't afford to lose it because rebuild() won't work
2342 if ($self->use_svm_props || $self->no_metadata) {
2344 copy($db, $db_lock) or die "rev_db_set(@_): ",
2346 "$db => $db_lock ($!)\n";
2348 rename $db, $db_lock or die "rev_db_set(@_): ",
2349 "Failed to rename: ",
2350 "$db => $db_lock ($!)\n";
2352 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2353 _rev_db_set($fh, $rev, $commit);
2355 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2356 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2358 close $fh or croak $!;
2361 command_noisy('update-ref', '-m', "r$rev",
2362 $self->refname, $commit);
2364 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2365 "$db_lock => $db ($!)\n";
2366 delete $LOCKFILES{$db_lock};
2368 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2369 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2370 kill $sig, $$ if defined $sig;
2377 my $db_path = $self->db_path;
2378 my @stat = stat $db_path or return 0;
2379 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2380 my $max = $stat[7] / 41;
2381 (($max > 0) ? $max - 1 : 0);
2385 my ($self, $rev, $uuid) = @_;
2387 my $offset = $rev * 41;
2388 my $db_path = $self->db_path($uuid);
2389 return undef unless -e $db_path;
2390 open my $fh, '<', $db_path or croak $!;
2391 if (sysseek($fh, $offset, 0) == $offset) {
2392 my $read = sysread($fh, $ret, 40);
2393 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2395 close $fh or croak $!;
2399 sub find_rev_before {
2400 my ($self, $rev, $eq_ok) = @_;
2401 --$rev unless $eq_ok;
2403 if (my $c = $self->rev_db_get($rev)) {
2408 return (undef, undef);
2412 my ($class, $repo_id, $ref_id, $path) = @_;
2413 unless (defined $repo_id && length $repo_id) {
2414 $repo_id = $Git::SVN::default_repo_id;
2416 unless (defined $ref_id && length $ref_id) {
2417 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2419 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2420 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2421 $_[3] = $path = '' unless (defined $path);
2422 mkpath(["$ENV{GIT_DIR}/svn"]);
2424 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2425 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2426 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2430 my ($self, $uuid) = @_;
2431 $uuid ||= $self->ra_uuid;
2432 "$self->{db_root}.$uuid";
2437 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2441 sub remove_username {
2442 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2445 package Git::SVN::Prompt;
2449 use vars qw/$_no_auth_cache $_username/;
2452 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2453 $may_save = undef if $_no_auth_cache;
2454 $default_username = $_username if defined $_username;
2455 if (defined $default_username && length $default_username) {
2456 if (defined $realm && length $realm) {
2457 print STDERR "Authentication realm: $realm\n";
2460 $cred->username($default_username);
2462 username($cred, $realm, $may_save, $pool);
2464 $cred->password(_read_password("Password for '" .
2465 $cred->username . "': ", $realm));
2466 $cred->may_save($may_save);
2467 $SVN::_Core::SVN_NO_ERROR;
2470 sub ssl_server_trust {
2471 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2472 $may_save = undef if $_no_auth_cache;
2473 print STDERR "Error validating server certificate for '$realm':\n";
2476 # All variables SVN::Auth::SSL::* are used only once,
2477 # so we're shutting up Perl warnings about this.
2478 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2479 print STDERR " - The certificate is not issued ",
2480 "by a trusted authority. Use the\n",
2481 " fingerprint to validate ",
2482 "the certificate manually!\n";
2484 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2485 print STDERR " - The certificate hostname ",
2486 "does not match.\n";
2488 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2489 print STDERR " - The certificate is not yet valid.\n";
2491 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2492 print STDERR " - The certificate has expired.\n";
2494 if ($failures & $SVN::Auth::SSL::OTHER) {
2495 print STDERR " - The certificate has ",
2496 "an unknown error.\n";
2498 } # no warnings 'once'
2500 "Certificate information:\n".
2501 " - Hostname: %s\n".
2502 " - Valid: from %s until %s\n".
2504 " - Fingerprint: %s\n",
2505 map $cert_info->$_, qw(hostname valid_from valid_until
2506 issuer_dname fingerprint);
2509 print STDERR $may_save ?
2510 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2511 "(R)eject or accept (t)emporarily? ";
2513 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2514 if ($choice =~ /^t$/i) {
2515 $cred->may_save(undef);
2516 } elsif ($choice =~ /^r$/i) {
2518 } elsif ($may_save && $choice =~ /^p$/i) {
2519 $cred->may_save($may_save);
2523 $cred->accepted_failures($failures);
2524 $SVN::_Core::SVN_NO_ERROR;
2527 sub ssl_client_cert {
2528 my ($cred, $realm, $may_save, $pool) = @_;
2529 $may_save = undef if $_no_auth_cache;
2530 print STDERR "Client certificate filename: ";
2532 chomp(my $filename = <STDIN>);
2533 $cred->cert_file($filename);
2534 $cred->may_save($may_save);
2535 $SVN::_Core::SVN_NO_ERROR;
2538 sub ssl_client_cert_pw {
2539 my ($cred, $realm, $may_save, $pool) = @_;
2540 $may_save = undef if $_no_auth_cache;
2541 $cred->password(_read_password("Password: ", $realm));
2542 $cred->may_save($may_save);
2543 $SVN::_Core::SVN_NO_ERROR;
2547 my ($cred, $realm, $may_save, $pool) = @_;
2548 $may_save = undef if $_no_auth_cache;
2549 if (defined $realm && length $realm) {
2550 print STDERR "Authentication realm: $realm\n";
2553 if (defined $_username) {
2554 $username = $_username;
2556 print STDERR "Username: ";
2558 chomp($username = <STDIN>);
2560 $cred->username($username);
2561 $cred->may_save($may_save);
2562 $SVN::_Core::SVN_NO_ERROR;
2565 sub _read_password {
2566 my ($prompt, $realm) = @_;
2567 print STDERR $prompt;
2569 require Term::ReadKey;
2570 Term::ReadKey::ReadMode('noecho');
2572 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2573 last if $key =~ /[\012\015]/; # \n\r
2576 Term::ReadKey::ReadMode('restore');
2582 package SVN::Git::Fetcher;
2590 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2592 my ($class, $git_svn) = @_;
2593 my $self = SVN::Delta::Editor->new;
2594 bless $self, $class;
2595 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2596 $self->{empty} = {};
2597 $self->{dir_prop} = {};
2598 $self->{file_prop} = {};
2599 $self->{absent_dir} = {};
2600 $self->{absent_file} = {};
2601 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2605 sub set_path_strip {
2606 my ($self, $path) = @_;
2607 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2614 sub open_directory {
2615 my ($self, $path, $pb, $rev) = @_;
2620 my ($self, $path) = @_;
2621 if ($self->{path_strip}) {
2622 $path =~ s!$self->{path_strip}!! or
2623 die "Failed to strip path '$path' ($self->{path_strip})\n";
2629 my ($self, $path, $rev, $pb) = @_;
2631 my $gpath = $self->git_path($path);
2632 return undef if ($gpath eq '');
2634 # remove entire directories.
2635 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2636 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2638 $self->{c}, '--', $gpath);
2642 $self->{gii}->remove($_);
2643 print "\tD\t$_\n" unless $::_q;
2645 print "\tD\t$gpath/\n" unless $::_q;
2646 command_close_pipe($ls, $ctx);
2647 $self->{empty}->{$path} = 0
2649 $self->{gii}->remove($gpath);
2650 print "\tD\t$gpath\n" unless $::_q;
2656 my ($self, $path, $pb, $rev) = @_;
2657 my $gpath = $self->git_path($path);
2658 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2659 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2660 unless (defined $mode && defined $blob) {
2661 die "$path was not found in commit $self->{c} (r$rev)\n";
2663 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2664 pool => SVN::Pool->new, action => 'M' };
2668 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2669 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2670 delete $self->{empty}->{$dir};
2671 { path => $path, mode_a => 100644, mode_b => 100644,
2672 pool => SVN::Pool->new, action => 'A' };
2676 my ($self, $path, $cp_path, $cp_rev) = @_;
2677 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2678 delete $self->{empty}->{$dir};
2679 $self->{empty}->{$path} = 1;
2683 sub change_dir_prop {
2684 my ($self, $db, $prop, $value) = @_;
2685 $self->{dir_prop}->{$db->{path}} ||= {};
2686 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2690 sub absent_directory {
2691 my ($self, $path, $pb) = @_;
2692 $self->{absent_dir}->{$pb->{path}} ||= [];
2693 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2698 my ($self, $path, $pb) = @_;
2699 $self->{absent_file}->{$pb->{path}} ||= [];
2700 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2704 sub change_file_prop {
2705 my ($self, $fb, $prop, $value) = @_;
2706 if ($prop eq 'svn:executable') {
2707 if ($fb->{mode_b} != 120000) {
2708 $fb->{mode_b} = defined $value ? 100755 : 100644;
2710 } elsif ($prop eq 'svn:special') {
2711 $fb->{mode_b} = defined $value ? 120000 : 100644;
2713 $self->{file_prop}->{$fb->{path}} ||= {};
2714 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2719 sub apply_textdelta {
2720 my ($self, $fb, $exp) = @_;
2721 my $fh = IO::File->new_tmpfile;
2723 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2724 # (but $base does not,) so dup() it for reading in close_file
2725 open my $dup, '<&', $fh or croak $!;
2726 my $base = IO::File->new_tmpfile;
2727 $base->autoflush(1);
2729 defined (my $pid = fork) or croak $!;
2731 open STDOUT, '>&', $base or croak $!;
2732 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2733 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2739 seek $base, 0, 0 or croak $!;
2740 my $md5 = Digest::MD5->new;
2741 $md5->addfile($base);
2742 my $got = $md5->hexdigest;
2743 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2745 " got: $got\n" if ($got ne $exp);
2748 seek $base, 0, 0 or croak $!;
2750 $fb->{base} = $base;
2751 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2755 my ($self, $fb, $exp) = @_;
2757 my $path = $self->git_path($fb->{path});
2758 if (my $fh = $fb->{fh}) {
2760 seek($fh, 0, 0) or croak $!;
2761 my $md5 = Digest::MD5->new;
2763 my $got = $md5->hexdigest;
2765 die "Checksum mismatch: $path\n",
2766 "expected: $exp\n got: $got\n";
2769 sysseek($fh, 0, 0) or croak $!;
2770 if ($fb->{mode_b} == 120000) {
2771 sysread($fh, my $buf, 5) == 5 or croak $!;
2772 $buf eq 'link ' or die "$path has mode 120000",
2773 "but is not a link\n";
2775 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2777 open STDIN, '<&', $fh or croak $!;
2778 exec qw/git-hash-object -w --stdin/ or croak $!;
2780 chomp($hash = do { local $/; <$out> });
2781 close $out or croak $!;
2782 close $fh or croak $!;
2783 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2784 close $fb->{base} or croak $!;
2786 $hash = $fb->{blob} or die "no blob information\n";
2789 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2790 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2796 $self->{nr} = $self->{gii}->{nr};
2797 delete $self->{gii};
2798 $self->SUPER::abort_edit(@_);
2803 $self->{git_commit_ok} = 1;
2804 $self->{nr} = $self->{gii}->{nr};
2805 delete $self->{gii};
2806 $self->SUPER::close_edit(@_);
2809 package SVN::Git::Editor;
2810 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2818 my ($class, $opts) = @_;
2819 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2820 die "$_ required!\n" unless (defined $opts->{$_});
2823 my $pool = SVN::Pool->new;
2824 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2825 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2828 # $opts->{ra} functions should not be used after this:
2829 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2830 $opts->{editor_cb}, $pool);
2831 my $self = SVN::Delta::Editor->new(@ce, $pool);
2832 bless $self, $class;
2833 foreach (qw/svn_path r tree_a tree_b/) {
2834 $self->{$_} = $opts->{$_};
2836 $self->{url} = $opts->{ra}->{url};
2837 $self->{mods} = $mods;
2838 $self->{types} = $types;
2839 $self->{pool} = $pool;
2840 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2842 $self->{path_prefix} = length $self->{svn_path} ?
2843 "$self->{svn_path}/" : '';
2848 my ($tree_a, $tree_b) = @_;
2849 my @diff_tree = qw(diff-tree -z -r);
2850 if ($_cp_similarity) {
2851 push @diff_tree, "-C$_cp_similarity";
2853 push @diff_tree, '-C';
2855 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2856 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2857 push @diff_tree, $tree_a, $tree_b;
2858 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2862 while (<$diff_fh>) {
2863 chomp $_; # this gets rid of the trailing "\0"
2864 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2865 $::sha1\s($::sha1)\s
2866 ([MTCRAD])\d*$/xo) {
2867 push @mods, { mode_a => $1, mode_b => $2,
2868 sha1_b => $3, chg => $4 };
2869 if ($4 =~ /^(?:C|R)$/) {
2874 } elsif ($state eq 'file_a') {
2875 my $x = $mods[$#mods] or croak "Empty array\n";
2876 if ($x->{chg} !~ /^(?:C|R)$/) {
2877 croak "Error parsing $_, $x->{chg}\n";
2881 } elsif ($state eq 'file_b') {
2882 my $x = $mods[$#mods] or croak "Empty array\n";
2883 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2884 croak "Error parsing $_, $x->{chg}\n";
2886 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2887 croak "Error parsing $_, $x->{chg}\n";
2892 croak "Error parsing $_\n";
2895 command_close_pipe($diff_fh, $ctx);
2899 sub check_diff_paths {
2900 my ($ra, $pfx, $rev, $mods) = @_;
2902 $pfx .= '/' if length $pfx;
2904 sub type_diff_paths {
2905 my ($ra, $types, $path, $rev) = @_;
2906 my @p = split m#/+#, $path;
2908 unless (defined $types->{$c}) {
2909 $types->{$c} = $ra->check_path($c, $rev);
2912 $c .= '/' . shift @p;
2913 next if defined $types->{$c};
2914 $types->{$c} = $ra->check_path($c, $rev);
2918 foreach my $m (@$mods) {
2919 foreach my $f (qw/file_a file_b/) {
2920 next unless defined $m->{$f};
2921 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2922 if (length $pfx.$dir && ! defined $types{$dir}) {
2923 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2931 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2935 my ($self, $path) = @_;
2936 $self->{path_prefix}.(defined $path ? $path : '');
2940 my ($self, $path) = @_;
2941 if ($self->{url} =~ m#^https?://#) {
2942 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2944 $self->{url} . '/' . $self->repo_path($path);
2949 my $rm = $self->{rm};
2950 delete $rm->{''}; # we never delete the url we're tracking
2953 foreach (keys %$rm) {
2954 my @d = split m#/#, $_;
2958 $c .= '/' . shift @d;
2962 delete $rm->{$self->{svn_path}};
2963 delete $rm->{''}; # we never delete the url we're tracking
2966 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2971 my @dn = split m#/#, $_;
2973 delete $rm->{join '/', @dn};
2980 command_close_pipe($fh, $ctx);
2982 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2983 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2984 $self->close_directory($bat->{$d}, $p);
2985 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
2986 print "\tD+\t$d/\n" unless $::_q;
2987 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2992 sub open_or_add_dir {
2993 my ($self, $full_path, $baton) = @_;
2994 my $t = $self->{types}->{$full_path};
2996 die "$full_path not known in r$self->{r} or we have a bug!\n";
3000 # SVN::Node::none and SVN::Node::file are used only once,
3001 # so we're shutting up Perl's warnings about them.
3002 if ($t == $SVN::Node::none) {
3003 return $self->add_directory($full_path, $baton,
3004 undef, -1, $self->{pool});
3005 } elsif ($t == $SVN::Node::dir) {
3006 return $self->open_directory($full_path, $baton,
3007 $self->{r}, $self->{pool});
3008 } # no warnings 'once'
3009 print STDERR "$full_path already exists in repository at ",
3010 "r$self->{r} and it is not a directory (",
3011 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3012 } # no warnings 'once'
3017 my ($self, $path) = @_;
3018 my $bat = $self->{bat};
3019 my $repo_path = $self->repo_path($path);
3020 return $bat->{''} unless (length $repo_path);
3021 my @p = split m#/+#, $repo_path;
3023 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3026 $c .= '/' . shift @p;
3027 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3033 my ($self, $m) = @_;
3034 my ($dir, $file) = split_path($m->{file_b});
3035 my $pbat = $self->ensure_path($dir);
3036 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3038 print "\tA\t$m->{file_b}\n" unless $::_q;
3039 $self->chg_file($fbat, $m);
3040 $self->close_file($fbat,undef,$self->{pool});
3044 my ($self, $m) = @_;
3045 my ($dir, $file) = split_path($m->{file_b});
3046 my $pbat = $self->ensure_path($dir);
3047 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3048 $self->url_path($m->{file_a}), $self->{r});
3049 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3050 $self->chg_file($fbat, $m);
3051 $self->close_file($fbat,undef,$self->{pool});
3055 my ($self, $path, $pbat) = @_;
3056 my $rpath = $self->repo_path($path);
3057 my ($dir, $file) = split_path($rpath);
3058 $self->{rm}->{$dir} = 1;
3059 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3063 my ($self, $m) = @_;
3064 my ($dir, $file) = split_path($m->{file_b});
3065 my $pbat = $self->ensure_path($dir);
3066 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3067 $self->url_path($m->{file_a}), $self->{r});
3068 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3069 $self->chg_file($fbat, $m);
3070 $self->close_file($fbat,undef,$self->{pool});
3072 ($dir, $file) = split_path($m->{file_a});
3073 $pbat = $self->ensure_path($dir);
3074 $self->delete_entry($m->{file_a}, $pbat);
3078 my ($self, $m) = @_;
3079 my ($dir, $file) = split_path($m->{file_b});
3080 my $pbat = $self->ensure_path($dir);
3081 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3082 $pbat,$self->{r},$self->{pool});
3083 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3084 $self->chg_file($fbat, $m);
3085 $self->close_file($fbat,undef,$self->{pool});
3088 sub T { shift->M(@_) }
3090 sub change_file_prop {
3091 my ($self, $fbat, $pname, $pval) = @_;
3092 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3096 my ($self, $fbat, $m) = @_;
3097 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3098 $self->change_file_prop($fbat,'svn:executable','*');
3099 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3100 $self->change_file_prop($fbat,'svn:executable',undef);
3102 my $fh = IO::File->new_tmpfile or croak $!;
3103 if ($m->{mode_b} =~ /^120/) {
3104 print $fh 'link ' or croak $!;
3105 $self->change_file_prop($fbat,'svn:special','*');
3106 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3107 $self->change_file_prop($fbat,'svn:special',undef);
3109 defined(my $pid = fork) or croak $!;
3111 open STDOUT, '>&', $fh or croak $!;
3112 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3116 $fh->flush == 0 or croak $!;
3117 seek $fh, 0, 0 or croak $!;
3119 my $md5 = Digest::MD5->new;
3120 $md5->addfile($fh) or croak $!;
3121 seek $fh, 0, 0 or croak $!;
3123 my $exp = $md5->hexdigest;
3124 my $pool = SVN::Pool->new;
3125 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3126 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3127 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3130 close $fh or croak $!;
3134 my ($self, $m) = @_;
3135 my ($dir, $file) = split_path($m->{file_b});
3136 my $pbat = $self->ensure_path($dir);
3137 print "\tD\t$m->{file_b}\n" unless $::_q;
3138 $self->delete_entry($m->{file_b}, $pbat);
3143 my ($p,$bat) = ($self->{pool}, $self->{bat});
3144 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3146 $self->close_directory($bat->{$_}, $p);
3148 $self->close_directory($bat->{''}, $p);
3149 $self->SUPER::close_edit($p);
3155 $self->SUPER::abort_edit($self->{pool});
3160 $self->SUPER::DESTROY(@_);
3161 $self->{pool}->clear;
3164 # this drives the editor
3167 my $mods = $self->{mods};
3168 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3169 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3171 if (defined $o{$f}) {
3174 fatal("Invalid change type: $f");
3177 $self->rmdirs if $_rmdir;
3183 return scalar @$mods;
3186 package Git::SVN::Ra;
3187 use vars qw/@ISA $config_dir $_log_window_size/;
3190 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3193 # enforce temporary pool usage for some simple functions
3195 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3196 my $SUPER = "SUPER::$f";
3199 my $pool = SVN::Pool->new;
3200 my @ret = $self->$SUPER(@_,$pool);
3202 wantarray ? @ret : $ret[0];
3207 sub _auth_providers () {
3209 SVN::Client::get_simple_provider(),
3210 SVN::Client::get_ssl_server_trust_file_provider(),
3211 SVN::Client::get_simple_prompt_provider(
3212 \&Git::SVN::Prompt::simple, 2),
3213 SVN::Client::get_ssl_client_cert_file_provider(),
3214 SVN::Client::get_ssl_client_cert_prompt_provider(
3215 \&Git::SVN::Prompt::ssl_client_cert, 2),
3216 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3217 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3218 SVN::Client::get_username_provider(),
3219 SVN::Client::get_ssl_server_trust_prompt_provider(
3220 \&Git::SVN::Prompt::ssl_server_trust),
3221 SVN::Client::get_username_prompt_provider(
3222 \&Git::SVN::Prompt::username, 2)
3226 sub escape_uri_only {
3229 foreach (split m{/}, $uri) {
3230 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3238 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3239 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3240 $url = "$scheme://$domain$uri";
3246 my ($class, $url) = @_;
3248 return $RA if ($RA && $RA->{url} eq $url);
3250 SVN::_Core::svn_config_ensure($config_dir, undef);
3251 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3252 my $config = SVN::Core::config_get_config($config_dir);
3254 my $dont_store_passwords = 1;
3255 my $conf_t = ${$config}{'config'};
3258 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3259 # produces warnings that variables are used only once.
3260 # I had not found the better way to shut them up, so
3261 # the warnings of type 'once' are disabled in this block.
3262 if (SVN::_Core::svn_config_get_bool($conf_t,
3263 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3264 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3266 SVN::_Core::svn_auth_set_parameter($baton,
3267 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3268 bless (\$dont_store_passwords, "_p_void"));
3270 if (SVN::_Core::svn_config_get_bool($conf_t,
3271 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3272 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3274 $Git::SVN::Prompt::_no_auth_cache = 1;
3276 } # no warnings 'once'
3277 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3279 pool => SVN::Pool->new,
3280 auth_provider_callbacks => $callbacks);
3281 $self->{url} = $url;
3282 $self->{svn_path} = $url;
3283 $self->{repos_root} = $self->get_repos_root;
3284 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3285 $self->{cache} = { check_path => { r => 0, data => {} },
3286 get_dir => { r => 0, data => {} } };
3287 $RA = bless $self, $class;
3291 my ($self, $path, $r) = @_;
3292 my $cache = $self->{cache}->{check_path};
3293 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3294 return $cache->{data}->{$path};
3296 my $pool = SVN::Pool->new;
3297 my $t = $self->SUPER::check_path($path, $r, $pool);
3299 if ($r != $cache->{r}) {
3300 %{$cache->{data}} = ();
3303 $cache->{data}->{$path} = $t;
3307 my ($self, $dir, $r) = @_;
3308 my $cache = $self->{cache}->{get_dir};
3309 if ($r == $cache->{r}) {
3310 if (my $x = $cache->{data}->{$dir}) {
3311 return wantarray ? @$x : $x->[0];
3314 my $pool = SVN::Pool->new;
3315 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3316 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3318 if ($r != $cache->{r}) {
3319 %{$cache->{data}} = ();
3322 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3323 wantarray ? (\%dirents, $r, $props) : \%dirents;
3327 # do not call the real DESTROY since we store ourselves in $RA
3331 my ($self, @args) = @_;
3332 my $pool = SVN::Pool->new;
3333 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3334 my $ret = $self->SUPER::get_log(@args, $pool);
3340 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3341 my $ctx = SVN::Client->new(auth => _auth_providers);
3342 my $out = IO::File->new_tmpfile;
3344 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3345 # $ctx->diff(), so we'll create a default one
3346 my $pool = SVN::Pool->new_default_sub;
3348 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3349 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3351 my $ret = (($out->stat)[7] == 0);
3352 close $out or croak $!;
3357 sub get_commit_editor {
3358 my ($self, $log, $cb, $pool) = @_;
3359 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3360 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3364 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3365 my $new = ($rev_a == $rev_b);
3366 my $path = $gs->{path};
3368 if ($new && -e $gs->{index}) {
3369 unlink $gs->{index} or die
3370 "Couldn't unlink index: $gs->{index}: $!\n";
3372 my $pool = SVN::Pool->new;
3373 $editor->set_path_strip($path);
3374 my (@pc) = split m#/#, $path;
3375 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3377 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3379 # Since we can't rely on svn_ra_reparent being available, we'll
3380 # just have to do some magic with set_path to make it so
3381 # we only want a partial path.
3383 my $final = join('/', @pc);
3385 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3386 $sp .= '/' if length $sp;
3389 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3391 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3393 $reporter->finish_report($pool);
3395 $editor->{git_commit_ok};
3398 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3399 # svn_ra_reparent didn't work before 1.4)
3401 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3402 my $path = $gs->{path};
3403 my $pool = SVN::Pool->new;
3405 my $full_url = $self->{url};
3406 my $old_url = $full_url;
3407 $full_url .= '/' . escape_uri_only($path) if length $path;
3408 my ($ra, $reparented);
3409 if ($old_url ne $full_url) {
3410 if ($old_url !~ m#^svn(\+ssh)?://#) {
3411 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3413 $self->{url} = $full_url;
3419 $ra = Git::SVN::Ra->new($full_url);
3424 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3425 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3426 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3427 $reporter->finish_report($pool);
3430 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3431 $self->{url} = $old_url;
3435 $editor->{git_commit_ok};
3438 sub longest_common_path {
3439 my ($gsv, $globs) = @_;
3441 my $common_max = scalar @$gsv;
3443 foreach my $gs (@$gsv) {
3444 my @tmp = split m#/#, $gs->{path};
3447 $p .= length($p) ? "/$_" : $_;
3453 $common_max += scalar @$globs;
3454 foreach my $glob (@$globs) {
3455 my @tmp = split m#/#, $glob->{path}->{left};
3458 $p .= length($p) ? "/$_" : $_;
3464 my $longest_path = '';
3465 foreach (sort {length $b <=> length $a} keys %common) {
3466 if ($common{$_} == $common_max) {
3474 sub gs_fetch_loop_common {
3475 my ($self, $base, $head, $gsv, $globs) = @_;
3476 return if ($base > $head);
3477 my $inc = $_log_window_size;
3478 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3479 my $longest_path = longest_common_path($gsv, $globs);
3480 my $ra_url = $self->{url};
3484 my $err_handler = $SVN::Error::handler;
3485 $SVN::Error::handler = sub {
3487 skip_unknown_revs($err);
3490 my ($paths, $r, $author, $date, $log) = @_;
3491 [ dup_changed_paths($paths),
3492 { author => $author, date => $date, log => $log } ];
3494 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3495 sub { $revs{$_[1]} = _cb(@_) });
3496 if ($err && $max >= $head) {
3497 print STDERR "Path '$longest_path' ",
3498 "was probably deleted:\n",
3499 $err->expanded_message,
3500 "\nWill attempt to follow ",
3501 "revisions r$min .. r$max ",
3502 "committed before the deletion\n";
3504 while (--$hi >= $min) {
3506 $self->get_log([$longest_path], $min, $hi,
3509 $revs{$_[1]} = _cb(@_) });
3511 print STDERR "r$min .. r$ok OK\n";
3516 $SVN::Error::handler = $err_handler;
3518 my %exists = map { $_->{path} => $_ } @$gsv;
3519 foreach my $r (sort {$a <=> $b} keys %revs) {
3520 my ($paths, $logged) = @{$revs{$r}};
3522 foreach my $gs ($self->match_globs(\%exists, $paths,
3524 if ($gs->rev_db_max >= $r) {
3527 next unless $gs->match_paths($paths, $r);
3528 $gs->{logged_rev_props} = $logged;
3529 if (my $last_commit = $gs->last_commit) {
3530 $gs->assert_index_clean($last_commit);
3532 my $log_entry = $gs->do_fetch($paths, $r);
3534 $gs->do_git_commit($log_entry);
3537 foreach my $g (@$globs) {
3538 my $k = "svn-remote.$g->{remote}." .
3540 Git::SVN::tmp_config($k, $r);
3546 $self = Git::SVN::Ra->new($ra_url);
3547 $ra_invalid = undef;
3550 # pre-fill the .rev_db since it'll eventually get filled in
3551 # with '0' x40 if something new gets committed
3552 foreach my $gs (@$gsv) {
3553 next if defined $gs->rev_db_get($max);
3554 $gs->rev_db_set($max, 0 x40);
3556 foreach my $g (@$globs) {
3557 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3558 Git::SVN::tmp_config($k, $max);
3560 last if $max >= $head;
3563 $max = $head if ($max > $head);
3568 my ($self, $exists, $paths, $globs, $r) = @_;
3571 my ($self, $exists, $g, $r) = @_;
3572 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3573 return unless scalar @x == 3;
3574 my $dirents = $x[0];
3575 foreach my $de (keys %$dirents) {
3576 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3577 my $p = $g->{path}->full_path($de);
3578 next if $exists->{$p};
3579 next if (length $g->{path}->{right} &&
3580 ($self->check_path($p, $r) !=
3582 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3583 $g->{ref}->full_path($de), 1);
3586 foreach my $g (@$globs) {
3587 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3588 if ($path->{action} =~ /^[AR]$/) {
3589 get_dir_check($self, $exists, $g, $r);
3592 foreach (keys %$paths) {
3593 if (/$g->{path}->{left_regex}/ &&
3594 !/$g->{path}->{regex}/) {
3595 next if $paths->{$_}->{action} !~ /^[AR]$/;
3596 get_dir_check($self, $exists, $g, $r);
3598 next unless /$g->{path}->{regex}/;
3600 my $pathname = $g->{path}->full_path($p);
3601 next if $exists->{$pathname};
3602 next if ($self->check_path($pathname, $r) !=
3604 $exists->{$pathname} = Git::SVN->init(
3605 $self->{url}, $pathname, undef,
3606 $g->{ref}->full_path($p), 1);
3609 foreach (split m#/#, $g->{path}->{left}) {
3611 next unless ($paths->{$c} &&
3612 ($paths->{$c}->{action} =~ /^[AR]$/));
3613 get_dir_check($self, $exists, $g, $r);
3621 return $self->{url} if ($self->{url} eq $self->{repos_root});
3622 my $url = $self->{repos_root};
3623 my @components = split(m!/!, $self->{svn_path});
3626 $url .= "/$c" if length $c;
3627 eval { (ref $self)->new($url)->get_latest_revnum };
3628 } while ($@ && ($c = shift @components));
3634 unless (defined $can_do_switch) {
3635 my $pool = SVN::Pool->new;
3637 $self->do_switch(1, '', 0, $self->{url},
3638 SVN::Delta::Editor->new, $pool);
3643 $rep->abort_report($pool);
3651 sub skip_unknown_revs {
3653 my $errno = $err->apr_err();
3654 # Maybe the branch we're tracking didn't
3655 # exist when the repo started, so it's
3656 # not an error if it doesn't, just continue
3658 # Wonderfully consistent library, eh?
3659 # 160013 - svn:// and file://
3660 # 175002 - http(s)://
3661 # 175007 - http(s):// (this repo required authorization, too...)
3662 # More codes may be discovered later...
3663 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3664 my $err_key = $err->expanded_message;
3665 # revision numbers change every time, filter them out
3666 $err_key =~ s/\d+/\0/g;
3667 $err_key = "$errno\0$err_key";
3668 unless ($ignored_err{$err_key}) {
3669 warn "W: Ignoring error from SVN, path probably ",
3670 "does not exist: ($errno): ",
3671 $err->expanded_message,"\n";
3672 $ignored_err{$err_key} = 1;
3676 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3679 # svn_log_changed_path_t objects passed to get_log are likely to be
3680 # overwritten even if only the refs are copied to an external variable,
3681 # so we should dup the structures in their entirety. Using an externally
3682 # passed pool (instead of our temporary and quickly cleared pool in
3683 # Git::SVN::Ra) does not help matters at all...
3684 sub dup_changed_paths {
3686 return undef unless $paths;
3688 foreach my $p (keys %$paths) {
3689 my $i = $paths->{$p};
3690 my %s = map { $_ => $i->$_ }
3691 qw/copyfrom_path copyfrom_rev action/;
3697 package Git::SVN::Log;
3700 use POSIX qw/strftime/;
3701 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3702 %rusers $show_commit $incremental/;
3707 return 1 if defined $c->{r};
3709 # big commit message got truncated by the 16k pretty buffer in rev-list
3710 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3711 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3713 my @log = command(qw/cat-file commit/, $c->{c});
3715 # shift off the headers
3716 shift @log while ($log[0] ne '');
3719 # TODO: make $c->{l} not have a trailing newline in the future
3720 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3722 (undef, $c->{r}, undef) = ::extract_metadata(
3723 (grep(/^git-svn-id: /, @log))[-1]);
3725 return defined $c->{r};
3731 $dcvar = 'color.diff';
3732 $dc = `git-config --get $dcvar`;
3734 # nothing at all; fallback to "diff.color"
3735 $dcvar = 'diff.color';
3736 $dc = `git-config --get $dcvar`;
3739 if ($dc eq 'auto') {
3741 $pc = `git-config --get color.pager`;
3743 # does not have it -- fallback to pager.color
3744 $pc = `git-config --bool --get pager.color`;
3747 $pc = `git-config --bool --get color.pager`;
3753 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3754 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3758 return 0 if $dc eq 'never';
3759 return 1 if $dc eq 'always';
3760 chomp($dc = `git-config --bool --get $dcvar`);
3761 return ($dc eq 'true');
3764 sub git_svn_log_cmd {
3765 my ($r_min, $r_max, @args) = @_;
3767 my (@files, @log_opts);
3768 foreach my $x (@args) {
3769 if ($x eq '--' || @files) {
3772 if (::verify_ref("$x^0")) {
3780 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3781 $gs ||= Git::SVN->_new;
3782 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3784 push @cmd, '-r' unless $non_recursive;
3785 push @cmd, qw/--raw --name-status/ if $verbose;
3786 push @cmd, '--color' if log_use_color();
3787 push @cmd, @log_opts;
3788 if (defined $r_max && $r_max == $r_min) {
3789 push @cmd, '--max-count=1';
3790 if (my $c = $gs->rev_db_get($r_max)) {
3793 } elsif (defined $r_max) {
3794 my ($c_min, $c_max);
3795 $c_max = $gs->rev_db_get($r_max);
3796 $c_min = $gs->rev_db_get($r_min);
3797 if (defined $c_min && defined $c_max) {
3798 if ($r_max > $r_max) {
3799 push @cmd, "$c_min..$c_max";
3801 push @cmd, "$c_max..$c_min";
3803 } elsif ($r_max > $r_min) {
3809 return (@cmd, @files);
3812 # adapted from pager.c
3814 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3815 if (!defined $pager) {
3817 } elsif (length $pager == 0 || $pager eq 'cat') {
3823 return unless -t *STDOUT && defined $pager;
3824 pipe my $rfd, my $wfd or return;
3825 defined(my $pid = fork) or ::fatal "Can't fork: $!";
3827 open STDOUT, '>&', $wfd or
3828 ::fatal "Can't redirect to stdout: $!";
3831 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
3832 $ENV{LESS} ||= 'FRSX';
3833 exec $pager or ::fatal "Can't run pager: $! ($pager)";
3836 sub tz_to_s_offset {
3839 return ($1 * 60) + ($tz * 3600);
3842 sub get_author_info {
3843 my ($dest, $author, $t, $tz) = @_;
3844 $author =~ s/(?:^\s*|\s*$)//g;
3845 $dest->{a_raw} = $author;
3848 $au = $rusers{$author} || undef;
3851 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3856 # Date::Parse isn't in the standard Perl distro :(
3857 if ($tz =~ s/^\+//) {
3858 $t += tz_to_s_offset($tz);
3859 } elsif ($tz =~ s/^\-//) {
3860 $t -= tz_to_s_offset($tz);
3862 $dest->{t_utc} = $t;
3865 sub process_commit {
3866 my ($c, $r_min, $r_max, $defer) = @_;
3867 if (defined $r_min && defined $r_max) {
3868 if ($r_min == $c->{r} && $r_min == $r_max) {
3872 return 1 if $r_min == $r_max;
3873 if ($r_min < $r_max) {
3874 # we need to reverse the print order
3875 return 0 if (defined $limit && --$limit < 0);
3879 if ($r_min != $r_max) {
3880 return 1 if ($r_min < $c->{r});
3881 return 1 if ($r_max > $c->{r});
3884 return 0 if (defined $limit && --$limit < 0);
3893 if (my $l = $c->{l}) {
3894 while ($l->[0] =~ /^\s*$/) { shift @$l }
3897 $l_fmt ||= 'A' . length($c->{r});
3898 print 'r',pack($l_fmt, $c->{r}),' | ';
3899 print "$c->{c} | " if $show_commit;
3902 show_commit_normal($c);
3906 sub show_commit_changed_paths {
3908 return unless $c->{changed};
3909 print "Changed paths:\n", @{$c->{changed}};
3912 sub show_commit_normal {
3914 print '-' x72, "\nr$c->{r} | ";
3915 print "$c->{c} | " if $show_commit;
3916 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3917 localtime($c->{t_utc})), ' | ';
3920 if (my $l = $c->{l}) {
3921 while ($l->[$#$l] eq "\n" && $#$l > 0
3922 && $l->[($#$l - 1)] eq "\n") {
3925 $nr_line = scalar @$l;
3927 print "1 line\n\n\n";
3929 if ($nr_line == 1) {
3930 $nr_line = '1 line';
3932 $nr_line .= ' lines';
3934 print $nr_line, "\n";
3935 show_commit_changed_paths($c);
3937 print $_ foreach @$l;
3941 show_commit_changed_paths($c);
3945 foreach my $x (qw/raw stat diff/) {
3948 print $_ foreach @{$c->{$x}}
3955 my ($r_min, $r_max);
3956 my $r_last = -1; # prevent dupes
3962 if (defined $::_revision) {
3963 if ($::_revision =~ /^(\d+):(\d+)$/) {
3964 ($r_min, $r_max) = ($1, $2);
3965 } elsif ($::_revision =~ /^\d+$/) {
3966 $r_min = $r_max = $::_revision;
3968 ::fatal "-r$::_revision is not supported, use ",
3969 "standard 'git log' arguments instead";
3974 @args = git_svn_log_cmd($r_min, $r_max, @args);
3975 my $log = command_output_pipe(@args);
3977 my (@k, $c, $d, $stat);
3978 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3980 if (/^${esc_color}commit ($::sha1_short)/o) {
3982 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3984 process_commit($c, $r_min, $r_max, \@k) or
3989 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3990 get_author_info($c, $1, $2, $3);
3991 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3993 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3994 push @{$c->{raw}}, $_;
3995 } elsif (/^${esc_color}[ACRMDT]\t/) {
3996 # we could add $SVN->{svn_path} here, but that requires
3997 # remote access at the moment (repo_path_split)...
3998 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3999 push @{$c->{changed}}, $_;
4000 } elsif (/^${esc_color}diff /o) {
4002 push @{$c->{diff}}, $_;
4004 push @{$c->{diff}}, $_;
4005 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4006 $esc_color*[\+\-]*$esc_color$/x) {
4008 push @{$c->{stat}}, $_;
4009 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4010 push @{$c->{stat}}, $_;
4012 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4013 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4014 } elsif (s/^${esc_color} //o) {
4015 push @{$c->{l}}, $_;
4018 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4020 process_commit($c, $r_min, $r_max, \@k);
4026 process_commit($_, $r_min, $r_max) foreach reverse @k;
4030 print '-' x72,"\n" unless $incremental || $oneline;
4033 package Git::SVN::Migration;
4034 # these version numbers do NOT correspond to actual version numbers
4035 # of git nor git-svn. They are just relative.
4037 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4039 # v1 layout: .git/$id/info/url, refs/remotes/$id
4041 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4043 # v3 layout: .git/svn/$id, refs/remotes/$id
4044 # - info/url may remain for backwards compatibility
4045 # - this is what we migrate up to this layout automatically,
4046 # - this will be used by git svn init on single branches
4047 # v3.1 layout (auto migrated):
4048 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4049 # for backwards compatibility
4051 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4052 # - this is only created for newly multi-init-ed
4053 # repositories. Similar in spirit to the
4054 # --use-separate-remotes option in git-clone (now default)
4055 # - we do not automatically migrate to this (following
4056 # the example set by core git)
4060 use File::Path qw/mkpath/;
4061 use File::Basename qw/dirname basename/;
4062 use vars qw/$_minimize/;
4064 sub migrate_from_v0 {
4065 my $git_dir = $ENV{GIT_DIR};
4066 return undef unless -d $git_dir;
4067 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4071 my ($id, $orig_ref) = ($_, $_);
4072 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4073 next unless -f "$git_dir/$id/info/url";
4074 my $new_ref = "refs/remotes/$id";
4075 if (::verify_ref("$new_ref^0")) {
4076 print STDERR "W: $orig_ref is probably an old ",
4077 "branch used by an ancient version of ",
4079 "However, $new_ref also exists.\n",
4080 "We will not be able ",
4081 "to use this branch until this ",
4082 "ambiguity is resolved.\n";
4085 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4086 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4087 command_noisy('update-ref', $new_ref, $orig_ref);
4088 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4091 command_close_pipe($fh, $ctx);
4092 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4096 sub migrate_from_v1 {
4097 my $git_dir = $ENV{GIT_DIR};
4099 return $migrated unless -d $git_dir;
4100 my $svn_dir = "$git_dir/svn";
4102 # just in case somebody used 'svn' as their $id at some point...
4103 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4105 print STDERR "Migrating from a git-svn v1 layout...\n";
4107 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4108 "$svn_dir\n\t(required for this version ",
4109 "($::VERSION) of git-svn) does not. exist\n";
4110 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4113 next unless $x =~ s#^refs/remotes/##;
4115 next unless -f "$git_dir/$x/info/url";
4116 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4118 my $dn = dirname("$git_dir/svn/$x");
4119 mkpath([$dn]) unless -d $dn;
4120 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4121 mkpath(["$git_dir/svn/svn"]);
4122 print STDERR " - $git_dir/$x/info => ",
4123 "$git_dir/svn/$x/info\n";
4124 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4126 # don't worry too much about these, they probably
4127 # don't exist with repos this old (save for index,
4128 # and we can easily regenerate that)
4129 foreach my $f (qw/unhandled.log index .rev_db/) {
4130 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4133 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4134 rename "$git_dir/$x", "$git_dir/svn/$x" or
4139 command_close_pipe($fh, $ctx);
4140 print STDERR "Done migrating from a git-svn v1 layout\n";
4145 my ($l_map, $pfx, $path) = @_;
4147 foreach (<$path/*>) {
4148 if (-r "$_/info/url") {
4149 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4150 my $ref_id = $pfx . basename $_;
4151 my $url = ::file_to_s("$_/info/url");
4152 $l_map->{$ref_id} = $url;
4159 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4160 read_old_urls($l_map, $x, $_);
4164 sub migrate_from_v2 {
4165 my @cfg = command(qw/config -l/);
4166 return if grep /^svn-remote\..+\.url=/, @cfg;
4168 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4171 foreach my $ref_id (sort keys %l_map) {
4172 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4174 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4181 sub minimize_connections {
4182 my $r = Git::SVN::read_all_remotes();
4184 my $root_repos = {};
4185 foreach my $repo_id (keys %$r) {
4186 my $url = $r->{$repo_id}->{url} or next;
4187 my $fetch = $r->{$repo_id}->{fetch} or next;
4188 my $ra = Git::SVN::Ra->new($url);
4190 # skip existing cases where we already connect to the root
4191 if (($ra->{url} eq $ra->{repos_root}) ||
4192 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4194 $root_repos->{$ra->{url}} = $repo_id;
4198 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4199 my $root_path = $ra->{url};
4200 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4201 foreach my $path (keys %$fetch) {
4202 my $ref_id = $fetch->{$path};
4203 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4205 # make sure we can read when connecting to
4206 # a higher level of a repository
4207 my ($last_rev, undef) = $gs->last_rev_commit;
4208 if (!defined $last_rev) {
4210 $root_ra->get_latest_revnum;
4214 my $new = $root_path;
4215 $new .= length $path ? "/$path" : '';
4217 $root_ra->get_log([$new], $last_rev, $last_rev,
4221 $new_urls->{$ra->{repos_root}}->{$new} =
4222 { ref_id => $ref_id,
4223 old_repo_id => $repo_id,
4224 old_path => $path };
4229 foreach my $url (keys %$new_urls) {
4230 # see if we can re-use an existing [svn-remote "repo_id"]
4231 # instead of creating a(n ugly) new section:
4232 my $repo_id = $root_repos->{$url} ||
4233 Git::SVN::sanitize_remote_name($url);
4235 my $fetch = $new_urls->{$url};
4236 foreach my $path (keys %$fetch) {
4237 my $x = $fetch->{$path};
4238 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4239 my $pfx = "svn-remote.$x->{old_repo_id}";
4241 my $old_fetch = quotemeta("$x->{old_path}:".
4242 "refs/remotes/$x->{ref_id}");
4243 command_noisy(qw/config --unset/,
4244 "$pfx.fetch", '^'. $old_fetch . '$');
4245 delete $r->{$x->{old_repo_id}}->
4246 {fetch}->{$x->{old_path}};
4247 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4248 command_noisy(qw/config --unset/,
4250 push @emptied, $x->{old_repo_id}
4255 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4256 "$ENV{GIT_DIR}/config";
4258 The following [svn-remote] sections in your config file ($file) are empty
4259 and can be safely removed:
4261 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4265 sub migration_check {
4269 minimize_connections() if $_minimize;
4272 package Git::IndexInfo;
4275 use Git qw/command_input_pipe command_close_pipe/;
4279 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4280 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4284 my ($self, $path) = @_;
4285 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4286 return ++$self->{nr};
4292 my ($self, $mode, $hash, $path) = @_;
4293 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4294 return ++$self->{nr};
4301 command_close_pipe($self->{gui}, $self->{ctx});
4304 package Git::SVN::GlobSpec;
4309 my ($class, $glob) = @_;
4311 $re =~ s!/+$!!g; # no need for trailing slashes
4312 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4313 my ($left, $right) = ($1, $2);
4315 die "Only one '*' wildcard expansion ",
4316 "is supported (got $nr): '$glob'\n";
4317 } elsif ($nr == 0) {
4318 die "One '*' is needed for glob: '$glob'\n";
4320 $re = quotemeta($left) . $re . quotemeta($right);
4321 if (length $left && !($left =~ s!/+$!!g)) {
4322 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4324 if (length $right && !($right =~ s!^/+!!g)) {
4325 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4327 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4328 bless { left => $left, right => $right, left_regex => $left_re,
4329 regex => qr/$re/, glob => $glob }, $class;
4333 my ($self, $path) = @_;
4334 return (length $self->{left} ? "$self->{left}/" : '') .
4335 $path . (length $self->{right} ? "/$self->{right}" : '');
4343 $remotes = { # returned by read_all_remotes()
4345 # svn-remote.svn.url=https://svn.musicpd.org
4346 url => 'https://svn.musicpd.org',
4347 # svn-remote.svn.fetch=mpd/trunk:trunk
4349 'mpd/trunk' => 'trunk',
4351 # svn-remote.svn.tags=mpd/tags/*:tags/*
4356 regex => qr!mpd/tags/([^/]+)$!,
4362 regex => qr!tags/([^/]+)$!,
4369 $log_entry hashref as returned by libsvn_log_entry()
4371 log => 'whitespace-formatted log entry
4372 ', # trailing newline is preserved
4373 revision => '8', # integer
4374 date => '2004-02-24T17:01:44.108345Z', # commit date
4375 author => 'committer name'
4379 # this is generated by generate_diff();
4380 @mods = array of diff-index line hashes, each element represents one line
4381 of diff-index output
4383 diff-index line ($m hash)
4385 mode_a => first column of diff-index output, no leading ':',
4386 mode_b => second column of diff-index output,
4387 sha1_b => sha1sum of the final blob,
4388 chg => change type [MCRADT],
4389 file_a => original file name of a file (iff chg is 'C' or 'R')
4390 file_b => new/current file name of a file (any chg)
4394 # retval of read_url_paths{,_all}();
4396 # repository root url
4397 'https://svn.musicpd.org' => {
4398 # repository path # GIT_SVN_ID
4399 'mpd/trunk' => 'trunk',
4400 'mpd/tags/0.11.5' => 'tags/0.11.5',
4405 I don't trust the each() function on unless I created %hash myself
4406 because the internal iterator may not have started at base.