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 $_repository
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';
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
47 # import functions from Git into our packages, en masse
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe
51 command_bidi_pipe command_close_bidi_pipe/) {
52 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
53 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 *{"${package}::$_"} = \&{"Git::$_"};
62 $sha1 = qr/[a-f\d]{40}/;
63 $sha1_short = qr/[a-f\d]{4,40}/;
64 my ($_stdin, $_help, $_edit,
67 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
68 $_merge, $_strategy, $_dry_run, $_local,
69 $_prefix, $_no_checkout, $_url, $_verbose,
70 $_git_format, $_commit_url, $_tag);
71 $Git::SVN::_follow_parent = 1;
73 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
74 'config-dir=s' => \$Git::SVN::Ra::config_dir,
75 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
76 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
77 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
78 'authors-file|A=s' => \$_authors,
79 'repack:i' => \$Git::SVN::_repack,
80 'noMetadata' => \$Git::SVN::_no_metadata,
81 'useSvmProps' => \$Git::SVN::_use_svm_props,
82 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
83 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
84 'no-checkout' => \$_no_checkout,
86 'repack-flags|repack-args|repack-opts=s' =>
87 \$Git::SVN::_repack_flags,
88 'use-log-author' => \$Git::SVN::_use_log_author,
89 'add-author-from' => \$Git::SVN::_add_author_from,
90 'localtime' => \$Git::SVN::_localtime,
93 my ($_trunk, $_tags, $_branches, $_stdlayout);
95 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
96 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
97 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
98 'stdlayout|s' => \$_stdlayout,
99 'minimize-url|m' => \$Git::SVN::_minimize_url,
100 'no-metadata' => sub { $icv{noMetadata} = 1 },
101 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
102 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
103 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
105 my %cmt_opts = ( 'edit|e' => \$_edit,
106 'rmdir' => \$SVN::Git::Editor::_rmdir,
107 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
108 'l=i' => \$SVN::Git::Editor::_rename_limit,
109 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
113 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
114 { 'revision|r=s' => \$_revision,
115 'fetch-all|all' => \$_fetch_all,
116 'parent|p' => \$_fetch_parent,
118 clone => [ \&cmd_clone, "Initialize and fetch revisions",
119 { 'revision|r=s' => \$_revision,
120 %fc_opts, %init_opts } ],
121 init => [ \&cmd_init, "Initialize a repo for tracking" .
122 " (requires URL argument)",
124 'multi-init' => [ \&cmd_multi_init,
125 "Deprecated alias for ".
126 "'$0 init -T<trunk> -b<branches> -t<tags>'",
128 dcommit => [ \&cmd_dcommit,
129 'Commit several diffs to merge with upstream',
130 { 'merge|m|M' => \$_merge,
131 'strategy|s=s' => \$_strategy,
132 'verbose|v' => \$_verbose,
133 'dry-run|n' => \$_dry_run,
134 'fetch-all|all' => \$_fetch_all,
135 'commit-url=s' => \$_commit_url,
136 'revision|r=i' => \$_revision,
137 'no-rebase' => \$_no_rebase,
138 %cmt_opts, %fc_opts } ],
139 branch => [ \&cmd_branch,
140 'Create a branch in the SVN repository',
141 { 'message|m=s' => \$_message,
142 'dry-run|n' => \$_dry_run,
143 'tag|t' => \$_tag } ],
144 tag => [ sub { $_tag = 1; cmd_branch(@_) },
145 'Create a tag in the SVN repository',
146 { 'message|m=s' => \$_message,
147 'dry-run|n' => \$_dry_run } ],
148 'set-tree' => [ \&cmd_set_tree,
149 "Set an SVN repository to a git tree-ish",
150 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
151 'create-ignore' => [ \&cmd_create_ignore,
152 'Create a .gitignore per svn:ignore',
153 { 'revision|r=i' => \$_revision
155 'propget' => [ \&cmd_propget,
156 'Print the value of a property on a file or directory',
157 { 'revision|r=i' => \$_revision } ],
158 'proplist' => [ \&cmd_proplist,
159 'List all properties of a file or directory',
160 { 'revision|r=i' => \$_revision } ],
161 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
162 { 'revision|r=i' => \$_revision
164 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
165 { 'revision|r=i' => \$_revision
167 'multi-fetch' => [ \&cmd_multi_fetch,
168 "Deprecated alias for $0 fetch --all",
169 { 'revision|r=s' => \$_revision, %fc_opts } ],
170 'migrate' => [ sub { },
171 # no-op, we automatically run this anyways,
172 'Migrate configuration/metadata/layout from
173 previous versions of git-svn',
174 { 'minimize' => \$Git::SVN::Migration::_minimize,
176 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
177 { 'limit=i' => \$Git::SVN::Log::limit,
178 'revision|r=s' => \$_revision,
179 'verbose|v' => \$Git::SVN::Log::verbose,
180 'incremental' => \$Git::SVN::Log::incremental,
181 'oneline' => \$Git::SVN::Log::oneline,
182 'show-commit' => \$Git::SVN::Log::show_commit,
183 'non-recursive' => \$Git::SVN::Log::non_recursive,
184 'authors-file|A=s' => \$_authors,
185 'color' => \$Git::SVN::Log::color,
186 'pager=s' => \$Git::SVN::Log::pager
188 'find-rev' => [ \&cmd_find_rev,
189 "Translate between SVN revision numbers and tree-ish",
191 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
192 { 'merge|m|M' => \$_merge,
193 'verbose|v' => \$_verbose,
194 'strategy|s=s' => \$_strategy,
195 'local|l' => \$_local,
196 'fetch-all|all' => \$_fetch_all,
197 'dry-run|n' => \$_dry_run,
199 'commit-diff' => [ \&cmd_commit_diff,
200 'Commit a diff between two trees',
201 { 'message|m=s' => \$_message,
202 'file|F=s' => \$_file,
203 'revision|r=s' => \$_revision,
205 'info' => [ \&cmd_info,
206 "Show info about the latest SVN revision
207 on the current branch",
208 { 'url' => \$_url, } ],
209 'blame' => [ \&Git::SVN::Log::cmd_blame,
210 "Show what revision and author last modified each line of a file",
211 { 'git-format' => \$_git_format } ],
215 for (my $i = 0; $i < @ARGV; $i++) {
216 if (defined $cmd{$ARGV[$i]}) {
223 # make sure we're always running at the top-level working directory
224 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
225 unless (-d $ENV{GIT_DIR}) {
226 if ($git_dir_user_set) {
227 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
228 "but it is not a directory\n";
230 my $git_dir = delete $ENV{GIT_DIR};
233 $cdup = command_oneline(qw/rev-parse --show-cdup/);
234 $git_dir = '.' unless ($cdup);
235 chomp $cdup if ($cdup);
236 $cdup = "." unless ($cdup && length $cdup);
237 } "Already at toplevel, but $git_dir not found\n";
238 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
239 unless (-d $git_dir) {
240 die "$git_dir still not found after going to ",
243 $ENV{GIT_DIR} = $git_dir;
245 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
248 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
250 read_repo_config(\%opts);
251 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
252 Getopt::Long::Configure('pass_through');
254 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
255 'minimize-connections' => \$Git::SVN::Migration::_minimize,
256 'id|i=s' => \$Git::SVN::default_ref_id,
257 'svn-remote|remote|R=s' => sub {
258 $Git::SVN::no_reuse_existing = 1;
259 $Git::SVN::default_repo_id = $_[1] });
260 exit 1 if (!$rv && $cmd && $cmd ne 'log');
263 version() if $_version;
264 usage(1) unless defined $cmd;
265 load_authors() if $_authors;
267 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
268 Git::SVN::Migration::migration_check();
270 Git::SVN::init_vars();
272 Git::SVN::verify_remotes_sanity();
273 $cmd{$cmd}->[0]->(@ARGV);
276 post_fetch_checkout();
279 ####################### primary functions ######################
281 my $exit = shift || 0;
282 my $fd = $exit ? \*STDERR : \*STDOUT;
284 git-svn - bidirectional operations between a single Subversion tree and git
285 Usage: git svn <command> [options] [arguments]\n
287 print $fd "Available commands:\n" unless $cmd;
289 foreach (sort keys %cmd) {
290 next if $cmd && $cmd ne $_;
291 next if /^multi-/; # don't show deprecated commands
292 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
293 foreach (sort keys %{$cmd{$_}->[2]}) {
294 # mixed-case options are for .git/config only
295 next if /[A-Z]/ && /^[a-z]+$/i;
296 # prints out arguments as they should be passed:
297 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
298 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
300 split /\|/,$_)," $x\n";
304 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
305 arbitrary identifier if you're tracking multiple SVN branches/repositories in
306 one git repository and want to keep them separate. See git-svn(1) for more
313 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
318 unless (-d $ENV{GIT_DIR}) {
319 my @init_db = ('init');
320 push @init_db, "--template=$_template" if defined $_template;
321 if (defined $_shared) {
322 if ($_shared =~ /[a-z]/) {
323 push @init_db, "--shared=$_shared";
325 push @init_db, "--shared";
328 command_noisy(@init_db);
329 $_repository = Git->repository(Repository => ".git");
331 command_noisy('config', 'core.autocrlf', 'false');
333 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
334 foreach my $i (keys %icv) {
335 die "'$set' and '$i' cannot both be set\n" if $set;
336 next unless defined $icv{$i};
337 command_noisy('config', "$pfx.$i", $icv{$i});
340 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
341 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
342 if defined $$ignore_regex;
346 my $repo_path = shift or return;
347 mkpath([$repo_path]) unless -d $repo_path;
348 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
349 $ENV{GIT_DIR} = '.git';
350 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
354 my ($url, $path) = @_;
355 if (!defined $path &&
356 (defined $_trunk || defined $_branches || defined $_tags ||
357 defined $_stdlayout) &&
358 $url !~ m#^[a-z\+]+://#) {
361 $path = basename($url) if !defined $path || !length $path;
362 cmd_init($url, $path);
363 Git::SVN::fetch_all($Git::SVN::default_repo_id);
364 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
368 if (defined $_stdlayout) {
369 $_trunk = 'trunk' if (!defined $_trunk);
370 $_tags = 'tags' if (!defined $_tags);
371 $_branches = 'branches' if (!defined $_branches);
373 if (defined $_trunk || defined $_branches || defined $_tags) {
374 return cmd_multi_init(@_);
376 my $url = shift or die "SVN repository location required ",
377 "as a command-line argument\n";
381 Git::SVN->init($url);
385 if (grep /^\d+=./, @_) {
386 die "'<rev>=<commit>' fetch arguments are ",
387 "no longer supported.\n";
391 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
393 if ($_fetch_parent) {
394 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
396 die "Unable to determine upstream SVN information from ",
397 "working tree history\n";
399 # just fetch, don't checkout.
400 $_no_checkout = 'true';
401 $_fetch_all ? $gs->fetch_all : $gs->fetch;
402 } elsif ($_fetch_all) {
405 $remote ||= $Git::SVN::default_repo_id;
406 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
412 if ($_stdin || !@commits) {
413 print "Reading from stdin...\n";
416 if (/\b($sha1_short)\b/o) {
417 unshift @commits, $1;
422 foreach my $c (@commits) {
423 my @tmp = command('rev-parse',$c);
424 if (scalar @tmp == 1) {
426 } elsif (scalar @tmp > 1) {
427 push @revs, reverse(command('rev-list',@tmp));
429 fatal "Failed to rev-parse $c";
432 my $gs = Git::SVN->new;
433 my ($r_last, $cmt_last) = $gs->last_rev_commit;
435 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
436 fatal "There are new revisions that were fetched ",
437 "and need to be merged (or acknowledged) ",
438 "before committing.\nlast rev: $r_last\n",
439 " current: $gs->{last_rev}";
441 $gs->set_tree($_) foreach @revs;
442 print "Done committing ",scalar @revs," revisions to SVN\n";
448 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
449 'Cannot dcommit with a dirty index. Commit your changes first, '
450 . "or stash them with `git stash'.\n";
453 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
455 die "Unable to determine upstream SVN information from ",
456 "$head history.\nPerhaps the repository is empty.";
459 if (defined $_commit_url) {
462 $url = eval { command_oneline('config', '--get',
463 "svn-remote.$gs->{repo_id}.commiturl") };
469 my $last_rev = $_revision if defined $_revision;
471 print "Committing to $url ...\n";
473 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
474 if ($_no_rebase && scalar(@$linear_refs) > 1) {
475 warn "Attempting to commit more than one change while ",
476 "--no-rebase is enabled.\n",
477 "If these changes depend on each other, re-running ",
478 "without --no-rebase may be required."
480 my $expect_url = $url;
481 Git::SVN::remove_username($expect_url);
483 my $d = shift @$linear_refs or last;
484 unless (defined $last_rev) {
485 (undef, $last_rev, undef) = cmt_metadata("$d~1");
486 unless (defined $last_rev) {
487 fatal "Unable to extract revision information ",
492 print "diff-tree $d~1 $d\n";
495 my %ed_opts = ( r => $last_rev,
496 log => get_commit_entry($d)->{log},
497 ra => Git::SVN::Ra->new($url),
498 config => SVN::Core::config_get_config(
499 $Git::SVN::Ra::config_dir
504 print "Committed r$_[0]\n";
508 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
509 print "No changes\n$d~1 == $d\n";
510 } elsif ($parents->{$d} && @{$parents->{$d}}) {
511 $gs->{inject_parents_dcommit}->{$cmt_rev} =
514 $_fetch_all ? $gs->fetch_all : $gs->fetch;
515 $last_rev = $cmt_rev;
518 # we always want to rebase against the current HEAD,
519 # not any head that was passed to us
520 my @diff = command('diff-tree', $d,
524 @finish = rebase_cmd();
525 print STDERR "W: $d and ", $gs->refname,
526 " differ, using @finish:\n",
527 join("\n", @diff), "\n";
529 print "No changes between current HEAD and ",
531 "\nResetting to the latest ",
533 @finish = qw/reset --mixed/;
535 command_noisy(@finish, $gs->refname);
538 my ($url_, $rev_, $uuid_, $gs_) =
539 working_head_info($head, \@refs);
540 my ($linear_refs_, $parents_) =
541 linearize_history($gs_, \@refs);
542 if (scalar(@$linear_refs) !=
543 scalar(@$linear_refs_)) {
544 fatal "# of revisions changed ",
546 join("\n", @$linear_refs),
548 join("\n", @$linear_refs_), "\n",
549 'If you are attempting to commit ',
550 "merges, try running:\n\t",
551 'git rebase --interactive',
552 '--preserve-merges ',
554 "\nBefore dcommitting";
556 if ($url_ ne $expect_url) {
557 fatal "URL mismatch after rebase: ",
558 "$url_ != $expect_url";
560 if ($uuid_ ne $uuid) {
561 fatal "uuid mismatch after rebase: ",
566 for ($i = 0; $i < scalar @$linear_refs; $i++) {
567 my $new = $linear_refs_->[$i] or next;
569 $parents->{$linear_refs->[$i]};
581 my ($branch_name, $head) = @_;
583 unless (defined $branch_name && length $branch_name) {
584 die(($_tag ? "tag" : "branch") . " name required\n");
588 my ($src, $rev, undef, $gs) = working_head_info($head);
590 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
591 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
592 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
593 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
595 my $ctx = SVN::Client->new(
596 auth => Git::SVN::Ra::_auth_providers(),
598 ${ $_[0] } = defined $_message
600 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
606 $ctx->ls($dst, 'HEAD', 0);
607 } and die "branch ${branch_name} already exists\n";
609 print "Copying ${src} at r${rev} to ${dst}...\n";
610 $ctx->copy($src, $rev, $dst)
617 my $revision_or_hash = shift or die "SVN or git revision required ",
618 "as a command-line argument\n";
620 if ($revision_or_hash =~ /^r\d+$/) {
624 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
626 die "Unable to determine upstream SVN information from ",
629 my $desired_revision = substr($revision_or_hash, 1);
630 $result = $gs->rev_map_get($desired_revision, $uuid);
632 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
635 print "$result\n" if $result;
639 command_noisy(qw/update-index --refresh/);
640 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
642 die "Unable to determine upstream SVN information from ",
643 "working tree history\n";
646 print "Remote Branch: " . $gs->refname . "\n";
647 print "SVN URL: " . $url . "\n";
650 if (command(qw/diff-index HEAD --/)) {
651 print STDERR "Cannot rebase with uncommited changes:\n";
652 command_noisy('status');
656 # rebase will checkout for us, so no need to do it explicitly
657 $_no_checkout = 'true';
658 $_fetch_all ? $gs->fetch_all : $gs->fetch;
660 command_noisy(rebase_cmd(), $gs->refname);
663 sub cmd_show_ignore {
664 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
665 $gs ||= Git::SVN->new;
666 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
667 $gs->prop_walk($gs->{path}, $r, sub {
668 my ($gs, $path, $props) = @_;
669 print STDOUT "\n# $path\n";
670 my $s = $props->{'svn:ignore'} or return;
671 $s =~ s/[\r\n]+/\n/g;
678 sub cmd_show_externals {
679 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
680 $gs ||= Git::SVN->new;
681 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
682 $gs->prop_walk($gs->{path}, $r, sub {
683 my ($gs, $path, $props) = @_;
684 print STDOUT "\n# $path\n";
685 my $s = $props->{'svn:externals'} or return;
686 $s =~ s/[\r\n]+/\n/g;
693 sub cmd_create_ignore {
694 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
695 $gs ||= Git::SVN->new;
696 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
697 $gs->prop_walk($gs->{path}, $r, sub {
698 my ($gs, $path, $props) = @_;
699 # $path is of the form /path/to/dir/
701 # SVN can have attributes on empty directories,
702 # which git won't track
703 mkpath([$path]) unless -d $path;
704 my $ignore = $path . '.gitignore';
705 my $s = $props->{'svn:ignore'} or return;
706 open(GITIGNORE, '>', $ignore)
707 or fatal("Failed to open `$ignore' for writing: $!");
708 $s =~ s/[\r\n]+/\n/g;
710 # Prefix all patterns so that the ignore doesn't apply
711 # to sub-directories.
713 print GITIGNORE "$s\n";
715 or fatal("Failed to close `$ignore': $!");
716 command_noisy('add', '-f', $ignore);
720 sub canonicalize_path {
722 my $dot_slash_added = 0;
723 if (substr($path, 0, 1) ne "/") {
724 $path = "./" . $path;
725 $dot_slash_added = 1;
727 # File::Spec->canonpath doesn't collapse x/../y into y (for a
728 # good reason), so let's do this manually.
730 $path =~ s#/\.(?:/|$)#/#g;
731 $path =~ s#/[^/]+/\.\.##g;
733 $path =~ s#^\./## if $dot_slash_added;
741 # Helper for cmd_propget and cmd_proplist below.
744 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
745 $gs ||= Git::SVN->new;
747 # prefix THE PATH by the sub-directory from which the user
749 $path = $cmd_dir_prefix . $path;
750 fatal("No such file or directory: $path") unless -e $path;
751 my $is_dir = -d $path ? 1 : 0;
752 $path = $gs->{path} . '/' . $path;
754 # canonicalize the path (otherwise libsvn will abort or fail to
756 $path = canonicalize_path($path);
758 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
761 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
764 (undef, $props) = $gs->ra->get_file($path, $r, undef);
769 # cmd_propget (PROP, PATH)
770 # ------------------------
771 # Print the SVN property PROP for PATH.
773 my ($prop, $path) = @_;
774 $path = '.' if not defined $path;
775 usage(1) if not defined $prop;
776 my $props = get_svnprops($path);
777 if (not defined $props->{$prop}) {
778 fatal("`$path' does not have a `$prop' SVN property.");
780 print $props->{$prop} . "\n";
783 # cmd_proplist (PATH)
784 # -------------------
785 # Print the list of SVN properties for PATH.
788 $path = '.' if not defined $path;
789 my $props = get_svnprops($path);
790 print "Properties on '$path':\n";
791 foreach (sort keys %{$props}) {
798 unless (defined $_trunk || defined $_branches || defined $_tags) {
802 # there are currently some bugs that prevent multi-init/multi-fetch
803 # setups from working well without this.
804 $Git::SVN::_minimize_url = 1;
806 $_prefix = '' unless defined $_prefix;
812 if (defined $_trunk) {
813 my $trunk_ref = $_prefix . 'trunk';
814 # try both old-style and new-style lookups:
815 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
817 my ($trunk_url, $trunk_path) =
818 complete_svn_url($url, $_trunk);
819 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
823 return unless defined $_branches || defined $_tags;
824 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
825 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
826 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
829 sub cmd_multi_fetch {
830 my $remotes = Git::SVN::read_all_remotes();
831 foreach my $repo_id (sort keys %$remotes) {
832 if ($remotes->{$repo_id}->{url}) {
833 Git::SVN::fetch_all($repo_id, $remotes);
838 # this command is special because it requires no metadata
839 sub cmd_commit_diff {
840 my ($ta, $tb, $url) = @_;
841 my $usage = "Usage: $0 commit-diff -r<revision> ".
842 "<tree-ish> <tree-ish> [<URL>]";
843 fatal($usage) if (!defined $ta || !defined $tb);
846 my $gs = eval { Git::SVN->new };
848 fatal("Needed URL or usable git-svn --id in ",
849 "the command-line\n", $usage);
852 $svn_path = $gs->{path};
854 unless (defined $_revision) {
855 fatal("-r|--revision is a required argument\n", $usage);
857 if (defined $_message && defined $_file) {
858 fatal("Both --message/-m and --file/-F specified ",
859 "for the commit message.\n",
860 "I have no idea what you mean");
862 if (defined $_file) {
863 $_message = file_to_s($_file);
865 $_message ||= get_commit_entry($tb)->{log};
867 my $ra ||= Git::SVN::Ra->new($url);
870 $r = $ra->get_latest_revnum;
871 } elsif ($r !~ /^\d+$/) {
872 die "revision argument: $r not understood by git-svn\n";
874 my %ed_opts = ( r => $r,
879 editor_cb => sub { print "Committed r$_[0]\n" },
880 svn_path => $svn_path );
881 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
882 print "No changes\n$ta == $tb\n";
886 sub escape_uri_only {
889 foreach (split m{/}, $uri) {
890 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
898 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
899 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
900 $url = "$scheme://$domain$uri";
906 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
907 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
909 die "Too many arguments specified\n";
912 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
914 if (!$file_type && !$diff_status) {
915 print STDERR "svn: '$path' is not under version control\n";
919 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
921 die "Unable to determine upstream SVN information from ",
922 "working tree history\n";
925 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
926 $path = "." if $path eq "";
928 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
931 print escape_url($full_url), "\n";
935 my $result = "Path: $path\n";
936 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
937 $result .= "URL: " . escape_url($full_url) . "\n";
940 my $repos_root = $gs->repos_root;
941 Git::SVN::remove_username($repos_root);
942 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
945 $result .= "Repository Root: (offline)\n";
947 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
948 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
949 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
951 $result .= "Node Kind: " .
952 ($file_type eq "dir" ? "directory" : "file") . "\n";
954 my $schedule = $diff_status eq "A"
956 : ($diff_status eq "D" ? "delete" : "normal");
957 $result .= "Schedule: $schedule\n";
959 if ($diff_status eq "A") {
964 my ($lc_author, $lc_rev, $lc_date_utc);
965 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
966 my $log = command_output_pipe(@args);
967 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
969 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
971 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
972 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
973 (undef, $lc_rev, undef) = ::extract_metadata($1);
978 Git::SVN::Log::set_local_timezone();
980 $result .= "Last Changed Author: $lc_author\n";
981 $result .= "Last Changed Rev: $lc_rev\n";
982 $result .= "Last Changed Date: " .
983 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
985 if ($file_type ne "dir") {
986 my $text_last_updated_date =
987 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
989 "Text Last Updated: " .
990 Git::SVN::Log::format_svn_date($text_last_updated_date) .
993 if ($diff_status eq "D") {
995 command_output_pipe(qw(cat-file blob), "HEAD:$path");
996 if ($file_type eq "link") {
997 my $file_name = <$fh>;
998 $checksum = md5sum("link $file_name");
1000 $checksum = md5sum($fh);
1002 command_close_pipe($fh, $ctx);
1003 } elsif ($file_type eq "link") {
1005 command(qw(cat-file blob), "HEAD:$path");
1007 md5sum("link " . $file_name);
1009 open FILE, "<", $path or die $!;
1010 $checksum = md5sum(\*FILE);
1011 close FILE or die $!;
1013 $result .= "Checksum: " . $checksum . "\n";
1016 print $result, "\n";
1019 ########################### utility functions #########################
1022 my @cmd = qw/rebase/;
1023 push @cmd, '-v' if $_verbose;
1024 push @cmd, qw/--merge/ if $_merge;
1025 push @cmd, "--strategy=$_strategy" if $_strategy;
1029 sub post_fetch_checkout {
1030 return if $_no_checkout;
1031 my $gs = $Git::SVN::_head or return;
1032 return if verify_ref('refs/heads/master^0');
1034 my $valid_head = verify_ref('HEAD^0');
1035 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1036 return if ($valid_head || !verify_ref('HEAD^0'));
1038 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1039 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1040 return if -f $index;
1042 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1043 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1044 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1045 print STDERR "Checked out HEAD:\n ",
1046 $gs->full_url, " r", $gs->last_rev, "\n";
1049 sub complete_svn_url {
1050 my ($url, $path) = @_;
1052 if ($path !~ m#^[a-z\+]+://#) {
1053 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1054 fatal("E: '$path' is not a complete URL ",
1055 "and a separate URL is not specified");
1057 return ($url, $path);
1062 sub complete_url_ls_init {
1063 my ($ra, $repo_path, $switch, $pfx) = @_;
1064 unless ($repo_path) {
1065 print STDERR "W: $switch not specified\n";
1068 $repo_path =~ s#/+$##;
1069 if ($repo_path =~ m#^[a-z\+]+://#) {
1070 $ra = Git::SVN::Ra->new($repo_path);
1073 $repo_path =~ s#^/+##;
1075 fatal("E: '$repo_path' is not a complete URL ",
1076 "and a separate URL is not specified");
1079 my $url = $ra->{url};
1080 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1081 my $k = "svn-remote.$gs->{repo_id}.url";
1082 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1083 if ($orig_url && ($orig_url ne $gs->{url})) {
1084 die "$k already set: $orig_url\n",
1085 "wanted to set to: $gs->{url}\n";
1087 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1088 my $remote_path = "$ra->{svn_path}/$repo_path";
1089 $remote_path =~ s#/+#/#g;
1090 $remote_path =~ s#^/##g;
1091 $remote_path .= "/*" if $remote_path !~ /\*/;
1092 my ($n) = ($switch =~ /^--(\w+)/);
1093 if (length $pfx && $pfx !~ m#/$#) {
1094 die "--prefix='$pfx' must have a trailing slash '/'\n";
1096 command_noisy('config',
1097 "svn-remote.$gs->{repo_id}.$n",
1098 "$remote_path:refs/remotes/$pfx*" .
1099 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1104 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1105 { STDERR => 0 }); };
1108 sub get_tree_from_treeish {
1110 # $treeish can be a symbolic ref, too:
1111 my $type = command_oneline(qw/cat-file -t/, $treeish);
1113 while ($type eq 'tag') {
1114 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1116 if ($type eq 'commit') {
1117 $expected = (grep /^tree /, command(qw/cat-file commit/,
1119 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1120 die "Unable to get tree from $treeish\n" unless $expected;
1121 } elsif ($type eq 'tree') {
1122 $expected = $treeish;
1124 die "$treeish is a $type, expected tree, tag or commit\n";
1129 sub get_commit_entry {
1130 my ($treeish) = shift;
1131 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1132 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1133 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1134 open my $log_fh, '>', $commit_editmsg or croak $!;
1136 my $type = command_oneline(qw/cat-file -t/, $treeish);
1137 if ($type eq 'commit' || $type eq 'tag') {
1138 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1146 $in_msg = 1 if (/^\s*$/);
1147 $author = $1 if (/^author (.*>)/);
1148 } elsif (/^git-svn-id: /) {
1149 # skip this for now, we regenerate the
1150 # correct one on re-fetch anyways
1151 # TODO: set *:merge properties or like...
1153 if (/^From:/ || /^Signed-off-by:/) {
1159 $msgbuf =~ s/\s+$//s;
1160 if ($Git::SVN::_add_author_from && defined($author)
1162 $msgbuf .= "\n\nFrom: $author";
1164 print $log_fh $msgbuf or croak $!;
1165 command_close_pipe($msg_fh, $ctx);
1167 close $log_fh or croak $!;
1169 if ($_edit || ($type eq 'tree')) {
1170 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1171 # TODO: strip out spaces, comments, like git-commit.sh
1172 system($editor, $commit_editmsg);
1174 rename $commit_editmsg, $commit_msg or croak $!;
1176 # SVN requires messages to be UTF-8 when entering the repo
1178 open $log_fh, '<', $commit_msg or croak $!;
1180 chomp($log_entry{log} = <$log_fh>);
1182 if (my $enc = Git::config('i18n.commitencoding')) {
1184 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1186 close $log_fh or croak $!;
1193 my ($str, $file, $mode) = @_;
1194 open my $fd,'>',$file or croak $!;
1195 print $fd $str,"\n" or croak $!;
1196 close $fd or croak $!;
1197 chmod ($mode &~ umask, $file) if (defined $mode);
1202 open my $fd,'<',$file or croak "$!: file: $file\n";
1205 close $fd or croak $!;
1210 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1212 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1213 my $log = $cmd eq 'log';
1214 while (<$authors>) {
1216 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1217 my ($user, $name, $email) = ($1, $2, $3);
1219 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1221 $users{$user} = [$name, $email];
1224 close $authors or croak $!;
1227 # convert GetOpt::Long specs for use by git-config
1228 sub read_repo_config {
1229 return unless -d $ENV{GIT_DIR};
1232 foreach my $o (keys %$opts) {
1233 # if we have mixedCase and a long option-only, then
1234 # it's a config-only variable that we don't need for
1236 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1237 my $v = $opts->{$o};
1238 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1240 my $arg = 'git config';
1241 $arg .= ' --int' if ($o =~ /[:=]i$/);
1242 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1243 if (ref $v eq 'ARRAY') {
1244 chomp(my @tmp = `$arg --get-all svn.$key`);
1247 chomp(my $tmp = `$arg --get svn.$key`);
1248 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1253 delete @$opts{@config_only} if @config_only;
1256 sub extract_metadata {
1257 my $id = shift or return (undef, undef, undef);
1258 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1260 if (!defined $rev || !$uuid || !$url) {
1261 # some of the original repositories I made had
1262 # identifiers like this:
1263 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1265 return ($url, $rev, $uuid);
1269 return extract_metadata((grep(/^git-svn-id: /,
1270 command(qw/cat-file commit/, shift)))[-1]);
1273 sub cmt_sha2rev_batch {
1275 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1278 foreach my $sha (@{$list}) {
1281 print $out $sha, "\n";
1283 while (my $line = <$in>) {
1284 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1287 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1291 } elsif ($line =~ /^(git-svn-id: )/) {
1292 my (undef, $rev, undef) =
1293 extract_metadata($line);
1297 $size -= length($line);
1298 last if ($size == 0);
1302 command_close_bidi_pipe($pid, $in, $out, $ctx);
1307 sub working_head_info {
1308 my ($head, $refs) = @_;
1309 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1310 my ($fh, $ctx) = command_output_pipe(@args, $head);
1314 if ( m{^commit ($::sha1)$} ) {
1315 unshift @$refs, $hash if $hash and $refs;
1319 next unless s{^\s*(git-svn-id:)}{$1};
1320 my ($url, $rev, $uuid) = extract_metadata($_);
1321 if (defined $url && defined $rev) {
1322 next if $max{$url} and $max{$url} < $rev;
1323 if (my $gs = Git::SVN->find_by_url($url)) {
1324 my $c = $gs->rev_map_get($rev, $uuid);
1325 if ($c && $c eq $hash) {
1326 close $fh; # break the pipe
1327 return ($url, $rev, $uuid, $gs);
1329 $max{$url} ||= $gs->rev_map_max;
1334 command_close_pipe($fh, $ctx);
1335 (undef, undef, undef, undef);
1338 sub read_commit_parents {
1339 my ($parents, $c) = @_;
1340 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1341 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1342 @{$parents->{$c}} = split(/ /, $p);
1345 sub linearize_history {
1346 my ($gs, $refs) = @_;
1348 foreach my $c (@$refs) {
1349 read_commit_parents(\%parents, $c);
1354 my $last_svn_commit = $gs->last_commit;
1355 foreach my $c (reverse @$refs) {
1356 next if $c eq $last_svn_commit;
1359 unshift @linear_refs, $c;
1362 # we only want the first parent to diff against for linear
1363 # history, we save the rest to inject when we finalize the
1365 my $fp_a = verify_ref("$c~1");
1366 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1367 if (!$fp_a || !$fp_b) {
1369 "has no parent commit, and therefore ",
1370 "nothing to diff against.\n",
1371 "You should be working from a repository ",
1372 "originally created by git-svn\n";
1374 if ($fp_a ne $fp_b) {
1375 die "$c~1 = $fp_a, however parsing commit $c ",
1376 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1379 foreach my $p (@{$parents{$c}}) {
1383 (\@linear_refs, \%parents);
1386 sub find_file_type_and_diff_status {
1388 return ('dir', '') if $path eq '';
1391 command_oneline(qw(diff --cached --name-status --), $path) || "";
1392 my $diff_status = (split(' ', $diff_output))[0] || "";
1394 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1396 return (undef, undef) if !$diff_status && !$ls_tree;
1398 if ($diff_status eq "A") {
1399 return ("link", $diff_status) if -l $path;
1400 return ("dir", $diff_status) if -d $path;
1401 return ("file", $diff_status);
1404 my $mode = (split(' ', $ls_tree))[0] || "";
1406 return ("link", $diff_status) if $mode eq "120000";
1407 return ("dir", $diff_status) if $mode eq "040000";
1408 return ("file", $diff_status);
1414 my $md5 = Digest::MD5->new();
1415 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1416 $md5->addfile($arg) or croak $!;
1417 } elsif ($ref eq 'SCALAR') {
1418 $md5->add($$arg) or croak $!;
1420 $md5->add($arg) or croak $!;
1422 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1424 return $md5->hexdigest();
1430 use Fcntl qw/:DEFAULT :seek/;
1431 use constant rev_map_fmt => 'NH40';
1432 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1433 $_repack $_repack_flags $_use_svm_props $_head
1434 $_use_svnsync_props $no_reuse_existing $_minimize_url
1435 $_use_log_author $_add_author_from $_localtime/;
1437 use File::Path qw/mkpath/;
1438 use File::Copy qw/copy/;
1441 my ($_gc_nr, $_gc_period);
1443 # properties that we do not log:
1446 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1447 svn:special svn:executable
1448 svn:entry:committed-rev
1449 svn:entry:last-author
1451 svn:entry:committed-date/;
1453 # some options are read globally, but can be overridden locally
1454 # per [svn-remote "..."] section. Command-line options will *NOT*
1455 # override options set in an [svn-remote "..."] section
1457 for my $option (qw/follow_parent no_metadata use_svm_props
1458 use_svnsync_props/) {
1461 my $prop = "-$option";
1464 return $self->{$prop} if exists $self->{$prop};
1465 my $k = "svn-remote.$self->{repo_id}.$key";
1466 eval { command_oneline(qw/config --get/, $k) };
1468 $self->{$prop} = ${"Git::SVN::_$option"};
1470 my $v = command_oneline(qw/config --bool/,$k);
1471 $self->{$prop} = $v eq 'false' ? 0 : 1;
1473 return $self->{$prop};
1479 my (%LOCKFILES, %INDEX_FILES);
1481 unlink keys %LOCKFILES if %LOCKFILES;
1482 unlink keys %INDEX_FILES if %INDEX_FILES;
1485 sub resolve_local_globs {
1486 my ($url, $fetch, $glob_spec) = @_;
1487 return unless defined $glob_spec;
1488 my $ref = $glob_spec->{ref};
1489 my $path = $glob_spec->{path};
1490 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1491 next unless m#^refs/remotes/$ref->{regex}$#;
1493 my $pathname = desanitize_refname($path->full_path($p));
1494 my $refname = desanitize_refname($ref->full_path($p));
1495 if (my $existing = $fetch->{$pathname}) {
1496 if ($existing ne $refname) {
1497 die "Refspec conflict:\n",
1498 "existing: refs/remotes/$existing\n",
1499 " globbed: refs/remotes/$refname\n";
1501 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1502 $u =~ s!^\Q$url\E(/|$)!! or die
1503 "refs/remotes/$refname: '$url' not found in '$u'\n";
1504 if ($pathname ne $u) {
1505 warn "W: Refspec glob conflict ",
1506 "(ref: refs/remotes/$refname):\n",
1507 "expected path: $pathname\n",
1509 "Continuing ahead with $u\n";
1513 $fetch->{$pathname} = $refname;
1518 sub parse_revision_argument {
1519 my ($base, $head) = @_;
1520 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1521 return ($base, $head);
1523 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1524 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1525 return ($head, $head) if ($::_revision eq 'HEAD');
1526 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1527 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1528 die "revision argument: $::_revision not understood by git-svn\n";
1532 my ($repo_id, $remotes) = @_;
1536 $repo_id = $gs->{repo_id};
1538 $remotes ||= read_all_remotes();
1539 my $remote = $remotes->{$repo_id} or
1540 die "[svn-remote \"$repo_id\"] unknown\n";
1541 my $fetch = $remote->{fetch};
1542 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1544 my $ra = Git::SVN::Ra->new($url);
1545 my $uuid = $ra->get_uuid;
1546 my $head = $ra->get_latest_revnum;
1547 my $base = defined $fetch ? $head : 0;
1549 # read the max revs for wildcard expansion (branches/*, tags/*)
1550 foreach my $t (qw/branches tags/) {
1551 defined $remote->{$t} or next;
1552 push @globs, $remote->{$t};
1553 my $max_rev = eval { tmp_config(qw/--int --get/,
1554 "svn-remote.$repo_id.${t}-maxRev") };
1555 if (defined $max_rev && ($max_rev < $base)) {
1557 } elsif (!defined $max_rev) {
1563 foreach my $p (sort keys %$fetch) {
1564 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1565 my $lr = $gs->rev_map_max;
1567 $base = $lr if ($lr < $base);
1573 ($base, $head) = parse_revision_argument($base, $head);
1574 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1577 sub read_all_remotes {
1579 my $use_svm_props = eval { command_oneline(qw/config --bool
1580 svn.useSvmProps/) };
1581 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1582 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1583 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1584 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1585 die("svn-remote.$remote: remote ref '$_remote_ref' "
1586 . "must start with 'refs/remotes/'\n")
1587 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1588 my $remote_ref = $1;
1589 $local_ref =~ s{^/}{};
1590 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1591 $r->{$remote}->{svm} = {} if $use_svm_props;
1592 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1593 $r->{$1}->{svm} = {};
1594 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1595 $r->{$1}->{url} = $2;
1596 } elsif (m!^(.+)\.(branches|tags)=
1597 (.*):refs/remotes/(.+)\s*$/!x) {
1598 my ($p, $g) = ($3, $4);
1599 my $rs = $r->{$1}->{$2} = {
1602 path => Git::SVN::GlobSpec->new($p),
1603 ref => Git::SVN::GlobSpec->new($g) };
1604 if (length($rs->{ref}->{right}) != 0) {
1605 die "The '*' glob character must be the last ",
1606 "character of '$g'\n";
1612 if (defined $r->{$_}->{svm}) {
1615 my $section = "svn-remote.$_";
1617 source => tmp_config('--get',
1618 "$section.svm-source"),
1619 replace => tmp_config('--get',
1620 "$section.svm-replace"),
1623 $r->{$_}->{svm} = $svm;
1631 $_gc_nr = $_gc_period = 1000;
1632 if (defined $_repack || defined $_repack_flags) {
1633 warn "Repack options are obsolete; they have no effect.\n";
1637 sub verify_remotes_sanity {
1638 return unless -d $ENV{GIT_DIR};
1640 foreach (command(qw/config -l/)) {
1641 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1643 die "Remote ref refs/remote/$1 is tracked by",
1644 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1645 "Please resolve this ambiguity in ",
1646 "your git configuration file before ",
1654 sub find_existing_remote {
1655 my ($url, $remotes) = @_;
1656 return undef if $no_reuse_existing;
1658 foreach my $repo_id (keys %$remotes) {
1659 my $u = $remotes->{$repo_id}->{url} or next;
1661 $existing = $repo_id;
1667 sub init_remote_config {
1668 my ($self, $url, $no_write) = @_;
1669 $url =~ s!/+$!!; # strip trailing slash
1670 my $r = read_all_remotes();
1671 my $existing = find_existing_remote($url, $r);
1673 unless ($no_write) {
1674 print STDERR "Using existing ",
1675 "[svn-remote \"$existing\"]\n";
1677 $self->{repo_id} = $existing;
1678 } elsif ($_minimize_url) {
1679 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1680 $existing = find_existing_remote($min_url, $r);
1682 unless ($no_write) {
1683 print STDERR "Using existing ",
1684 "[svn-remote \"$existing\"]\n";
1686 $self->{repo_id} = $existing;
1688 if ($min_url ne $url) {
1689 unless ($no_write) {
1690 print STDERR "Using higher level of URL: ",
1691 "$url => $min_url\n";
1693 my $old_path = $self->{path};
1694 $self->{path} = $url;
1695 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1696 if (length $old_path) {
1697 $self->{path} .= "/$old_path";
1704 # verify that we aren't overwriting anything:
1706 command_oneline('config', '--get',
1707 "svn-remote.$self->{repo_id}.url")
1709 if ($orig_url && ($orig_url ne $url)) {
1710 die "svn-remote.$self->{repo_id}.url already set: ",
1711 "$orig_url\nwanted to set to: $url\n";
1714 my ($xrepo_id, $xpath) = find_ref($self->refname);
1715 if (defined $xpath) {
1716 die "svn-remote.$xrepo_id.fetch already set to track ",
1717 "$xpath:refs/remotes/", $self->refname, "\n";
1719 unless ($no_write) {
1720 command_noisy('config',
1721 "svn-remote.$self->{repo_id}.url", $url);
1722 $self->{path} =~ s{^/}{};
1723 command_noisy('config', '--add',
1724 "svn-remote.$self->{repo_id}.fetch",
1725 "$self->{path}:".$self->refname);
1727 $self->{url} = $url;
1730 sub find_by_url { # repos_root and, path are optional
1731 my ($class, $full_url, $repos_root, $path) = @_;
1733 return undef unless defined $full_url;
1734 remove_username($full_url);
1735 remove_username($repos_root) if defined $repos_root;
1736 my $remotes = read_all_remotes();
1737 if (defined $full_url && defined $repos_root && !defined $path) {
1739 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1741 foreach my $repo_id (keys %$remotes) {
1742 my $u = $remotes->{$repo_id}->{url} or next;
1743 remove_username($u);
1744 next if defined $repos_root && $repos_root ne $u;
1746 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1747 foreach (qw/branches tags/) {
1748 resolve_local_globs($u, $fetch,
1749 $remotes->{$repo_id}->{$_});
1752 my $rwr = rewrite_root({repo_id => $repo_id});
1753 my $svm = $remotes->{$repo_id}->{svm}
1754 if defined $remotes->{$repo_id}->{svm};
1755 unless (defined $p) {
1761 remove_username($z);
1762 } elsif (defined $svm) {
1763 $z = $svm->{source};
1764 $prefix = $svm->{replace};
1765 $prefix =~ s#^\Q$u\E(?:/|$)##;
1768 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1770 foreach my $f (keys %$fetch) {
1772 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1779 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1780 my $self = _new($class, $repo_id, $ref_id, $path);
1782 $self->init_remote_config($url, $no_write);
1789 foreach (command(qw/config -l/)) {
1790 next unless m!^svn-remote\.(.+)\.fetch=
1791 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1792 my ($repo_id, $path, $ref) = ($1, $2, $3);
1793 if ($ref eq $ref_id) {
1794 $path = '' if ($path =~ m#^\./?#);
1795 return ($repo_id, $path);
1798 (undef, undef, undef);
1802 my ($class, $ref_id, $repo_id, $path) = @_;
1803 if (defined $ref_id && !defined $repo_id && !defined $path) {
1804 ($repo_id, $path) = find_ref($ref_id);
1805 if (!defined $repo_id) {
1806 die "Could not find a \"svn-remote.*.fetch\" key ",
1807 "in the repository configuration matching: ",
1808 "refs/remotes/$ref_id\n";
1811 my $self = _new($class, $repo_id, $ref_id, $path);
1812 if (!defined $self->{path} || !length $self->{path}) {
1813 my $fetch = command_oneline('config', '--get',
1814 "svn-remote.$repo_id.fetch",
1815 ":refs/remotes/$ref_id\$") or
1816 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1817 "\":refs/remotes/$ref_id\$\" in config\n";
1818 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1820 $self->{url} = command_oneline('config', '--get',
1821 "svn-remote.$repo_id.url") or
1822 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1828 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1830 # It cannot end with a slash /, we'll throw up on this because
1831 # SVN can't have directories with a slash in their name, either:
1832 if ($refname =~ m{/$}) {
1833 die "ref: '$refname' ends with a trailing slash, this is ",
1834 "not permitted by git nor Subversion\n";
1837 # It cannot have ASCII control character space, tilde ~, caret ^,
1838 # colon :, question-mark ?, asterisk *, space, or open bracket [
1841 # Additionally, % must be escaped because it is used for escaping
1842 # and we want our escaped refname to be reversible
1843 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1845 # no slash-separated component can begin with a dot .
1847 $refname =~ s{/\.}{/%2E}g;
1849 # It cannot have two consecutive dots .. anywhere
1851 $refname =~ s{\.\.}{%2E%2E}g;
1856 sub desanitize_refname {
1858 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1864 return $self->{svm}->{uuid} if $self->svm;
1866 unless ($self->{svm}) {
1867 die "SVM UUID not cached, and reading remotely failed\n";
1869 $self->{svm}->{uuid};
1874 return $self->{svm} if $self->{svm};
1876 # see if we have it in our config, first:
1878 my $section = "svn-remote.$self->{repo_id}";
1880 source => tmp_config('--get', "$section.svm-source"),
1881 uuid => tmp_config('--get', "$section.svm-uuid"),
1882 replace => tmp_config('--get', "$section.svm-replace"),
1885 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1886 $self->{svm} = $svm;
1892 my ($self, $ra) = @_;
1893 return $ra if $self->svm;
1895 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1896 "(svm:source, svm:uuid) ",
1897 "from the following URLs:\n" );
1898 sub read_svm_props {
1899 my ($self, $ra, $path, $r) = @_;
1900 my $props = ($ra->get_dir($path, $r))[2];
1901 my $src = $props->{'svm:source'};
1902 my $uuid = $props->{'svm:uuid'};
1903 return undef if (!$src || !$uuid);
1907 $uuid =~ m{^[0-9a-f\-]{30,}$}
1908 or die "doesn't look right - svm:uuid is '$uuid'\n";
1910 # the '!' is used to mark the repos_root!/relative/path
1911 $src =~ s{/?!/?}{/};
1912 $src =~ s{/+$}{}; # no trailing slashes please
1913 # username is of no interest
1914 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1916 my $replace = $ra->{url};
1917 $replace .= "/$path" if length $path;
1919 my $section = "svn-remote.$self->{repo_id}";
1920 tmp_config("$section.svm-source", $src);
1921 tmp_config("$section.svm-replace", $replace);
1922 tmp_config("$section.svm-uuid", $uuid);
1930 my $r = $ra->get_latest_revnum;
1931 my $path = $self->{path};
1933 while (length $path) {
1934 unless ($tried{"$self->{url}/$path"}) {
1935 return $ra if $self->read_svm_props($ra, $path, $r);
1936 $tried{"$self->{url}/$path"} = 1;
1938 $path =~ s#/?[^/]+$##;
1940 die "Path: '$path' should be ''\n" if $path ne '';
1941 return $ra if $self->read_svm_props($ra, $path, $r);
1942 $tried{"$self->{url}/$path"} = 1;
1944 if ($ra->{repos_root} eq $self->{url}) {
1945 die @err, (map { " $_\n" } keys %tried), "\n";
1948 # nope, make sure we're connected to the repository root:
1951 $path = $ra->{svn_path};
1952 $ra = Git::SVN::Ra->new($ra->{repos_root});
1953 while (length $path) {
1954 unless ($tried{"$ra->{url}/$path"}) {
1955 $ok = $self->read_svm_props($ra, $path, $r);
1957 $tried{"$ra->{url}/$path"} = 1;
1959 $path =~ s#/?[^/]+$##;
1961 die "Path: '$path' should be ''\n" if $path ne '';
1962 $ok ||= $self->read_svm_props($ra, $path, $r);
1963 $tried{"$ra->{url}/$path"} = 1;
1965 die @err, (map { " $_\n" } keys %tried), "\n";
1967 Git::SVN::Ra->new($self->{url});
1972 return $self->{svnsync} if $self->{svnsync};
1974 if ($self->no_metadata) {
1975 die "Can't have both 'noMetadata' and ",
1976 "'useSvnsyncProps' options set!\n";
1978 if ($self->rewrite_root) {
1979 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1984 # see if we have it in our config, first:
1986 my $section = "svn-remote.$self->{repo_id}";
1988 my $url = tmp_config('--get', "$section.svnsync-url");
1989 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1990 die "doesn't look right - svn:sync-from-url is '$url'\n";
1992 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1993 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1994 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1996 $svnsync = { url => $url, uuid => $uuid }
1998 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1999 return $self->{svnsync} = $svnsync;
2002 my $err = "useSvnsyncProps set, but failed to read " .
2003 "svnsync property: svn:sync-from-";
2004 my $rp = $self->ra->rev_proplist(0);
2006 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2007 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2008 die "doesn't look right - svn:sync-from-url is '$url'\n";
2010 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2011 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2012 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2014 my $section = "svn-remote.$self->{repo_id}";
2015 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2016 tmp_config('--add', "$section.svnsync-url", $url);
2017 return $self->{svnsync} = { url => $url, uuid => $uuid };
2020 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2021 # remote lookup (useful for 'git svn log').
2024 unless ($self->{ra_uuid}) {
2025 my $key = "svn-remote.$self->{repo_id}.uuid";
2026 my $uuid = eval { tmp_config('--get', $key) };
2027 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2028 $self->{ra_uuid} = $uuid;
2030 die "ra_uuid called without URL\n" unless $self->{url};
2031 $self->{ra_uuid} = $self->ra->get_uuid;
2032 tmp_config('--add', $key, $self->{ra_uuid});
2038 sub _set_repos_root {
2039 my ($self, $repos_root) = @_;
2040 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2041 $repos_root ||= $self->ra->{repos_root};
2042 tmp_config($k, $repos_root);
2048 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2049 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2054 my $ra = Git::SVN::Ra->new($self->{url});
2055 $self->_set_repos_root($ra->{repos_root});
2056 if ($self->use_svm_props && !$self->{svm}) {
2057 if ($self->no_metadata) {
2058 die "Can't have both 'noMetadata' and ",
2059 "'useSvmProps' options set!\n";
2060 } elsif ($self->use_svnsync_props) {
2061 die "Can't have both 'useSvnsyncProps' and ",
2062 "'useSvmProps' options set!\n";
2064 $ra = $self->_set_svm_vars($ra);
2065 $self->{-want_revprops} = 1;
2072 my $repos_root = $self->ra->{repos_root};
2073 return $self->{path} if ($self->{url} eq $repos_root);
2074 my $url = $self->{url} .
2075 (length $self->{path} ? "/$self->{path}" : $self->{path});
2076 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2080 # prop_walk(PATH, REV, SUB)
2081 # -------------------------
2082 # Recursively traverse PATH at revision REV and invoke SUB for each
2083 # directory that contains a SVN property. SUB will be invoked as
2084 # follows: &SUB(gs, path, props); where `gs' is this instance of
2085 # Git::SVN, `path' the path to the directory where the properties
2086 # `props' were found. The `path' will be relative to point of checkout,
2087 # that is, if url://repo/trunk is the current Git branch, and that
2088 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2089 # as `path' (note the trailing `/').
2091 my ($self, $path, $rev, $sub) = @_;
2094 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2097 # Strip the irrelevant part of the path.
2098 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2099 # Ensure the path is terminated by a `/'.
2102 # The properties contain all the internal SVN stuff nobody
2103 # (usually) cares about.
2104 my $interesting_props = 0;
2105 foreach (keys %{$props}) {
2106 # If it doesn't start with `svn:', it must be a
2107 # user-defined property.
2108 ++$interesting_props and next if $_ !~ /^svn:/;
2109 # FIXME: Fragile, if SVN adds new public properties,
2110 # this needs to be updated.
2111 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2112 |eol-style|mime-type
2113 |externals|needs-lock)$/x;
2115 &$sub($self, $p, $props) if $interesting_props;
2117 foreach (sort keys %$dirent) {
2118 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2119 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2123 sub last_rev { ($_[0]->last_rev_commit)[0] }
2124 sub last_commit { ($_[0]->last_rev_commit)[1] }
2126 # returns the newest SVN revision number and newest commit SHA1
2127 sub last_rev_commit {
2129 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2130 return ($self->{last_rev}, $self->{last_commit});
2132 my $c = ::verify_ref($self->refname.'^0');
2133 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2134 my $rev = (::cmt_metadata($c))[1];
2136 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2140 my $map_path = $self->map_path;
2141 unless (-e $map_path) {
2142 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2143 return (undef, undef);
2145 my ($rev, $commit) = $self->rev_map_max(1);
2146 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2147 return ($rev, $commit);
2150 sub get_fetch_range {
2151 my ($self, $min, $max) = @_;
2152 $max ||= $self->ra->get_latest_revnum;
2153 $min ||= $self->rev_map_max;
2159 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2160 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2161 if (! -f $config && -f $old_def_config) {
2162 rename $old_def_config, $config or
2163 die "Failed rename $old_def_config => $config: $!\n";
2165 my $old_config = $ENV{GIT_CONFIG};
2166 $ENV{GIT_CONFIG} = $config;
2169 unless (-f $config) {
2171 open my $fh, '>', $config or
2172 die "Can't open $config: $!\n";
2173 print $fh "; This file is used internally by ",
2175 "Couldn't write to $config: $!\n";
2176 print $fh "; You should not have to edit it\n" or
2177 die "Couldn't write to $config: $!\n";
2178 close $fh or die "Couldn't close $config: $!\n";
2180 command('config', @args);
2183 if (defined $old_config) {
2184 $ENV{GIT_CONFIG} = $old_config;
2186 delete $ENV{GIT_CONFIG};
2189 wantarray ? @ret : $ret[0];
2193 my ($self, $sub) = @_;
2194 my $old_index = $ENV{GIT_INDEX_FILE};
2195 $ENV{GIT_INDEX_FILE} = $self->{index};
2198 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2199 mkpath([$dir]) unless -d $dir;
2203 if (defined $old_index) {
2204 $ENV{GIT_INDEX_FILE} = $old_index;
2206 delete $ENV{GIT_INDEX_FILE};
2209 wantarray ? @ret : $ret[0];
2212 sub assert_index_clean {
2213 my ($self, $treeish) = @_;
2215 $self->tmp_index_do(sub {
2216 command_noisy('read-tree', $treeish) unless -e $self->{index};
2217 my $x = command_oneline('write-tree');
2218 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2219 /^tree ($::sha1)/mo);
2222 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2223 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2224 command_noisy('read-tree', $treeish);
2225 $x = command_oneline('write-tree');
2227 ::fatal "trees ($treeish) $y != $x\n",
2228 "Something is seriously wrong...";
2233 sub get_commit_parents {
2234 my ($self, $log_entry) = @_;
2235 my (%seen, @ret, @tmp);
2236 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2237 if (my $ip = $self->{inject_parents}) {
2238 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2242 if (my $cur = ::verify_ref($self->refname.'^0')) {
2245 if (my $ipd = $self->{inject_parents_dcommit}) {
2246 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2247 push @tmp, @$commit;
2250 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2251 while (my $p = shift @tmp) {
2255 # MAXPARENT is defined to 16 in commit-tree.c:
2259 die "r$log_entry->{revision}: No room for parents:\n\t",
2260 join("\n\t", @tmp), "\n";
2267 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2268 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2269 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2272 if ($rwr !~ m#^[a-z\+]+://#) {
2273 die "$rwr is not a valid URL (key: $k)\n";
2276 $self->{-rewrite_root} = $rwr;
2281 ($self->rewrite_root || $self->{url}) .
2282 (length $self->{path} ? '/' . $self->{path} : '');
2287 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2291 sub set_commit_header_env {
2292 my ($log_entry) = @_;
2294 foreach my $ned (qw/NAME EMAIL DATE/) {
2295 foreach my $ac (qw/AUTHOR COMMITTER/) {
2296 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2300 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2301 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2302 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2304 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2305 ? $log_entry->{commit_name}
2306 : $log_entry->{name};
2307 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2308 ? $log_entry->{commit_email}
2309 : $log_entry->{email};
2313 sub restore_commit_header_env {
2315 foreach my $ned (qw/NAME EMAIL DATE/) {
2316 foreach my $ac (qw/AUTHOR COMMITTER/) {
2317 my $k = "GIT_${ac}_${ned}";
2318 if (defined $env->{$k}) {
2319 $ENV{$k} = $env->{$k};
2328 command_noisy('gc', '--auto');
2332 my ($self, $log_entry) = @_;
2333 my $lr = $self->last_rev;
2334 if (defined $lr && $lr >= $log_entry->{revision}) {
2335 die "Last fetched revision of ", $self->refname,
2336 " was r$lr, but we are about to fetch: ",
2337 "r$log_entry->{revision}!\n";
2339 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2340 croak "$log_entry->{revision} = $c already exists! ",
2341 "Why are we refetching it?\n";
2343 my $old_env = set_commit_header_env($log_entry);
2344 my $tree = $log_entry->{tree};
2345 if (!defined $tree) {
2346 $tree = $self->tmp_index_do(sub {
2347 command_oneline('write-tree') });
2349 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2351 my @exec = ('git', 'commit-tree', $tree);
2352 foreach ($self->get_commit_parents($log_entry)) {
2353 push @exec, '-p', $_;
2355 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2359 # we always get UTF-8 from SVN, but we may want our commits in
2360 # a different encoding.
2361 if (my $enc = Git::config('i18n.commitencoding')) {
2363 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2365 print $msg_fh $log_entry->{log} or croak $!;
2366 restore_commit_header_env($old_env);
2367 unless ($self->no_metadata) {
2368 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2371 $msg_fh->flush == 0 or croak $!;
2372 close $msg_fh or croak $!;
2373 chomp(my $commit = do { local $/; <$out_fh> });
2374 close $out_fh or croak $!;
2377 if ($commit !~ /^$::sha1$/o) {
2378 die "Failed to commit, invalid sha1: $commit\n";
2381 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2383 $self->{last_rev} = $log_entry->{revision};
2384 $self->{last_commit} = $commit;
2385 print "r$log_entry->{revision}" unless $::_q > 1;
2386 if (defined $log_entry->{svm_revision}) {
2387 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2388 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2389 0, $self->svm_uuid);
2391 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2392 if (--$_gc_nr == 0) {
2393 $_gc_nr = $_gc_period;
2400 my ($self, $paths, $r) = @_;
2401 return 1 if $self->{path} eq '';
2402 if (my $path = $paths->{"/$self->{path}"}) {
2403 return ($path->{action} eq 'D') ? 0 : 1;
2405 my $repos_root = $self->ra->{repos_root};
2406 my $extended_path = $self->{url} . '/' . $self->{path};
2407 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2408 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2409 if (grep /$self->{path_regex}/, keys %$paths) {
2413 foreach (split m#/#, $self->{path}) {
2415 next unless ($paths->{$c} &&
2416 ($paths->{$c}->{action} =~ /^[AR]$/));
2417 if ($self->ra->check_path($self->{path}, $r) ==
2425 sub find_parent_branch {
2426 my ($self, $paths, $rev) = @_;
2427 return undef unless $self->follow_parent;
2428 unless (defined $paths) {
2429 my $err_handler = $SVN::Error::handler;
2430 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2431 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2433 Git::SVN::Ra::dup_changed_paths($_[0]) });
2434 $SVN::Error::handler = $err_handler;
2436 return undef unless defined $paths;
2438 # look for a parent from another branch:
2439 my @b_path_components = split m#/#, $self->rel_path;
2440 my @a_path_components;
2442 while (@b_path_components) {
2443 $i = $paths->{'/'.join('/', @b_path_components)};
2444 last if $i && defined $i->{copyfrom_path};
2445 unshift(@a_path_components, pop(@b_path_components));
2447 return undef unless defined $i && defined $i->{copyfrom_path};
2448 my $branch_from = $i->{copyfrom_path};
2449 if (@a_path_components) {
2450 print STDERR "branch_from: $branch_from => ";
2451 $branch_from .= '/'.join('/', @a_path_components);
2452 print STDERR $branch_from, "\n";
2454 my $r = $i->{copyfrom_rev};
2455 my $repos_root = $self->ra->{repos_root};
2456 my $url = $self->ra->{url};
2457 my $new_url = $repos_root . $branch_from;
2458 print STDERR "Found possible branch point: ",
2459 "$new_url => ", $self->full_url, ", $r\n";
2460 $branch_from =~ s#^/##;
2461 my $gs = $self->other_gs($new_url, $url, $repos_root,
2462 $branch_from, $r, $self->{ref_id});
2463 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2466 if (!defined $r0 || !defined $parent) {
2467 ($base, $head) = parse_revision_argument(0, $r);
2470 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2471 0, 1, sub { $base = $_[1] - 1 });
2474 if (defined $base && $base <= $r) {
2475 $gs->fetch($base, $r);
2477 ($r0, $parent) = $gs->find_rev_before($r, 1);
2479 if (defined $r0 && defined $parent) {
2480 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2482 if ($self->ra->can_do_switch) {
2483 $self->assert_index_clean($parent);
2484 print STDERR "Following parent with do_switch\n";
2485 # do_switch works with svn/trunk >= r22312, but that
2486 # is not included with SVN 1.4.3 (the latest version
2487 # at the moment), so we can't rely on it
2488 $self->{last_rev} = $r0;
2489 $self->{last_commit} = $parent;
2490 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2491 $gs->ra->gs_do_switch($r0, $rev, $gs,
2492 $self->full_url, $ed)
2493 or die "SVN connection failed somewhere...\n";
2494 } elsif ($self->ra->trees_match($new_url, $r0,
2495 $self->full_url, $rev)) {
2496 print STDERR "Trees match:\n",
2498 " ${\$self->full_url}\@$rev\n",
2499 "Following parent with no changes\n";
2500 $self->tmp_index_do(sub {
2501 command_noisy('read-tree', $parent);
2503 $self->{last_commit} = $parent;
2505 print STDERR "Following parent with do_update\n";
2506 $ed = SVN::Git::Fetcher->new($self);
2507 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2508 or die "SVN connection failed somewhere...\n";
2510 print STDERR "Successfully followed parent\n";
2511 return $self->make_log_entry($rev, [$parent], $ed);
2517 my ($self, $paths, $rev) = @_;
2519 my ($last_rev, @parents);
2520 if (my $lc = $self->last_commit) {
2521 # we can have a branch that was deleted, then re-added
2522 # under the same name but copied from another path, in
2523 # which case we'll have multiple parents (we don't
2524 # want to break the original ref, nor lose copypath info):
2525 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2526 push @{$log_entry->{parents}}, $lc;
2529 $ed = SVN::Git::Fetcher->new($self);
2530 $last_rev = $self->{last_rev};
2535 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2538 $ed = SVN::Git::Fetcher->new($self);
2540 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2541 die "SVN connection failed somewhere...\n";
2543 $self->make_log_entry($rev, \@parents, $ed);
2547 my ($self, $ed) = @_;
2549 my $h = $ed->{empty};
2550 foreach (sort keys %$h) {
2551 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2552 push @out, " $act: " . uri_encode($_);
2553 warn "W: $act: $_\n";
2555 foreach my $t (qw/dir_prop file_prop/) {
2556 $h = $ed->{$t} or next;
2557 foreach my $path (sort keys %$h) {
2558 my $ppath = $path eq '' ? '.' : $path;
2559 foreach my $prop (sort keys %{$h->{$path}}) {
2560 next if $SKIP_PROP{$prop};
2561 my $v = $h->{$path}->{$prop};
2562 my $t_ppath_prop = "$t: " .
2563 uri_encode($ppath) . ' ' .
2566 push @out, " +$t_ppath_prop " .
2569 push @out, " -$t_ppath_prop";
2574 foreach my $t (qw/absent_file absent_directory/) {
2575 $h = $ed->{$t} or next;
2576 foreach my $parent (sort keys %$h) {
2577 foreach my $path (sort @{$h->{$parent}}) {
2578 push @out, " $t: " .
2579 uri_encode("$parent/$path");
2580 warn "W: $t: $parent/$path ",
2581 "Insufficient permissions?\n";
2588 # parse_svn_date(DATE)
2589 # --------------------
2590 # Given a date (in UTC) from Subversion, return a string in the format
2591 # "<TZ Offset> <local date/time>" that Git will use.
2593 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2594 # is true we'll convert it to the local timezone instead.
2595 sub parse_svn_date {
2596 my $date = shift || return '+0000 1970-01-01 00:00:00';
2597 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2598 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2599 croak "Unable to parse date: $date\n";
2600 my $parsed_date; # Set next.
2602 if ($Git::SVN::_localtime) {
2603 # Translate the Subversion datetime to an epoch time.
2604 # Begin by switching ourselves to $date's timezone, UTC.
2605 my $old_env_TZ = $ENV{TZ};
2609 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2611 # Determine our local timezone (including DST) at the
2612 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2613 # value of TZ, if any, at the time we were run.
2614 if (defined $Git::SVN::Log::TZ) {
2615 $ENV{TZ} = $Git::SVN::Log::TZ;
2621 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2623 # This converts $epoch_in_UTC into our local timezone.
2624 my ($sec, $min, $hour, $mday, $mon, $year,
2625 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2627 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2628 $our_TZ, $year + 1900, $mon + 1,
2629 $mday, $hour, $min, $sec);
2631 # Reset us to the timezone in effect when we entered
2633 if (defined $old_env_TZ) {
2634 $ENV{TZ} = $old_env_TZ;
2639 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2642 return $parsed_date;
2646 my ($self, $new_url, $url, $repos_root,
2647 $branch_from, $r, $old_ref_id) = @_;
2648 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2650 my $ref_id = $old_ref_id;
2651 $ref_id =~ s/\@\d+$//;
2653 # just grow a tail if we're not unique enough :x
2654 $ref_id .= '-' while find_ref($ref_id);
2655 print STDERR "Initializing parent: $ref_id\n";
2656 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2657 if ($u =~ s#^\Q$url\E(/|$)##) {
2660 $repo_id = $self->{repo_id};
2662 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2669 if (!defined $author || length $author == 0) {
2670 $author = '(no author)';
2671 } elsif (defined $::_authors && ! defined $::users{$author}) {
2672 die "Author: $author not defined in $::_authors file\n";
2677 sub make_log_entry {
2678 my ($self, $rev, $parents, $ed) = @_;
2679 my $untracked = $self->get_untracked($ed);
2681 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2682 print $un "r$rev\n" or croak $!;
2683 print $un $_, "\n" foreach @$untracked;
2684 my %log_entry = ( parents => $parents || [], revision => $rev,
2688 my $logged = delete $self->{logged_rev_props};
2689 if (!$logged || $self->{-want_revprops}) {
2690 my $rp = $self->ra->rev_proplist($rev);
2691 foreach (sort keys %$rp) {
2693 if (/^svn:(author|date|log)$/) {
2694 $log_entry{$1} = $v;
2695 } elsif ($_ eq 'svm:headrev') {
2698 print $un " rev_prop: ", uri_encode($_), ' ',
2699 uri_encode($v), "\n";
2703 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2705 close $un or croak $!;
2707 $log_entry{date} = parse_svn_date($log_entry{date});
2708 $log_entry{log} .= "\n";
2709 my $author = $log_entry{author} = check_author($log_entry{author});
2710 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2713 my ($commit_name, $commit_email) = ($name, $email);
2714 if ($_use_log_author) {
2716 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2718 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2721 if (!defined $name_field) {
2722 if (!defined $email) {
2725 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2726 ($name, $email) = ($1, $2);
2727 } elsif ($name_field =~ /(.*)@/) {
2728 ($name, $email) = ($1, $name_field);
2730 ($name, $email) = ($name_field, $name_field);
2733 if (defined $headrev && $self->use_svm_props) {
2734 if ($self->rewrite_root) {
2735 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2738 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2739 # we don't want "SVM: initializing mirror for junk" ...
2740 return undef if $r == 0;
2741 my $svm = $self->svm;
2742 if ($uuid ne $svm->{uuid}) {
2743 die "UUID mismatch on SVM path:\n",
2744 "expected: $svm->{uuid}\n",
2747 my $full_url = $self->full_url;
2748 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2749 die "Failed to replace '$svm->{replace}' with ",
2750 "'$svm->{source}' in $full_url\n";
2751 # throw away username for storing in records
2752 remove_username($full_url);
2753 $log_entry{metadata} = "$full_url\@$r $uuid";
2754 $log_entry{svm_revision} = $r;
2755 $email ||= "$author\@$uuid";
2756 $commit_email ||= "$author\@$uuid";
2757 } elsif ($self->use_svnsync_props) {
2758 my $full_url = $self->svnsync->{url};
2759 $full_url .= "/$self->{path}" if length $self->{path};
2760 remove_username($full_url);
2761 my $uuid = $self->svnsync->{uuid};
2762 $log_entry{metadata} = "$full_url\@$rev $uuid";
2763 $email ||= "$author\@$uuid";
2764 $commit_email ||= "$author\@$uuid";
2766 my $url = $self->metadata_url;
2767 remove_username($url);
2768 $log_entry{metadata} = "$url\@$rev " .
2769 $self->ra->get_uuid;
2770 $email ||= "$author\@" . $self->ra->get_uuid;
2771 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2773 $log_entry{name} = $name;
2774 $log_entry{email} = $email;
2775 $log_entry{commit_name} = $commit_name;
2776 $log_entry{commit_email} = $commit_email;
2781 my ($self, $min_rev, $max_rev, @parents) = @_;
2782 my ($last_rev, $last_commit) = $self->last_rev_commit;
2783 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2784 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2788 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2789 $self->{inject_parents} = { $rev => $tree };
2790 $self->fetch(undef, undef);
2794 my ($self, $tree) = (shift, shift);
2795 my $log_entry = ::get_commit_entry($tree);
2796 unless ($self->{last_rev}) {
2797 ::fatal("Must have an existing revision to commit");
2799 my %ed_opts = ( r => $self->{last_rev},
2800 log => $log_entry->{log},
2802 tree_a => $self->{last_commit},
2805 $self->set_tree_cb($log_entry, $tree, @_) },
2806 svn_path => $self->{path} );
2807 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2808 print "No changes\nr$self->{last_rev} = $tree\n";
2812 sub rebuild_from_rev_db {
2813 my ($self, $path) = @_;
2815 open my $fh, '<', $path or croak "open: $!";
2816 binmode $fh or croak "binmode: $!";
2818 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2821 next if $_ eq ('0' x 40);
2822 $self->rev_map_set($r, $_);
2825 close $fh or croak "close: $!";
2826 unlink $path or croak "unlink: $!";
2831 my $map_path = $self->map_path;
2832 my $partial = (-e $map_path && ! -z $map_path);
2833 return unless ::verify_ref($self->refname.'^0');
2834 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2835 my $rev_db = $self->rev_db_path;
2836 $self->rebuild_from_rev_db($rev_db);
2837 if ($self->use_svm_props) {
2838 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2839 $self->rebuild_from_rev_db($svm_rev_db);
2841 $self->unlink_rev_db_symlink;
2844 print "Rebuilding $map_path ...\n" if (!$partial);
2845 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2848 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2849 ($head ? "$head.." : "") . $self->refname,
2851 my $metadata_url = $self->metadata_url;
2852 remove_username($metadata_url);
2853 my $svn_uuid = $self->ra_uuid;
2856 if ( m{^commit ($::sha1)$} ) {
2860 next unless s{^\s*(git-svn-id:)}{$1};
2861 my ($url, $rev, $uuid) = ::extract_metadata($_);
2862 remove_username($url);
2864 # ignore merges (from set-tree)
2865 next if (!defined $rev || !$uuid);
2867 # if we merged or otherwise started elsewhere, this is
2868 # how we break out of it
2869 if (($uuid ne $svn_uuid) ||
2870 ($metadata_url && $url && ($url ne $metadata_url))) {
2873 if ($partial && $head) {
2874 print "Partial-rebuilding $map_path ...\n";
2875 print "Currently at $base_rev = $head\n";
2879 $self->rev_map_set($rev, $c);
2880 print "r$rev = $c\n";
2882 command_close_pipe($log, $ctx);
2883 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2884 my $rev_db_path = $self->rev_db_path;
2885 if (-f $self->rev_db_path) {
2886 unlink $self->rev_db_path or croak "unlink: $!";
2888 $self->unlink_rev_db_symlink;
2892 # Tie::File seems to be prone to offset errors if revisions get sparse,
2893 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2894 # one of my favorite modules is out :< Next up would be one of the DBM
2895 # modules, but I'm not sure which is most portable...
2897 # This is the replacement for the rev_db format, which was too big
2898 # and inefficient for large repositories with a lot of sparse history
2901 # The format is this:
2902 # - 24 bytes for every record,
2903 # * 4 bytes for the integer representing an SVN revision number
2904 # * 20 bytes representing the sha1 of a git commit
2905 # - No empty padding records like the old format
2906 # (except the last record, which can be overwritten)
2907 # - new records are written append-only since SVN revision numbers
2908 # increase monotonically
2909 # - lookups on SVN revision number are done via a binary search
2910 # - Piping the file to xxd -c24 is a good way of dumping it for
2911 # viewing or editing (piped back through xxd -r), should the need
2913 # - The last record can be padding revision with an all-zero sha1
2914 # This is used to optimize fetch performance when using multiple
2915 # "fetch" directives in .git/config
2917 # These files are disposable unless noMetadata or useSvmProps is set
2920 my ($fh, $rev, $commit) = @_;
2922 binmode $fh or croak "binmode: $!";
2923 my $size = (stat($fh))[7];
2924 ($size % 24) == 0 or croak "inconsistent size: $size";
2928 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2929 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2930 $read == 24 or croak "read only $read bytes (!= 24)";
2931 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2932 if ($last_commit eq ('0' x40)) {
2934 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2935 $read = sysread($fh, $buf, 24) or
2938 croak "read only $read bytes (!= 24)";
2939 ($last_rev, $last_commit) =
2940 unpack(rev_map_fmt, $buf);
2941 if ($last_commit eq ('0' x40)) {
2942 croak "inconsistent .rev_map\n";
2945 if ($last_rev >= $rev) {
2946 croak "last_rev is higher!: $last_rev >= $rev";
2951 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2952 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2959 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2960 mkpath([$dir]) unless -d $dir;
2961 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2962 close $fh or die "Couldn't close (create) $path: $!\n";
2967 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2968 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2969 my $db = $self->map_path($uuid);
2970 my $db_lock = "$db.lock";
2973 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2974 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2978 $LOCKFILES{$db_lock} = 1;
2980 # both of these options make our .rev_db file very, very important
2981 # and we can't afford to lose it because rebuild() won't work
2982 if ($self->use_svm_props || $self->no_metadata) {
2984 copy($db, $db_lock) or die "rev_map_set(@_): ",
2986 "$db => $db_lock ($!)\n";
2988 rename $db, $db_lock or die "rev_map_set(@_): ",
2989 "Failed to rename: ",
2990 "$db => $db_lock ($!)\n";
2993 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2994 or croak "Couldn't open $db_lock: $!\n";
2995 _rev_map_set($fh, $rev, $commit);
2997 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2998 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3000 close $fh or croak $!;
3003 command_noisy('update-ref', '-m', "r$rev",
3004 $self->refname, $commit);
3006 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3007 "$db_lock => $db ($!)\n";
3008 delete $LOCKFILES{$db_lock};
3010 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3011 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3012 kill $sig, $$ if defined $sig;
3016 # If want_commit, this will return an array of (rev, commit) where
3017 # commit _must_ be a valid commit in the archive.
3018 # Otherwise, it'll return the max revision (whether or not the
3019 # commit is valid or just a 0x40 placeholder).
3021 my ($self, $want_commit) = @_;
3023 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3024 $want_commit ? ($r, $c) : $r;
3027 sub rev_map_max_norebuild {
3028 my ($self, $want_commit) = @_;
3029 my $map_path = $self->map_path;
3030 stat $map_path or return $want_commit ? (0, undef) : 0;
3031 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3032 binmode $fh or croak "binmode: $!";
3033 my $size = (stat($fh))[7];
3034 ($size % 24) == 0 or croak "inconsistent size: $size";
3037 close $fh or croak "close: $!";
3038 return $want_commit ? (0, undef) : 0;
3041 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3042 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3043 my ($r, $c) = unpack(rev_map_fmt, $buf);
3044 if ($want_commit && $c eq ('0' x40)) {
3046 return $want_commit ? (0, undef) : 0;
3048 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3049 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3050 ($r, $c) = unpack(rev_map_fmt, $buf);
3051 if ($c eq ('0'x40)) {
3052 croak "Penultimate record is all-zeroes in $map_path";
3055 close $fh or croak "close: $!";
3056 $want_commit ? ($r, $c) : $r;
3060 my ($self, $rev, $uuid) = @_;
3061 my $map_path = $self->map_path($uuid);
3062 return undef unless -e $map_path;
3064 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3065 binmode $fh or croak "binmode: $!";
3066 my $size = (stat($fh))[7];
3067 ($size % 24) == 0 or croak "inconsistent size: $size";
3070 close $fh or croak "close: $fh";
3074 my ($l, $u) = (0, $size - 24);
3078 my $i = int(($l/24 + $u/24) / 2) * 24;
3079 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3080 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3081 my ($r, $c) = unpack('NH40', $buf);
3085 } elsif ($r > $rev) {
3087 } else { # $r == $rev
3088 close($fh) or croak "close: $!";
3089 return $c eq ('0' x 40) ? undef : $c;
3092 close($fh) or croak "close: $!";
3096 # Finds the first svn revision that exists on (if $eq_ok is true) or
3097 # before $rev for the current branch. It will not search any lower
3098 # than $min_rev. Returns the git commit hash and svn revision number
3099 # if found, else (undef, undef).
3100 sub find_rev_before {
3101 my ($self, $rev, $eq_ok, $min_rev) = @_;
3102 --$rev unless $eq_ok;
3104 while ($rev >= $min_rev) {
3105 if (my $c = $self->rev_map_get($rev)) {
3110 return (undef, undef);
3113 # Finds the first svn revision that exists on (if $eq_ok is true) or
3114 # after $rev for the current branch. It will not search any higher
3115 # than $max_rev. Returns the git commit hash and svn revision number
3116 # if found, else (undef, undef).
3117 sub find_rev_after {
3118 my ($self, $rev, $eq_ok, $max_rev) = @_;
3119 ++$rev unless $eq_ok;
3120 $max_rev ||= $self->rev_map_max;
3121 while ($rev <= $max_rev) {
3122 if (my $c = $self->rev_map_get($rev)) {
3127 return (undef, undef);
3131 my ($class, $repo_id, $ref_id, $path) = @_;
3132 unless (defined $repo_id && length $repo_id) {
3133 $repo_id = $Git::SVN::default_repo_id;
3135 unless (defined $ref_id && length $ref_id) {
3136 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3139 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3140 $_[3] = $path = '' unless (defined $path);
3141 mkpath(["$ENV{GIT_DIR}/svn"]);
3143 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3144 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3145 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3148 # for read-only access of old .rev_db formats
3149 sub unlink_rev_db_symlink {
3151 my $link = $self->rev_db_path;
3152 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3154 unlink $link or croak "unlink: $link failed!";
3159 my ($self, $uuid) = @_;
3160 my $db_path = $self->map_path($uuid);
3161 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3162 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3166 # the new replacement for .rev_db
3168 my ($self, $uuid) = @_;
3169 $uuid ||= $self->ra_uuid;
3170 "$self->{map_root}.$uuid";
3175 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3179 sub remove_username {
3180 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3183 package Git::SVN::Prompt;
3187 use vars qw/$_no_auth_cache $_username/;
3190 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3191 $may_save = undef if $_no_auth_cache;
3192 $default_username = $_username if defined $_username;
3193 if (defined $default_username && length $default_username) {
3194 if (defined $realm && length $realm) {
3195 print STDERR "Authentication realm: $realm\n";
3198 $cred->username($default_username);
3200 username($cred, $realm, $may_save, $pool);
3202 $cred->password(_read_password("Password for '" .
3203 $cred->username . "': ", $realm));
3204 $cred->may_save($may_save);
3205 $SVN::_Core::SVN_NO_ERROR;
3208 sub ssl_server_trust {
3209 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3210 $may_save = undef if $_no_auth_cache;
3211 print STDERR "Error validating server certificate for '$realm':\n";
3214 # All variables SVN::Auth::SSL::* are used only once,
3215 # so we're shutting up Perl warnings about this.
3216 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3217 print STDERR " - The certificate is not issued ",
3218 "by a trusted authority. Use the\n",
3219 " fingerprint to validate ",
3220 "the certificate manually!\n";
3222 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3223 print STDERR " - The certificate hostname ",
3224 "does not match.\n";
3226 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3227 print STDERR " - The certificate is not yet valid.\n";
3229 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3230 print STDERR " - The certificate has expired.\n";
3232 if ($failures & $SVN::Auth::SSL::OTHER) {
3233 print STDERR " - The certificate has ",
3234 "an unknown error.\n";
3236 } # no warnings 'once'
3238 "Certificate information:\n".
3239 " - Hostname: %s\n".
3240 " - Valid: from %s until %s\n".
3242 " - Fingerprint: %s\n",
3243 map $cert_info->$_, qw(hostname valid_from valid_until
3244 issuer_dname fingerprint);
3247 print STDERR $may_save ?
3248 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3249 "(R)eject or accept (t)emporarily? ";
3251 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3252 if ($choice =~ /^t$/i) {
3253 $cred->may_save(undef);
3254 } elsif ($choice =~ /^r$/i) {
3256 } elsif ($may_save && $choice =~ /^p$/i) {
3257 $cred->may_save($may_save);
3261 $cred->accepted_failures($failures);
3262 $SVN::_Core::SVN_NO_ERROR;
3265 sub ssl_client_cert {
3266 my ($cred, $realm, $may_save, $pool) = @_;
3267 $may_save = undef if $_no_auth_cache;
3268 print STDERR "Client certificate filename: ";
3270 chomp(my $filename = <STDIN>);
3271 $cred->cert_file($filename);
3272 $cred->may_save($may_save);
3273 $SVN::_Core::SVN_NO_ERROR;
3276 sub ssl_client_cert_pw {
3277 my ($cred, $realm, $may_save, $pool) = @_;
3278 $may_save = undef if $_no_auth_cache;
3279 $cred->password(_read_password("Password: ", $realm));
3280 $cred->may_save($may_save);
3281 $SVN::_Core::SVN_NO_ERROR;
3285 my ($cred, $realm, $may_save, $pool) = @_;
3286 $may_save = undef if $_no_auth_cache;
3287 if (defined $realm && length $realm) {
3288 print STDERR "Authentication realm: $realm\n";
3291 if (defined $_username) {
3292 $username = $_username;
3294 print STDERR "Username: ";
3296 chomp($username = <STDIN>);
3298 $cred->username($username);
3299 $cred->may_save($may_save);
3300 $SVN::_Core::SVN_NO_ERROR;
3303 sub _read_password {
3304 my ($prompt, $realm) = @_;
3305 print STDERR $prompt;
3307 require Term::ReadKey;
3308 Term::ReadKey::ReadMode('noecho');
3310 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3311 last if $key =~ /[\012\015]/; # \n\r
3314 Term::ReadKey::ReadMode('restore');
3320 package SVN::Git::Fetcher;
3325 use File::Temp qw/tempfile/;
3327 use vars qw/$_ignore_regex/;
3329 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3331 my ($class, $git_svn, $switch_path) = @_;
3332 my $self = SVN::Delta::Editor->new;
3333 bless $self, $class;
3334 if (exists $git_svn->{last_commit}) {
3335 $self->{c} = $git_svn->{last_commit};
3336 $self->{empty_symlinks} =
3337 _mark_empty_symlinks($git_svn, $switch_path);
3339 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3340 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3341 $self->{empty} = {};
3342 $self->{dir_prop} = {};
3343 $self->{file_prop} = {};
3344 $self->{absent_dir} = {};
3345 $self->{absent_file} = {};
3346 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3350 # this uses the Ra object, so it must be called before do_{switch,update},
3351 # not inside them (when the Git::SVN::Fetcher object is passed) to
3352 # do_{switch,update}
3353 sub _mark_empty_symlinks {
3354 my ($git_svn, $switch_path) = @_;
3355 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3356 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3359 my ($rev, $cmt) = $git_svn->last_rev_commit;
3360 return {} unless ($rev && $cmt);
3362 # allow the warning to be printed for each revision we fetch to
3363 # ensure the user sees it. The user can also disable the workaround
3364 # on the repository even while git svn is running and the next
3365 # revision fetched will skip this expensive function.
3366 my $printed_warning;
3367 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3368 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3370 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3371 $pfx .= '/' if length($pfx);
3374 s/\A100644 blob $empty_blob\t//o or next;
3375 unless ($printed_warning) {
3376 print STDERR "Scanning for empty symlinks, ",
3377 "this may take a while if you have ",
3378 "many empty files\n",
3379 "You may disable this with `",
3380 "git config svn.brokenSymlinkWorkaround ",
3382 "This may be done in a different ",
3383 "terminal without restarting ",
3385 $printed_warning = 1;
3388 my (undef, $props) =
3389 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3390 if ($props->{'svn:special'}) {
3394 command_close_pipe($ls, $ctx);
3398 # returns true if a given path is inside a ".git" directory
3400 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3403 # return value: 0 -- don't ignore, 1 -- ignore
3404 sub is_path_ignored {
3405 my ($self, $path) = @_;
3406 return 1 if in_dot_git($path);
3407 return 1 if defined($self->{ignore_regex}) &&
3408 $path =~ m!$self->{ignore_regex}!;
3409 return 0 unless defined($_ignore_regex);
3410 return 1 if $path =~ m!$_ignore_regex!o;
3414 sub set_path_strip {
3415 my ($self, $path) = @_;
3416 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3423 sub open_directory {
3424 my ($self, $path, $pb, $rev) = @_;
3429 my ($self, $path) = @_;
3430 if ($self->{path_strip}) {
3431 $path =~ s!$self->{path_strip}!! or
3432 die "Failed to strip path '$path' ($self->{path_strip})\n";
3438 my ($self, $path, $rev, $pb) = @_;
3439 return undef if $self->is_path_ignored($path);
3441 my $gpath = $self->git_path($path);
3442 return undef if ($gpath eq '');
3444 # remove entire directories.
3445 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3446 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3448 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3454 my $rmpath = "$gpath/$_";
3455 $self->{gii}->remove($rmpath);
3456 print "\tD\t$rmpath\n" unless $::_q;
3458 print "\tD\t$gpath/\n" unless $::_q;
3459 command_close_pipe($ls, $ctx);
3460 $self->{empty}->{$path} = 0
3462 $self->{gii}->remove($gpath);
3463 print "\tD\t$gpath\n" unless $::_q;
3469 my ($self, $path, $pb, $rev) = @_;
3472 goto out if $self->is_path_ignored($path);
3474 my $gpath = $self->git_path($path);
3475 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3476 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3477 unless (defined $mode && defined $blob) {
3478 die "$path was not found in commit $self->{c} (r$rev)\n";
3480 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3484 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3485 pool => SVN::Pool->new, action => 'M' };
3489 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3492 if (!$self->is_path_ignored($path)) {
3493 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3494 delete $self->{empty}->{$dir};
3497 { path => $path, mode_a => $mode, mode_b => $mode,
3498 pool => SVN::Pool->new, action => 'A' };
3502 my ($self, $path, $cp_path, $cp_rev) = @_;
3503 goto out if $self->is_path_ignored($path);
3504 my $gpath = $self->git_path($path);
3506 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3512 $self->{gii}->remove($_);
3513 print "\tD\t$_\n" unless $::_q;
3515 command_close_pipe($ls, $ctx);
3516 $self->{empty}->{$path} = 0;
3518 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3519 delete $self->{empty}->{$dir};
3520 $self->{empty}->{$path} = 1;
3525 sub change_dir_prop {
3526 my ($self, $db, $prop, $value) = @_;
3527 return undef if $self->is_path_ignored($db->{path});
3528 $self->{dir_prop}->{$db->{path}} ||= {};
3529 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3533 sub absent_directory {
3534 my ($self, $path, $pb) = @_;
3535 return undef if $self->is_path_ignored($path);
3536 $self->{absent_dir}->{$pb->{path}} ||= [];
3537 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3542 my ($self, $path, $pb) = @_;
3543 return undef if $self->is_path_ignored($path);
3544 $self->{absent_file}->{$pb->{path}} ||= [];
3545 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3549 sub change_file_prop {
3550 my ($self, $fb, $prop, $value) = @_;
3551 return undef if $self->is_path_ignored($fb->{path});
3552 if ($prop eq 'svn:executable') {
3553 if ($fb->{mode_b} != 120000) {
3554 $fb->{mode_b} = defined $value ? 100755 : 100644;
3556 } elsif ($prop eq 'svn:special') {
3557 $fb->{mode_b} = defined $value ? 120000 : 100644;
3559 $self->{file_prop}->{$fb->{path}} ||= {};
3560 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3565 sub apply_textdelta {
3566 my ($self, $fb, $exp) = @_;
3567 return undef if $self->is_path_ignored($fb->{path});
3568 my $fh = $::_repository->temp_acquire('svn_delta');
3569 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3570 # (but $base does not,) so dup() it for reading in close_file
3571 open my $dup, '<&', $fh or croak $!;
3572 my $base = $::_repository->temp_acquire('git_blob');
3575 my ($base_is_link, $size);
3577 if ($fb->{mode_a} eq '120000' &&
3578 ! $self->{empty_symlinks}->{$fb->{path}}) {
3579 print $base 'link ' or die "print $!\n";
3583 $size = $::_repository->cat_blob($fb->{blob}, $base);
3584 die "Failed to read object $fb->{blob}" if ($size < 0);
3587 seek $base, 0, 0 or croak $!;
3588 my $got = ::md5sum($base);
3590 my $err = "Checksum mismatch: ".
3591 "$fb->{path} $fb->{blob}\n" .
3592 "expected: $exp\n" .
3594 if ($base_is_link) {
3596 "Retrying... (possibly ",
3597 "a bad symlink from SVN)\n";
3598 $::_repository->temp_reset($base);
3606 seek $base, 0, 0 or croak $!;
3608 $fb->{base} = $base;
3609 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3613 my ($self, $fb, $exp) = @_;
3614 return undef if $self->is_path_ignored($fb->{path});
3617 my $path = $self->git_path($fb->{path});
3618 if (my $fh = $fb->{fh}) {
3620 seek($fh, 0, 0) or croak $!;
3621 my $got = ::md5sum($fh);
3623 die "Checksum mismatch: $path\n",
3624 "expected: $exp\n got: $got\n";
3627 if ($fb->{mode_b} == 120000) {
3628 sysseek($fh, 0, 0) or croak $!;
3629 my $rd = sysread($fh, my $buf, 5);
3632 croak "sysread: $!\n";
3633 } elsif ($rd == 0) {
3634 warn "$path has mode 120000",
3635 " but it points to nothing\n",
3636 "converting to an empty file with mode",
3638 $fb->{mode_b} = '100644';
3639 } elsif ($buf ne 'link ') {
3640 warn "$path has mode 120000",
3641 " but is not a link\n";
3643 my $tmp_fh = $::_repository->temp_acquire(
3646 while ($res = sysread($fh, my $str, 1024)) {
3647 my $out = syswrite($tmp_fh, $str, $res);
3648 defined($out) && $out == $res
3650 Git::temp_path($tmp_fh),
3653 defined $res or croak $!;
3655 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3656 Git::temp_release($tmp_fh, 1);
3660 $hash = $::_repository->hash_and_insert_object(
3661 Git::temp_path($fh));
3662 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3664 Git::temp_release($fb->{base}, 1);
3665 Git::temp_release($fh, 1);
3667 $hash = $fb->{blob} or die "no blob information\n";
3670 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3671 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3677 $self->{nr} = $self->{gii}->{nr};
3678 delete $self->{gii};
3679 $self->SUPER::abort_edit(@_);
3684 $self->{git_commit_ok} = 1;
3685 $self->{nr} = $self->{gii}->{nr};
3686 delete $self->{gii};
3687 $self->SUPER::close_edit(@_);
3690 package SVN::Git::Editor;
3691 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3698 my ($class, $opts) = @_;
3699 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3700 die "$_ required!\n" unless (defined $opts->{$_});
3703 my $pool = SVN::Pool->new;
3704 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3705 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3708 # $opts->{ra} functions should not be used after this:
3709 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3710 $opts->{editor_cb}, $pool);
3711 my $self = SVN::Delta::Editor->new(@ce, $pool);
3712 bless $self, $class;
3713 foreach (qw/svn_path r tree_a tree_b/) {
3714 $self->{$_} = $opts->{$_};
3716 $self->{url} = $opts->{ra}->{url};
3717 $self->{mods} = $mods;
3718 $self->{types} = $types;
3719 $self->{pool} = $pool;
3720 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3722 $self->{path_prefix} = length $self->{svn_path} ?
3723 "$self->{svn_path}/" : '';
3724 $self->{config} = $opts->{config};
3729 my ($tree_a, $tree_b) = @_;
3730 my @diff_tree = qw(diff-tree -z -r);
3731 if ($_cp_similarity) {
3732 push @diff_tree, "-C$_cp_similarity";
3734 push @diff_tree, '-C';
3736 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3737 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3738 push @diff_tree, $tree_a, $tree_b;
3739 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3743 while (<$diff_fh>) {
3744 chomp $_; # this gets rid of the trailing "\0"
3745 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3746 ($::sha1)\s($::sha1)\s
3747 ([MTCRAD])\d*$/xo) {
3748 push @mods, { mode_a => $1, mode_b => $2,
3749 sha1_a => $3, sha1_b => $4,
3751 if ($5 =~ /^(?:C|R)$/) {
3756 } elsif ($state eq 'file_a') {
3757 my $x = $mods[$#mods] or croak "Empty array\n";
3758 if ($x->{chg} !~ /^(?:C|R)$/) {
3759 croak "Error parsing $_, $x->{chg}\n";
3763 } elsif ($state eq 'file_b') {
3764 my $x = $mods[$#mods] or croak "Empty array\n";
3765 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3766 croak "Error parsing $_, $x->{chg}\n";
3768 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3769 croak "Error parsing $_, $x->{chg}\n";
3774 croak "Error parsing $_\n";
3777 command_close_pipe($diff_fh, $ctx);
3781 sub check_diff_paths {
3782 my ($ra, $pfx, $rev, $mods) = @_;
3784 $pfx .= '/' if length $pfx;
3786 sub type_diff_paths {
3787 my ($ra, $types, $path, $rev) = @_;
3788 my @p = split m#/+#, $path;
3790 unless (defined $types->{$c}) {
3791 $types->{$c} = $ra->check_path($c, $rev);
3794 $c .= '/' . shift @p;
3795 next if defined $types->{$c};
3796 $types->{$c} = $ra->check_path($c, $rev);
3800 foreach my $m (@$mods) {
3801 foreach my $f (qw/file_a file_b/) {
3802 next unless defined $m->{$f};
3803 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3804 if (length $pfx.$dir && ! defined $types{$dir}) {
3805 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3813 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3817 my ($self, $path) = @_;
3818 $self->{path_prefix}.(defined $path ? $path : '');
3822 my ($self, $path) = @_;
3823 if ($self->{url} =~ m#^https?://#) {
3824 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3826 $self->{url} . '/' . $self->repo_path($path);
3831 my $rm = $self->{rm};
3832 delete $rm->{''}; # we never delete the url we're tracking
3835 foreach (keys %$rm) {
3836 my @d = split m#/#, $_;
3840 $c .= '/' . shift @d;
3844 delete $rm->{$self->{svn_path}};
3845 delete $rm->{''}; # we never delete the url we're tracking
3848 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3853 my @dn = split m#/#, $_;
3855 delete $rm->{join '/', @dn};
3862 command_close_pipe($fh, $ctx);
3864 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3865 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3866 $self->close_directory($bat->{$d}, $p);
3867 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3868 print "\tD+\t$d/\n" unless $::_q;
3869 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3874 sub open_or_add_dir {
3875 my ($self, $full_path, $baton) = @_;
3876 my $t = $self->{types}->{$full_path};
3878 die "$full_path not known in r$self->{r} or we have a bug!\n";
3882 # SVN::Node::none and SVN::Node::file are used only once,
3883 # so we're shutting up Perl's warnings about them.
3884 if ($t == $SVN::Node::none) {
3885 return $self->add_directory($full_path, $baton,
3886 undef, -1, $self->{pool});
3887 } elsif ($t == $SVN::Node::dir) {
3888 return $self->open_directory($full_path, $baton,
3889 $self->{r}, $self->{pool});
3890 } # no warnings 'once'
3891 print STDERR "$full_path already exists in repository at ",
3892 "r$self->{r} and it is not a directory (",
3893 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3894 } # no warnings 'once'
3899 my ($self, $path) = @_;
3900 my $bat = $self->{bat};
3901 my $repo_path = $self->repo_path($path);
3902 return $bat->{''} unless (length $repo_path);
3903 my @p = split m#/+#, $repo_path;
3905 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3908 $c .= '/' . shift @p;
3909 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3914 # Subroutine to convert a globbing pattern to a regular expression.
3915 # From perl cookbook.
3917 my $globstr = shift;
3918 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3919 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3920 return '^' . $globstr . '$';
3923 sub check_autoprop {
3924 my ($self, $pattern, $properties, $file, $fbat) = @_;
3925 # Convert the globbing pattern to a regular expression.
3926 my $regex = glob2pat($pattern);
3927 # Check if the pattern matches the file name.
3928 if($file =~ m/($regex)/) {
3929 # Parse the list of properties to set.
3930 my @props = split(/;/, $properties);
3931 foreach my $prop (@props) {
3932 # Parse 'name=value' syntax and set the property.
3933 if ($prop =~ /([^=]+)=(.*)/) {
3934 my ($n,$v) = ($1,$2);
3938 $self->change_file_prop($fbat, $n, $v);
3944 sub apply_autoprops {
3945 my ($self, $file, $fbat) = @_;
3946 my $conf_t = ${$self->{config}}{'config'};
3948 # Check [miscellany]/enable-auto-props in svn configuration.
3949 if (SVN::_Core::svn_config_get_bool(
3951 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3952 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3954 # Auto-props are enabled. Enumerate them to look for matches.
3955 my $callback = sub {
3956 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3958 SVN::_Core::svn_config_enumerate(
3960 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3966 my ($self, $m) = @_;
3967 my ($dir, $file) = split_path($m->{file_b});
3968 my $pbat = $self->ensure_path($dir);
3969 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3971 print "\tA\t$m->{file_b}\n" unless $::_q;
3972 $self->apply_autoprops($file, $fbat);
3973 $self->chg_file($fbat, $m);
3974 $self->close_file($fbat,undef,$self->{pool});
3978 my ($self, $m) = @_;
3979 my ($dir, $file) = split_path($m->{file_b});
3980 my $pbat = $self->ensure_path($dir);
3981 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3982 $self->url_path($m->{file_a}), $self->{r});
3983 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3984 $self->chg_file($fbat, $m);
3985 $self->close_file($fbat,undef,$self->{pool});
3989 my ($self, $path, $pbat) = @_;
3990 my $rpath = $self->repo_path($path);
3991 my ($dir, $file) = split_path($rpath);
3992 $self->{rm}->{$dir} = 1;
3993 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3997 my ($self, $m) = @_;
3998 my ($dir, $file) = split_path($m->{file_b});
3999 my $pbat = $self->ensure_path($dir);
4000 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4001 $self->url_path($m->{file_a}), $self->{r});
4002 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4003 $self->apply_autoprops($file, $fbat);
4004 $self->chg_file($fbat, $m);
4005 $self->close_file($fbat,undef,$self->{pool});
4007 ($dir, $file) = split_path($m->{file_a});
4008 $pbat = $self->ensure_path($dir);
4009 $self->delete_entry($m->{file_a}, $pbat);
4013 my ($self, $m) = @_;
4014 my ($dir, $file) = split_path($m->{file_b});
4015 my $pbat = $self->ensure_path($dir);
4016 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4017 $pbat,$self->{r},$self->{pool});
4018 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4019 $self->chg_file($fbat, $m);
4020 $self->close_file($fbat,undef,$self->{pool});
4023 sub T { shift->M(@_) }
4025 sub change_file_prop {
4026 my ($self, $fbat, $pname, $pval) = @_;
4027 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4030 sub _chg_file_get_blob ($$$$) {
4031 my ($self, $fbat, $m, $which) = @_;
4032 my $fh = $::_repository->temp_acquire("git_blob_$which");
4033 if ($m->{"mode_$which"} =~ /^120/) {
4034 print $fh 'link ' or croak $!;
4035 $self->change_file_prop($fbat,'svn:special','*');
4036 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4037 $self->change_file_prop($fbat,'svn:special',undef);
4039 my $blob = $m->{"sha1_$which"};
4040 return ($fh,) if ($blob =~ /^0{40}$/);
4041 my $size = $::_repository->cat_blob($blob, $fh);
4042 croak "Failed to read object $blob" if ($size < 0);
4043 $fh->flush == 0 or croak $!;
4044 seek $fh, 0, 0 or croak $!;
4046 my $exp = ::md5sum($fh);
4047 seek $fh, 0, 0 or croak $!;
4052 my ($self, $fbat, $m) = @_;
4053 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4054 $self->change_file_prop($fbat,'svn:executable','*');
4055 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4056 $self->change_file_prop($fbat,'svn:executable',undef);
4058 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4059 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4060 my $pool = SVN::Pool->new;
4061 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4063 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4064 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4066 die "Unexpected result from send_txstream: $res\n",
4067 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4070 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4071 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4072 if ($got ne $exp_b);
4074 Git::temp_release($fh_b, 1);
4075 Git::temp_release($fh_a, 1);
4080 my ($self, $m) = @_;
4081 my ($dir, $file) = split_path($m->{file_b});
4082 my $pbat = $self->ensure_path($dir);
4083 print "\tD\t$m->{file_b}\n" unless $::_q;
4084 $self->delete_entry($m->{file_b}, $pbat);
4089 my ($p,$bat) = ($self->{pool}, $self->{bat});
4090 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4092 $self->close_directory($bat->{$_}, $p);
4094 $self->close_directory($bat->{''}, $p);
4095 $self->SUPER::close_edit($p);
4101 $self->SUPER::abort_edit($self->{pool});
4106 $self->SUPER::DESTROY(@_);
4107 $self->{pool}->clear;
4110 # this drives the editor
4113 my $mods = $self->{mods};
4114 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4115 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4117 if (defined $o{$f}) {
4120 fatal("Invalid change type: $f");
4123 $self->rmdirs if $_rmdir;
4129 return scalar @$mods;
4132 package Git::SVN::Ra;
4133 use vars qw/@ISA $config_dir $_log_window_size/;
4136 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4139 # enforce temporary pool usage for some simple functions
4141 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4143 my $SUPER = "SUPER::$f";
4146 my $pool = SVN::Pool->new;
4147 my @ret = $self->$SUPER(@_,$pool);
4149 wantarray ? @ret : $ret[0];
4154 sub _auth_providers () {
4156 SVN::Client::get_simple_provider(),
4157 SVN::Client::get_ssl_server_trust_file_provider(),
4158 SVN::Client::get_simple_prompt_provider(
4159 \&Git::SVN::Prompt::simple, 2),
4160 SVN::Client::get_ssl_client_cert_file_provider(),
4161 SVN::Client::get_ssl_client_cert_prompt_provider(
4162 \&Git::SVN::Prompt::ssl_client_cert, 2),
4163 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4164 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4165 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4166 SVN::Client::get_username_provider(),
4167 SVN::Client::get_ssl_server_trust_prompt_provider(
4168 \&Git::SVN::Prompt::ssl_server_trust),
4169 SVN::Client::get_username_prompt_provider(
4170 \&Git::SVN::Prompt::username, 2)
4174 sub escape_uri_only {
4177 foreach (split m{/}, $uri) {
4178 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4186 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4187 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4188 $url = "$scheme://$domain$uri";
4194 my ($class, $url) = @_;
4196 return $RA if ($RA && $RA->{url} eq $url);
4198 SVN::_Core::svn_config_ensure($config_dir, undef);
4199 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4200 my $config = SVN::Core::config_get_config($config_dir);
4202 my $dont_store_passwords = 1;
4203 my $conf_t = ${$config}{'config'};
4206 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4207 # produces warnings that variables are used only once.
4208 # I had not found the better way to shut them up, so
4209 # the warnings of type 'once' are disabled in this block.
4210 if (SVN::_Core::svn_config_get_bool($conf_t,
4211 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4212 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4214 SVN::_Core::svn_auth_set_parameter($baton,
4215 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4216 bless (\$dont_store_passwords, "_p_void"));
4218 if (SVN::_Core::svn_config_get_bool($conf_t,
4219 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4220 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4222 $Git::SVN::Prompt::_no_auth_cache = 1;
4224 } # no warnings 'once'
4225 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4227 pool => SVN::Pool->new,
4228 auth_provider_callbacks => $callbacks);
4229 $self->{url} = $url;
4230 $self->{svn_path} = $url;
4231 $self->{repos_root} = $self->get_repos_root;
4232 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4233 $self->{cache} = { check_path => { r => 0, data => {} },
4234 get_dir => { r => 0, data => {} } };
4235 $RA = bless $self, $class;
4239 my ($self, $path, $r) = @_;
4240 my $cache = $self->{cache}->{check_path};
4241 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4242 return $cache->{data}->{$path};
4244 my $pool = SVN::Pool->new;
4245 my $t = $self->SUPER::check_path($path, $r, $pool);
4247 if ($r != $cache->{r}) {
4248 %{$cache->{data}} = ();
4251 $cache->{data}->{$path} = $t;
4255 my ($self, $dir, $r) = @_;
4256 my $cache = $self->{cache}->{get_dir};
4257 if ($r == $cache->{r}) {
4258 if (my $x = $cache->{data}->{$dir}) {
4259 return wantarray ? @$x : $x->[0];
4262 my $pool = SVN::Pool->new;
4263 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4264 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4266 if ($r != $cache->{r}) {
4267 %{$cache->{data}} = ();
4270 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4271 wantarray ? (\%dirents, $r, $props) : \%dirents;
4275 # do not call the real DESTROY since we store ourselves in $RA
4278 # get_log(paths, start, end, limit,
4279 # discover_changed_paths, strict_node_history, receiver)
4281 my ($self, @args) = @_;
4282 my $pool = SVN::Pool->new;
4284 # the limit parameter was not supported in SVN 1.1.x, so we
4285 # drop it. Therefore, the receiver callback passed to it
4286 # is made aware of this limitation by being wrapped if
4287 # the limit passed to is being wrapped.
4288 if ($SVN::Core::VERSION le '1.2.0') {
4289 my $limit = splice(@args, 3, 1);
4291 my $receiver = pop @args;
4292 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4295 my $ret = $self->SUPER::get_log(@args, $pool);
4301 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4302 my $ctx = SVN::Client->new(auth => _auth_providers);
4303 my $out = IO::File->new_tmpfile;
4305 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4306 # $ctx->diff(), so we'll create a default one
4307 my $pool = SVN::Pool->new_default_sub;
4309 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4310 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4312 my $ret = (($out->stat)[7] == 0);
4313 close $out or croak $!;
4318 sub get_commit_editor {
4319 my ($self, $log, $cb, $pool) = @_;
4320 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4321 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4325 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4326 my $new = ($rev_a == $rev_b);
4327 my $path = $gs->{path};
4329 if ($new && -e $gs->{index}) {
4330 unlink $gs->{index} or die
4331 "Couldn't unlink index: $gs->{index}: $!\n";
4333 my $pool = SVN::Pool->new;
4334 $editor->set_path_strip($path);
4335 my (@pc) = split m#/#, $path;
4336 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4338 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4340 # Since we can't rely on svn_ra_reparent being available, we'll
4341 # just have to do some magic with set_path to make it so
4342 # we only want a partial path.
4344 my $final = join('/', @pc);
4346 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4347 $sp .= '/' if length $sp;
4350 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4352 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4354 $reporter->finish_report($pool);
4356 $editor->{git_commit_ok};
4359 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4360 # svn_ra_reparent didn't work before 1.4)
4362 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4363 my $path = $gs->{path};
4364 my $pool = SVN::Pool->new;
4366 my $full_url = $self->{url};
4367 my $old_url = $full_url;
4368 $full_url .= '/' . escape_uri_only($path) if length $path;
4369 my ($ra, $reparented);
4371 if ($old_url =~ m#^svn(\+ssh)?://#) {
4375 $ra = Git::SVN::Ra->new($full_url);
4377 } elsif ($old_url ne $full_url) {
4378 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4379 $self->{url} = $full_url;
4384 $url_b = escape_url($url_b);
4385 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4386 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4387 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4388 $reporter->finish_report($pool);
4391 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4392 $self->{url} = $old_url;
4396 $editor->{git_commit_ok};
4399 sub longest_common_path {
4400 my ($gsv, $globs) = @_;
4402 my $common_max = scalar @$gsv;
4404 foreach my $gs (@$gsv) {
4405 my @tmp = split m#/#, $gs->{path};
4408 $p .= length($p) ? "/$_" : $_;
4414 $common_max += scalar @$globs;
4415 foreach my $glob (@$globs) {
4416 my @tmp = split m#/#, $glob->{path}->{left};
4419 $p .= length($p) ? "/$_" : $_;
4425 my $longest_path = '';
4426 foreach (sort {length $b <=> length $a} keys %common) {
4427 if ($common{$_} == $common_max) {
4435 sub gs_fetch_loop_common {
4436 my ($self, $base, $head, $gsv, $globs) = @_;
4437 return if ($base > $head);
4438 my $inc = $_log_window_size;
4439 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4440 my $longest_path = longest_common_path($gsv, $globs);
4441 my $ra_url = $self->{url};
4442 my $find_trailing_edge;
4446 my $err_handler = $SVN::Error::handler;
4447 $SVN::Error::handler = sub {
4449 skip_unknown_revs($err);
4452 my ($paths, $r, $author, $date, $log) = @_;
4453 [ dup_changed_paths($paths),
4454 { author => $author, date => $date, log => $log } ];
4456 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4457 sub { $revs{$_[1]} = _cb(@_) });
4459 print "Checked through r$max\r";
4461 $find_trailing_edge = 1;
4463 if ($err and $find_trailing_edge) {
4464 print STDERR "Path '$longest_path' ",
4465 "was probably deleted:\n",
4466 $err->expanded_message,
4467 "\nWill attempt to follow ",
4468 "revisions r$min .. r$max ",
4469 "committed before the deletion\n";
4471 while (--$hi >= $min) {
4473 $self->get_log([$longest_path], $min, $hi,
4476 $revs{$_[1]} = _cb(@_) });
4478 print STDERR "r$min .. r$ok OK\n";
4482 $find_trailing_edge = 0;
4484 $SVN::Error::handler = $err_handler;
4486 my %exists = map { $_->{path} => $_ } @$gsv;
4487 foreach my $r (sort {$a <=> $b} keys %revs) {
4488 my ($paths, $logged) = @{$revs{$r}};
4490 foreach my $gs ($self->match_globs(\%exists, $paths,
4492 if ($gs->rev_map_max >= $r) {
4495 next unless $gs->match_paths($paths, $r);
4496 $gs->{logged_rev_props} = $logged;
4497 if (my $last_commit = $gs->last_commit) {
4498 $gs->assert_index_clean($last_commit);
4500 my $log_entry = $gs->do_fetch($paths, $r);
4502 $gs->do_git_commit($log_entry);
4504 $INDEX_FILES{$gs->{index}} = 1;
4506 foreach my $g (@$globs) {
4507 my $k = "svn-remote.$g->{remote}." .
4509 Git::SVN::tmp_config($k, $r);
4515 $self = Git::SVN::Ra->new($ra_url);
4516 $ra_invalid = undef;
4519 # pre-fill the .rev_db since it'll eventually get filled in
4520 # with '0' x40 if something new gets committed
4521 foreach my $gs (@$gsv) {
4522 next if $gs->rev_map_max >= $max;
4523 next if defined $gs->rev_map_get($max);
4524 $gs->rev_map_set($max, 0 x40);
4526 foreach my $g (@$globs) {
4527 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4528 Git::SVN::tmp_config($k, $max);
4530 last if $max >= $head;
4533 $max = $head if ($max > $head);
4538 sub get_dir_globbed {
4539 my ($self, $left, $depth, $r) = @_;
4541 my @x = eval { $self->get_dir($left, $r) };
4542 return unless scalar @x == 3;
4543 my $dirents = $x[0];
4545 foreach my $de (keys %$dirents) {
4546 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4548 my @args = ("$left/$de", $depth - 1, $r);
4549 foreach my $dir ($self->get_dir_globbed(@args)) {
4550 push @finalents, "$de/$dir";
4553 push @finalents, $de;
4560 my ($self, $exists, $paths, $globs, $r) = @_;
4563 my ($self, $exists, $g, $r) = @_;
4565 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4566 $g->{path}->{depth},
4569 foreach my $de (@dirs) {
4570 my $p = $g->{path}->full_path($de);
4571 next if $exists->{$p};
4572 next if (length $g->{path}->{right} &&
4573 ($self->check_path($p, $r) !=
4575 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4576 $g->{ref}->full_path($de), 1);
4579 foreach my $g (@$globs) {
4580 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4581 if ($path->{action} =~ /^[AR]$/) {
4582 get_dir_check($self, $exists, $g, $r);
4585 foreach (keys %$paths) {
4586 if (/$g->{path}->{left_regex}/ &&
4587 !/$g->{path}->{regex}/) {
4588 next if $paths->{$_}->{action} !~ /^[AR]$/;
4589 get_dir_check($self, $exists, $g, $r);
4591 next unless /$g->{path}->{regex}/;
4593 my $pathname = $g->{path}->full_path($p);
4594 next if $exists->{$pathname};
4595 next if ($self->check_path($pathname, $r) !=
4597 $exists->{$pathname} = Git::SVN->init(
4598 $self->{url}, $pathname, undef,
4599 $g->{ref}->full_path($p), 1);
4602 foreach (split m#/#, $g->{path}->{left}) {
4604 next unless ($paths->{$c} &&
4605 ($paths->{$c}->{action} =~ /^[AR]$/));
4606 get_dir_check($self, $exists, $g, $r);
4614 return $self->{url} if ($self->{url} eq $self->{repos_root});
4615 my $url = $self->{repos_root};
4616 my @components = split(m!/!, $self->{svn_path});
4619 $url .= "/$c" if length $c;
4620 eval { (ref $self)->new($url)->get_latest_revnum };
4621 } while ($@ && ($c = shift @components));
4627 unless (defined $can_do_switch) {
4628 my $pool = SVN::Pool->new;
4630 $self->do_switch(1, '', 0, $self->{url},
4631 SVN::Delta::Editor->new, $pool);
4636 $rep->abort_report($pool);
4644 sub skip_unknown_revs {
4646 my $errno = $err->apr_err();
4647 # Maybe the branch we're tracking didn't
4648 # exist when the repo started, so it's
4649 # not an error if it doesn't, just continue
4651 # Wonderfully consistent library, eh?
4652 # 160013 - svn:// and file://
4653 # 175002 - http(s)://
4654 # 175007 - http(s):// (this repo required authorization, too...)
4655 # More codes may be discovered later...
4656 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4657 my $err_key = $err->expanded_message;
4658 # revision numbers change every time, filter them out
4659 $err_key =~ s/\d+/\0/g;
4660 $err_key = "$errno\0$err_key";
4661 unless ($ignored_err{$err_key}) {
4662 warn "W: Ignoring error from SVN, path probably ",
4663 "does not exist: ($errno): ",
4664 $err->expanded_message,"\n";
4665 warn "W: Do not be alarmed at the above message ",
4666 "git-svn is just searching aggressively for ",
4668 "This may take a while on large repositories\n";
4669 $ignored_err{$err_key} = 1;
4673 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4676 # svn_log_changed_path_t objects passed to get_log are likely to be
4677 # overwritten even if only the refs are copied to an external variable,
4678 # so we should dup the structures in their entirety. Using an externally
4679 # passed pool (instead of our temporary and quickly cleared pool in
4680 # Git::SVN::Ra) does not help matters at all...
4681 sub dup_changed_paths {
4683 return undef unless $paths;
4685 foreach my $p (keys %$paths) {
4686 my $i = $paths->{$p};
4687 my %s = map { $_ => $i->$_ }
4688 qw/copyfrom_path copyfrom_rev action/;
4694 package Git::SVN::Log;
4697 use POSIX qw/strftime/;
4699 use constant commit_log_separator => ('-' x 72) . "\n";
4700 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4701 %rusers $show_commit $incremental/;
4706 return 1 if defined $c->{r};
4708 # big commit message got truncated by the 16k pretty buffer in rev-list
4709 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4710 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4712 my @log = command(qw/cat-file commit/, $c->{c});
4714 # shift off the headers
4715 shift @log while ($log[0] ne '');
4718 # TODO: make $c->{l} not have a trailing newline in the future
4719 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4721 (undef, $c->{r}, undef) = ::extract_metadata(
4722 (grep(/^git-svn-id: /, @log))[-1]);
4724 return defined $c->{r};
4728 return $color || Git->repository->get_colorbool('color.diff');
4731 sub git_svn_log_cmd {
4732 my ($r_min, $r_max, @args) = @_;
4734 my (@files, @log_opts);
4735 foreach my $x (@args) {
4736 if ($x eq '--' || @files) {
4739 if (::verify_ref("$x^0")) {
4747 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4748 $gs ||= Git::SVN->_new;
4749 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4751 push @cmd, '-r' unless $non_recursive;
4752 push @cmd, qw/--raw --name-status/ if $verbose;
4753 push @cmd, '--color' if log_use_color();
4754 push @cmd, @log_opts;
4755 if (defined $r_max && $r_max == $r_min) {
4756 push @cmd, '--max-count=1';
4757 if (my $c = $gs->rev_map_get($r_max)) {
4760 } elsif (defined $r_max) {
4761 if ($r_max < $r_min) {
4762 ($r_min, $r_max) = ($r_max, $r_min);
4764 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4765 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4766 # If there are no commits in the range, both $c_max and $c_min
4767 # will be undefined. If there is at least 1 commit in the
4768 # range, both will be defined.
4769 return () if !defined $c_min || !defined $c_max;
4770 if ($c_min eq $c_max) {
4771 push @cmd, '--max-count=1', $c_min;
4773 push @cmd, '--boundary', "$c_min..$c_max";
4776 return (@cmd, @files);
4779 # adapted from pager.c
4781 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4782 if (!defined $pager) {
4784 } elsif (length $pager == 0 || $pager eq 'cat') {
4787 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4791 return unless -t *STDOUT && defined $pager;
4792 pipe my ($rfd, $wfd) or return;
4793 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4795 open STDOUT, '>&', $wfd or
4796 ::fatal "Can't redirect to stdout: $!";
4799 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4800 $ENV{LESS} ||= 'FRSX';
4801 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4804 sub format_svn_date {
4805 # some systmes don't handle or mishandle %z, so be creative.
4806 my $t = shift || time;
4807 my $gm = timelocal(gmtime($t));
4808 my $sign = qw( + + - )[ $t <=> $gm ];
4809 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4810 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4813 sub parse_git_date {
4815 # Date::Parse isn't in the standard Perl distro :(
4816 if ($tz =~ s/^\+//) {
4817 $t += tz_to_s_offset($tz);
4818 } elsif ($tz =~ s/^\-//) {
4819 $t -= tz_to_s_offset($tz);
4824 sub set_local_timezone {
4832 sub tz_to_s_offset {
4835 return ($1 * 60) + ($tz * 3600);
4838 sub get_author_info {
4839 my ($dest, $author, $t, $tz) = @_;
4840 $author =~ s/(?:^\s*|\s*$)//g;
4841 $dest->{a_raw} = $author;
4844 $au = $rusers{$author} || undef;
4847 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4852 $dest->{t_utc} = parse_git_date($t, $tz);
4855 sub process_commit {
4856 my ($c, $r_min, $r_max, $defer) = @_;
4857 if (defined $r_min && defined $r_max) {
4858 if ($r_min == $c->{r} && $r_min == $r_max) {
4862 return 1 if $r_min == $r_max;
4863 if ($r_min < $r_max) {
4864 # we need to reverse the print order
4865 return 0 if (defined $limit && --$limit < 0);
4869 if ($r_min != $r_max) {
4870 return 1 if ($r_min < $c->{r});
4871 return 1 if ($r_max > $c->{r});
4874 return 0 if (defined $limit && --$limit < 0);
4883 if (my $l = $c->{l}) {
4884 while ($l->[0] =~ /^\s*$/) { shift @$l }
4887 $l_fmt ||= 'A' . length($c->{r});
4888 print 'r',pack($l_fmt, $c->{r}),' | ';
4889 print "$c->{c} | " if $show_commit;
4892 show_commit_normal($c);
4896 sub show_commit_changed_paths {
4898 return unless $c->{changed};
4899 print "Changed paths:\n", @{$c->{changed}};
4902 sub show_commit_normal {
4904 print commit_log_separator, "r$c->{r} | ";
4905 print "$c->{c} | " if $show_commit;
4906 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4909 if (my $l = $c->{l}) {
4910 while ($l->[$#$l] eq "\n" && $#$l > 0
4911 && $l->[($#$l - 1)] eq "\n") {
4914 $nr_line = scalar @$l;
4916 print "1 line\n\n\n";
4918 if ($nr_line == 1) {
4919 $nr_line = '1 line';
4921 $nr_line .= ' lines';
4923 print $nr_line, "\n";
4924 show_commit_changed_paths($c);
4926 print $_ foreach @$l;
4930 show_commit_changed_paths($c);
4934 foreach my $x (qw/raw stat diff/) {
4937 print $_ foreach @{$c->{$x}}
4944 my ($r_min, $r_max);
4945 my $r_last = -1; # prevent dupes
4946 set_local_timezone();
4947 if (defined $::_revision) {
4948 if ($::_revision =~ /^(\d+):(\d+)$/) {
4949 ($r_min, $r_max) = ($1, $2);
4950 } elsif ($::_revision =~ /^\d+$/) {
4951 $r_min = $r_max = $::_revision;
4953 ::fatal "-r$::_revision is not supported, use ",
4954 "standard 'git log' arguments instead";
4959 @args = git_svn_log_cmd($r_min, $r_max, @args);
4961 print commit_log_separator unless $incremental || $oneline;
4964 my $log = command_output_pipe(@args);
4966 my (@k, $c, $d, $stat);
4967 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4969 if (/^${esc_color}commit -?($::sha1_short)/o) {
4971 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4973 process_commit($c, $r_min, $r_max, \@k) or
4978 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4979 get_author_info($c, $1, $2, $3);
4980 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4982 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4983 push @{$c->{raw}}, $_;
4984 } elsif (/^${esc_color}[ACRMDT]\t/) {
4985 # we could add $SVN->{svn_path} here, but that requires
4986 # remote access at the moment (repo_path_split)...
4987 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4988 push @{$c->{changed}}, $_;
4989 } elsif (/^${esc_color}diff /o) {
4991 push @{$c->{diff}}, $_;
4993 push @{$c->{diff}}, $_;
4994 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4995 $esc_color*[\+\-]*$esc_color$/x) {
4997 push @{$c->{stat}}, $_;
4998 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4999 push @{$c->{stat}}, $_;
5001 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5002 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5003 } elsif (s/^${esc_color} //o) {
5004 push @{$c->{l}}, $_;
5007 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5009 process_commit($c, $r_min, $r_max, \@k);
5012 ($r_min, $r_max) = ($r_max, $r_min);
5013 process_commit($_, $r_min, $r_max) foreach reverse @k;
5017 print commit_log_separator unless $incremental || $oneline;
5026 my ($fh, $ctx, $rev);
5029 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5030 while (my $line = <$fh>) {
5031 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5032 # Uncommitted edits show up as a rev ID of
5033 # all zeros, which we can't look up with
5036 (undef, $rev, undef) =
5038 $rev = '0' if (!$rev);
5042 $rev = sprintf('%-10s', $rev);
5043 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5048 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5053 my %dsha; #distinct sha keys
5055 while (my $line = <$fh>) {
5056 push @buffer, $line;
5057 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5062 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5064 foreach my $line (@buffer) {
5065 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5067 $rev = '0' if (!$rev)
5069 elsif ($line =~ /^author (.*)/) {
5070 $authors{$rev} = $1;
5071 $authors{$rev} =~ s/\s/_/g;
5073 elsif ($line =~ /^\t(.*)$/) {
5074 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5078 command_close_pipe($fh, $ctx);
5081 package Git::SVN::Migration;
5082 # these version numbers do NOT correspond to actual version numbers
5083 # of git nor git-svn. They are just relative.
5085 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5087 # v1 layout: .git/$id/info/url, refs/remotes/$id
5089 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5091 # v3 layout: .git/svn/$id, refs/remotes/$id
5092 # - info/url may remain for backwards compatibility
5093 # - this is what we migrate up to this layout automatically,
5094 # - this will be used by git svn init on single branches
5095 # v3.1 layout (auto migrated):
5096 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5097 # for backwards compatibility
5099 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5100 # - this is only created for newly multi-init-ed
5101 # repositories. Similar in spirit to the
5102 # --use-separate-remotes option in git-clone (now default)
5103 # - we do not automatically migrate to this (following
5104 # the example set by core git)
5106 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5107 # - newer, more-efficient format that uses 24-bytes per record
5108 # with no filler space.
5109 # - use xxd -c24 < .rev_map.$UUID to view and debug
5110 # - This is a one-way migration, repositories updated to the
5111 # new format will not be able to use old git-svn without
5112 # rebuilding the .rev_db. Rebuilding the rev_db is not
5113 # possible if noMetadata or useSvmProps are set; but should
5114 # be no problem for users that use the (sensible) defaults.
5118 use File::Path qw/mkpath/;
5119 use File::Basename qw/dirname basename/;
5120 use vars qw/$_minimize/;
5122 sub migrate_from_v0 {
5123 my $git_dir = $ENV{GIT_DIR};
5124 return undef unless -d $git_dir;
5125 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5129 my ($id, $orig_ref) = ($_, $_);
5130 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5131 next unless -f "$git_dir/$id/info/url";
5132 my $new_ref = "refs/remotes/$id";
5133 if (::verify_ref("$new_ref^0")) {
5134 print STDERR "W: $orig_ref is probably an old ",
5135 "branch used by an ancient version of ",
5137 "However, $new_ref also exists.\n",
5138 "We will not be able ",
5139 "to use this branch until this ",
5140 "ambiguity is resolved.\n";
5143 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5144 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5145 command_noisy('update-ref', $new_ref, $orig_ref);
5146 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5149 command_close_pipe($fh, $ctx);
5150 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5154 sub migrate_from_v1 {
5155 my $git_dir = $ENV{GIT_DIR};
5157 return $migrated unless -d $git_dir;
5158 my $svn_dir = "$git_dir/svn";
5160 # just in case somebody used 'svn' as their $id at some point...
5161 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5163 print STDERR "Migrating from a git-svn v1 layout...\n";
5165 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5166 "$svn_dir\n\t(required for this version ",
5167 "($::VERSION) of git-svn) does not exist.\n";
5168 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5171 next unless $x =~ s#^refs/remotes/##;
5173 next unless -f "$git_dir/$x/info/url";
5174 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5176 my $dn = dirname("$git_dir/svn/$x");
5177 mkpath([$dn]) unless -d $dn;
5178 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5179 mkpath(["$git_dir/svn/svn"]);
5180 print STDERR " - $git_dir/$x/info => ",
5181 "$git_dir/svn/$x/info\n";
5182 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5184 # don't worry too much about these, they probably
5185 # don't exist with repos this old (save for index,
5186 # and we can easily regenerate that)
5187 foreach my $f (qw/unhandled.log index .rev_db/) {
5188 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5191 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5192 rename "$git_dir/$x", "$git_dir/svn/$x" or
5197 command_close_pipe($fh, $ctx);
5198 print STDERR "Done migrating from a git-svn v1 layout\n";
5203 my ($l_map, $pfx, $path) = @_;
5205 foreach (<$path/*>) {
5206 if (-r "$_/info/url") {
5207 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5208 my $ref_id = $pfx . basename $_;
5209 my $url = ::file_to_s("$_/info/url");
5210 $l_map->{$ref_id} = $url;
5217 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5218 read_old_urls($l_map, $x, $_);
5222 sub migrate_from_v2 {
5223 my @cfg = command(qw/config -l/);
5224 return if grep /^svn-remote\..+\.url=/, @cfg;
5226 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5229 foreach my $ref_id (sort keys %l_map) {
5230 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5232 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5239 sub minimize_connections {
5240 my $r = Git::SVN::read_all_remotes();
5242 my $root_repos = {};
5243 foreach my $repo_id (keys %$r) {
5244 my $url = $r->{$repo_id}->{url} or next;
5245 my $fetch = $r->{$repo_id}->{fetch} or next;
5246 my $ra = Git::SVN::Ra->new($url);
5248 # skip existing cases where we already connect to the root
5249 if (($ra->{url} eq $ra->{repos_root}) ||
5250 ($ra->{repos_root} eq $repo_id)) {
5251 $root_repos->{$ra->{url}} = $repo_id;
5255 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5256 my $root_path = $ra->{url};
5257 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5258 foreach my $path (keys %$fetch) {
5259 my $ref_id = $fetch->{$path};
5260 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5262 # make sure we can read when connecting to
5263 # a higher level of a repository
5264 my ($last_rev, undef) = $gs->last_rev_commit;
5265 if (!defined $last_rev) {
5267 $root_ra->get_latest_revnum;
5271 my $new = $root_path;
5272 $new .= length $path ? "/$path" : '';
5274 $root_ra->get_log([$new], $last_rev, $last_rev,
5278 $new_urls->{$ra->{repos_root}}->{$new} =
5279 { ref_id => $ref_id,
5280 old_repo_id => $repo_id,
5281 old_path => $path };
5286 foreach my $url (keys %$new_urls) {
5287 # see if we can re-use an existing [svn-remote "repo_id"]
5288 # instead of creating a(n ugly) new section:
5289 my $repo_id = $root_repos->{$url} || $url;
5291 my $fetch = $new_urls->{$url};
5292 foreach my $path (keys %$fetch) {
5293 my $x = $fetch->{$path};
5294 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5295 my $pfx = "svn-remote.$x->{old_repo_id}";
5297 my $old_fetch = quotemeta("$x->{old_path}:".
5298 "refs/remotes/$x->{ref_id}");
5299 command_noisy(qw/config --unset/,
5300 "$pfx.fetch", '^'. $old_fetch . '$');
5301 delete $r->{$x->{old_repo_id}}->
5302 {fetch}->{$x->{old_path}};
5303 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5304 command_noisy(qw/config --unset/,
5306 push @emptied, $x->{old_repo_id}
5311 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5313 The following [svn-remote] sections in your config file ($file) are empty
5314 and can be safely removed:
5316 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5320 sub migration_check {
5324 minimize_connections() if $_minimize;
5327 package Git::IndexInfo;
5330 use Git qw/command_input_pipe command_close_pipe/;
5334 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5335 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5339 my ($self, $path) = @_;
5340 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5341 return ++$self->{nr};
5347 my ($self, $mode, $hash, $path) = @_;
5348 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5349 return ++$self->{nr};
5356 command_close_pipe($self->{gui}, $self->{ctx});
5359 package Git::SVN::GlobSpec;
5364 my ($class, $glob) = @_;
5366 $re =~ s!/+$!!g; # no need for trailing slashes
5367 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5369 my ($left, $right) = ($1, $3);
5371 my $depth = $re =~ tr/*/*/;
5372 if ($depth != $temp =~ tr/*/*/) {
5373 die "Only one set of wildcard directories " .
5374 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5377 die "One '*' is needed for glob: '$glob'\n";
5379 $re =~ s!\*!\[^/\]*!g;
5380 $re = quotemeta($left) . "($re)" . quotemeta($right);
5381 if (length $left && !($left =~ s!/+$!!g)) {
5382 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5384 if (length $right && !($right =~ s!^/+!!g)) {
5385 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5387 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5388 bless { left => $left, right => $right, left_regex => $left_re,
5389 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5393 my ($self, $path) = @_;
5394 return (length $self->{left} ? "$self->{left}/" : '') .
5395 $path . (length $self->{right} ? "/$self->{right}" : '');
5403 $remotes = { # returned by read_all_remotes()
5405 # svn-remote.svn.url=https://svn.musicpd.org
5406 url => 'https://svn.musicpd.org',
5407 # svn-remote.svn.fetch=mpd/trunk:trunk
5409 'mpd/trunk' => 'trunk',
5411 # svn-remote.svn.tags=mpd/tags/*:tags/*
5416 regex => qr!mpd/tags/([^/]+)$!,
5422 regex => qr!tags/([^/]+)$!,
5429 $log_entry hashref as returned by libsvn_log_entry()
5431 log => 'whitespace-formatted log entry
5432 ', # trailing newline is preserved
5433 revision => '8', # integer
5434 date => '2004-02-24T17:01:44.108345Z', # commit date
5435 author => 'committer name'
5439 # this is generated by generate_diff();
5440 @mods = array of diff-index line hashes, each element represents one line
5441 of diff-index output
5443 diff-index line ($m hash)
5445 mode_a => first column of diff-index output, no leading ':',
5446 mode_b => second column of diff-index output,
5447 sha1_b => sha1sum of the final blob,
5448 chg => change type [MCRADT],
5449 file_a => original file name of a file (iff chg is 'C' or 'R')
5450 file_b => new/current file name of a file (any chg)
5454 # retval of read_url_paths{,_all}();
5456 # repository root url
5457 'https://svn.musicpd.org' => {
5458 # repository path # GIT_SVN_ID
5459 'mpd/trunk' => 'trunk',
5460 'mpd/tags/0.11.5' => 'tags/0.11.5',
5465 I don't trust the each() function on unless I created %hash myself
5466 because the internal iterator may not have started at base.