2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
7 use vars qw/ $AUTHOR $VERSION
8 $sha1 $sha1_short $_revision $_repository
9 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH}) {
26 if (exists $ENV{GIT_SSH}) {
27 $ENV{SVN_SSH} = $ENV{GIT_SSH};
29 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
35 $Git::SVN::Log::TZ = $ENV{TZ};
37 $| = 1; # unbuffer STDOUT
39 sub fatal (@) { print STDERR "@_\n"; exit 1 }
41 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
44 if ($SVN::Core::VERSION lt '1.1.0') {
45 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
48 my $can_compress = eval { require Compress::Zlib; 1};
49 push @Git::SVN::Ra::ISA, 'SVN::Ra';
50 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
51 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
55 use File::Basename qw/dirname basename/;
56 use File::Path qw/mkpath/;
59 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
62 use Memoize; # core since 5.8.0, Jul 2002
65 # import functions from Git into our packages, en masse
67 foreach (qw/command command_oneline command_noisy command_output_pipe
68 command_input_pipe command_close_pipe
69 command_bidi_pipe command_close_bidi_pipe/) {
70 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
71 Git::SVN::Migration Git::SVN::Log Git::SVN),
73 *{"${package}::$_"} = \&{"Git::$_"};
76 Memoize::memoize 'Git::config';
77 Memoize::memoize 'Git::config_bool';
82 $sha1 = qr/[a-f\d]{40}/;
83 $sha1_short = qr/[a-f\d]{4,40}/;
84 my ($_stdin, $_help, $_edit,
85 $_message, $_file, $_branch_dest,
87 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
88 $_merge, $_strategy, $_dry_run, $_local,
89 $_prefix, $_no_checkout, $_url, $_verbose,
90 $_git_format, $_commit_url, $_tag, $_merge_info);
91 $Git::SVN::_follow_parent = 1;
92 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
94 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
95 'config-dir=s' => \$Git::SVN::Ra::config_dir,
96 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
97 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
98 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
99 'authors-file|A=s' => \$_authors,
100 'authors-prog=s' => \$_authors_prog,
101 'repack:i' => \$Git::SVN::_repack,
102 'noMetadata' => \$Git::SVN::_no_metadata,
103 'useSvmProps' => \$Git::SVN::_use_svm_props,
104 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
105 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
106 'no-checkout' => \$_no_checkout,
108 'repack-flags|repack-args|repack-opts=s' =>
109 \$Git::SVN::_repack_flags,
110 'use-log-author' => \$Git::SVN::_use_log_author,
111 'add-author-from' => \$Git::SVN::_add_author_from,
112 'localtime' => \$Git::SVN::_localtime,
115 my ($_trunk, @_tags, @_branches, $_stdlayout);
117 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
118 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
119 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
120 'stdlayout|s' => \$_stdlayout,
121 'minimize-url|m!' => \$Git::SVN::_minimize_url,
122 'no-metadata' => sub { $icv{noMetadata} = 1 },
123 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
124 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
125 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
126 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
128 my %cmt_opts = ( 'edit|e' => \$_edit,
129 'rmdir' => \$SVN::Git::Editor::_rmdir,
130 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
131 'l=i' => \$SVN::Git::Editor::_rename_limit,
132 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
136 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
137 { 'revision|r=s' => \$_revision,
138 'fetch-all|all' => \$_fetch_all,
139 'parent|p' => \$_fetch_parent,
141 clone => [ \&cmd_clone, "Initialize and fetch revisions",
142 { 'revision|r=s' => \$_revision,
143 'preserve-empty-dirs' =>
144 \$SVN::Git::Fetcher::_preserve_empty_dirs,
145 'placeholder-filename=s' =>
146 \$SVN::Git::Fetcher::_placeholder_filename,
147 %fc_opts, %init_opts } ],
148 init => [ \&cmd_init, "Initialize a repo for tracking" .
149 " (requires URL argument)",
151 'multi-init' => [ \&cmd_multi_init,
152 "Deprecated alias for ".
153 "'$0 init -T<trunk> -b<branches> -t<tags>'",
155 dcommit => [ \&cmd_dcommit,
156 'Commit several diffs to merge with upstream',
157 { 'merge|m|M' => \$_merge,
158 'strategy|s=s' => \$_strategy,
159 'verbose|v' => \$_verbose,
160 'dry-run|n' => \$_dry_run,
161 'fetch-all|all' => \$_fetch_all,
162 'commit-url=s' => \$_commit_url,
163 'revision|r=i' => \$_revision,
164 'no-rebase' => \$_no_rebase,
165 'mergeinfo=s' => \$_merge_info,
166 %cmt_opts, %fc_opts } ],
167 branch => [ \&cmd_branch,
168 'Create a branch in the SVN repository',
169 { 'message|m=s' => \$_message,
170 'destination|d=s' => \$_branch_dest,
171 'dry-run|n' => \$_dry_run,
173 'username=s' => \$Git::SVN::Prompt::_username,
174 'commit-url=s' => \$_commit_url } ],
175 tag => [ sub { $_tag = 1; cmd_branch(@_) },
176 'Create a tag in the SVN repository',
177 { 'message|m=s' => \$_message,
178 'destination|d=s' => \$_branch_dest,
179 'dry-run|n' => \$_dry_run,
180 'username=s' => \$Git::SVN::Prompt::_username,
181 'commit-url=s' => \$_commit_url } ],
182 'set-tree' => [ \&cmd_set_tree,
183 "Set an SVN repository to a git tree-ish",
184 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
185 'create-ignore' => [ \&cmd_create_ignore,
186 'Create a .gitignore per svn:ignore',
187 { 'revision|r=i' => \$_revision
189 'mkdirs' => [ \&cmd_mkdirs ,
190 "recreate empty directories after a checkout",
191 { 'revision|r=i' => \$_revision } ],
192 'propget' => [ \&cmd_propget,
193 'Print the value of a property on a file or directory',
194 { 'revision|r=i' => \$_revision } ],
195 'proplist' => [ \&cmd_proplist,
196 'List all properties of a file or directory',
197 { 'revision|r=i' => \$_revision } ],
198 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
199 { 'revision|r=i' => \$_revision
201 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
202 { 'revision|r=i' => \$_revision
204 'multi-fetch' => [ \&cmd_multi_fetch,
205 "Deprecated alias for $0 fetch --all",
206 { 'revision|r=s' => \$_revision, %fc_opts } ],
207 'migrate' => [ sub { },
208 # no-op, we automatically run this anyways,
209 'Migrate configuration/metadata/layout from
210 previous versions of git-svn',
211 { 'minimize' => \$Git::SVN::Migration::_minimize,
213 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
214 { 'limit=i' => \$Git::SVN::Log::limit,
215 'revision|r=s' => \$_revision,
216 'verbose|v' => \$Git::SVN::Log::verbose,
217 'incremental' => \$Git::SVN::Log::incremental,
218 'oneline' => \$Git::SVN::Log::oneline,
219 'show-commit' => \$Git::SVN::Log::show_commit,
220 'non-recursive' => \$Git::SVN::Log::non_recursive,
221 'authors-file|A=s' => \$_authors,
222 'color' => \$Git::SVN::Log::color,
223 'pager=s' => \$Git::SVN::Log::pager
225 'find-rev' => [ \&cmd_find_rev,
226 "Translate between SVN revision numbers and tree-ish",
228 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
229 { 'merge|m|M' => \$_merge,
230 'verbose|v' => \$_verbose,
231 'strategy|s=s' => \$_strategy,
232 'local|l' => \$_local,
233 'fetch-all|all' => \$_fetch_all,
234 'dry-run|n' => \$_dry_run,
236 'commit-diff' => [ \&cmd_commit_diff,
237 'Commit a diff between two trees',
238 { 'message|m=s' => \$_message,
239 'file|F=s' => \$_file,
240 'revision|r=s' => \$_revision,
242 'info' => [ \&cmd_info,
243 "Show info about the latest SVN revision
244 on the current branch",
245 { 'url' => \$_url, } ],
246 'blame' => [ \&Git::SVN::Log::cmd_blame,
247 "Show what revision and author last modified each line of a file",
248 { 'git-format' => \$_git_format } ],
249 'reset' => [ \&cmd_reset,
250 "Undo fetches back to the specified SVN revision",
251 { 'revision|r=s' => \$_revision,
252 'parent|p' => \$_fetch_parent } ],
254 "Compress unhandled.log files in .git/svn and remove " .
255 "index files in .git/svn",
260 for (my $i = 0; $i < @ARGV; $i++) {
261 if (defined $cmd{$ARGV[$i]}) {
265 } elsif ($ARGV[$i] eq 'help') {
271 # make sure we're always running at the top-level working directory
272 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
273 unless (-d $ENV{GIT_DIR}) {
274 if ($git_dir_user_set) {
275 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
276 "but it is not a directory\n";
278 my $git_dir = delete $ENV{GIT_DIR};
281 $cdup = command_oneline(qw/rev-parse --show-cdup/);
282 $git_dir = '.' unless ($cdup);
283 chomp $cdup if ($cdup);
284 $cdup = "." unless ($cdup && length $cdup);
285 } "Already at toplevel, but $git_dir not found\n";
286 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
287 unless (-d $git_dir) {
288 die "$git_dir still not found after going to ",
291 $ENV{GIT_DIR} = $git_dir;
293 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
296 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
298 read_git_config(\%opts);
299 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
300 Getopt::Long::Configure('pass_through');
302 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
303 'minimize-connections' => \$Git::SVN::Migration::_minimize,
304 'id|i=s' => \$Git::SVN::default_ref_id,
305 'svn-remote|remote|R=s' => sub {
306 $Git::SVN::no_reuse_existing = 1;
307 $Git::SVN::default_repo_id = $_[1] });
308 exit 1 if (!$rv && $cmd && $cmd ne 'log');
311 version() if $_version;
312 usage(1) unless defined $cmd;
313 load_authors() if $_authors;
314 if (defined $_authors_prog) {
315 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
318 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
319 Git::SVN::Migration::migration_check();
321 Git::SVN::init_vars();
323 Git::SVN::verify_remotes_sanity();
324 $cmd{$cmd}->[0]->(@ARGV);
327 post_fetch_checkout();
330 ####################### primary functions ######################
332 my $exit = shift || 0;
333 my $fd = $exit ? \*STDERR : \*STDOUT;
335 git-svn - bidirectional operations between a single Subversion tree and git
336 Usage: git svn <command> [options] [arguments]\n
338 print $fd "Available commands:\n" unless $cmd;
340 foreach (sort keys %cmd) {
341 next if $cmd && $cmd ne $_;
342 next if /^multi-/; # don't show deprecated commands
343 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
344 foreach (sort keys %{$cmd{$_}->[2]}) {
345 # mixed-case options are for .git/config only
346 next if /[A-Z]/ && /^[a-z]+$/i;
347 # prints out arguments as they should be passed:
348 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
349 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
351 split /\|/,$_)," $x\n";
355 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
356 arbitrary identifier if you're tracking multiple SVN branches/repositories in
357 one git repository and want to keep them separate. See git-svn(1) for more
365 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
370 unless (-d $ENV{GIT_DIR}) {
371 my @init_db = ('init');
372 push @init_db, "--template=$_template" if defined $_template;
373 if (defined $_shared) {
374 if ($_shared =~ /[a-z]/) {
375 push @init_db, "--shared=$_shared";
377 push @init_db, "--shared";
380 command_noisy(@init_db);
381 $_repository = Git->repository(Repository => ".git");
384 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
385 foreach my $i (keys %icv) {
386 die "'$set' and '$i' cannot both be set\n" if $set;
387 next unless defined $icv{$i};
388 command_noisy('config', "$pfx.$i", $icv{$i});
391 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
392 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
393 if defined $$ignore_regex;
395 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
396 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
397 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
398 command_noisy('config', "$pfx.placeholder-filename", $$fname);
403 my $repo_path = shift or return;
404 mkpath([$repo_path]) unless -d $repo_path;
405 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
406 $ENV{GIT_DIR} = '.git';
407 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
411 my ($url, $path) = @_;
412 if (!defined $path &&
413 (defined $_trunk || @_branches || @_tags ||
414 defined $_stdlayout) &&
415 $url !~ m#^[a-z\+]+://#) {
418 $path = basename($url) if !defined $path || !length $path;
419 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
420 cmd_init($url, $path);
421 command_oneline('config', 'svn.authorsfile', $authors_absolute)
423 Git::SVN::fetch_all($Git::SVN::default_repo_id);
427 if (defined $_stdlayout) {
428 $_trunk = 'trunk' if (!defined $_trunk);
429 @_tags = 'tags' if (! @_tags);
430 @_branches = 'branches' if (! @_branches);
432 if (defined $_trunk || @_branches || @_tags) {
433 return cmd_multi_init(@_);
435 my $url = shift or die "SVN repository location required ",
436 "as a command-line argument\n";
437 $url = canonicalize_url($url);
441 if ($Git::SVN::_minimize_url eq 'unset') {
442 $Git::SVN::_minimize_url = 0;
445 Git::SVN->init($url);
449 if (grep /^\d+=./, @_) {
450 die "'<rev>=<commit>' fetch arguments are ",
451 "no longer supported.\n";
455 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
457 $Git::SVN::no_reuse_existing = undef;
458 if ($_fetch_parent) {
459 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
461 die "Unable to determine upstream SVN information from ",
462 "working tree history\n";
464 # just fetch, don't checkout.
465 $_no_checkout = 'true';
466 $_fetch_all ? $gs->fetch_all : $gs->fetch;
467 } elsif ($_fetch_all) {
470 $remote ||= $Git::SVN::default_repo_id;
471 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
477 if ($_stdin || !@commits) {
478 print "Reading from stdin...\n";
481 if (/\b($sha1_short)\b/o) {
482 unshift @commits, $1;
487 foreach my $c (@commits) {
488 my @tmp = command('rev-parse',$c);
489 if (scalar @tmp == 1) {
491 } elsif (scalar @tmp > 1) {
492 push @revs, reverse(command('rev-list',@tmp));
494 fatal "Failed to rev-parse $c";
497 my $gs = Git::SVN->new;
498 my ($r_last, $cmt_last) = $gs->last_rev_commit;
500 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
501 fatal "There are new revisions that were fetched ",
502 "and need to be merged (or acknowledged) ",
503 "before committing.\nlast rev: $r_last\n",
504 " current: $gs->{last_rev}";
506 $gs->set_tree($_) foreach @revs;
507 print "Done committing ",scalar @revs," revisions to SVN\n";
511 sub split_merge_info_range {
513 if ($range =~ /(\d+)-(\d+)/) {
514 return (int($1), int($2));
516 return (int($range), int($range));
524 my @arr = split(/,/, $in);
525 for my $element (@arr) {
526 my ($start, $end) = split_merge_info_range($element);
530 my @sorted = @arr [ sort {
531 $fnums[$a] <=> $fnums[$b]
537 for my $element (@sorted) {
538 my ($start, $end) = split_merge_info_range($element);
545 if ($start <= $last+1) {
551 if ($first == $last) {
552 push @return, "$first";
554 push @return, "$first-$last";
561 if ($first == $last) {
562 push @return, "$first";
564 push @return, "$first-$last";
568 return join(',', @return);
571 sub merge_revs_into_hash {
572 my ($hash, $minfo) = @_;
573 my @lines = split(' ', $minfo);
575 for my $line (@lines) {
576 my ($branchpath, $revs) = split(/:/, $line);
578 if (exists($hash->{$branchpath})) {
579 # Merge the two revision sets
580 my $combined = "$hash->{$branchpath},$revs";
581 $hash->{$branchpath} = combine_ranges($combined);
583 # Just do range combining for consolidation
584 $hash->{$branchpath} = combine_ranges($revs);
589 sub merge_merge_info {
590 my ($mergeinfo_one, $mergeinfo_two) = @_;
591 my %result_hash = ();
593 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
594 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
597 # Sort below is for consistency's sake
598 for my $branchname (sort keys(%result_hash)) {
599 my $revlist = $result_hash{$branchname};
600 $result .= "$branchname:$revlist\n"
605 sub populate_merge_info {
606 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
609 read_commit_parents(\%parentshash, $d);
610 my @parents = @{$parentshash{$d}};
613 my $all_parents_ok = 1;
614 my $aggregate_mergeinfo = '';
615 my $rooturl = $gs->repos_root;
617 if (defined($rewritten_parent)) {
618 # Replace first parent with newly-rewritten version
620 unshift @parents, $rewritten_parent;
623 foreach my $parent (@parents) {
624 my ($branchurl, $svnrev, $paruuid) =
625 cmt_metadata($parent);
627 unless (defined($svnrev)) {
628 # Should have been caught be preflight check
629 fatal "merge commit $d has ancestor $parent, but that change "
630 ."does not have git-svn metadata!";
632 unless ($branchurl =~ /^$rooturl(.*)/) {
633 fatal "commit $parent git-svn metadata changed mid-run!";
637 my $ra = Git::SVN::Ra->new($branchurl);
638 my (undef, undef, $props) =
639 $ra->get_dir(canonicalize_path("."), $svnrev);
640 my $par_mergeinfo = $props->{'svn:mergeinfo'};
641 unless (defined $par_mergeinfo) {
644 # Merge previous mergeinfo values
645 $aggregate_mergeinfo =
646 merge_merge_info($aggregate_mergeinfo,
649 next if $parent eq $parents[0]; # Skip first parent
650 # Add new changes being placed in tree by merge
651 my @cmd = (qw/rev-list --reverse/,
653 foreach my $par (@parents) {
654 unless ($par eq $parent) {
659 my ($revlist, $ctx) = command_output_pipe(@cmd);
663 my (undef, $csvnrev, undef) =
665 unless (defined $csvnrev) {
666 # A child is missing SVN annotations...
667 # this might be OK, or might not be.
668 warn "W:child $irev is merged into revision "
669 ."$d but does not have git-svn metadata. "
670 ."This means git-svn cannot determine the "
671 ."svn revision numbers to place into the "
672 ."svn:mergeinfo property. You must ensure "
673 ."a branch is entirely committed to "
674 ."SVN before merging it in order for "
675 ."svn:mergeinfo population to function "
678 push @revsin, $csvnrev;
680 command_close_pipe($revlist, $ctx);
682 last unless $all_parents_ok;
684 # We now have a list of all SVN revnos which are
685 # merged by this particular parent. Integrate them.
686 next if $#revsin == -1;
687 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
688 $aggregate_mergeinfo =
689 merge_merge_info($aggregate_mergeinfo,
692 if ($all_parents_ok and $aggregate_mergeinfo) {
693 return $aggregate_mergeinfo;
702 command_noisy(qw/update-index --refresh/);
703 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
704 'Cannot dcommit with a dirty index. Commit your changes first, '
705 . "or stash them with `git stash'.\n";
709 if ($head ne 'HEAD') {
711 command_oneline([qw/symbolic-ref -q HEAD/])
714 $old_head =~ s{^refs/heads/}{};
716 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
718 command(['checkout', $head], STDERR => 0);
722 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
724 die "Unable to determine upstream SVN information from ",
725 "$head history.\nPerhaps the repository is empty.";
728 if (defined $_commit_url) {
731 $url = eval { command_oneline('config', '--get',
732 "svn-remote.$gs->{repo_id}.commiturl") };
734 $url = $gs->full_pushurl
738 my $last_rev = $_revision if defined $_revision;
740 print "Committing to $url ...\n";
742 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
743 if ($_no_rebase && scalar(@$linear_refs) > 1) {
744 warn "Attempting to commit more than one change while ",
745 "--no-rebase is enabled.\n",
746 "If these changes depend on each other, re-running ",
747 "without --no-rebase may be required."
749 my $expect_url = $url;
751 my $push_merge_info = eval {
752 command_oneline(qw/config --get svn.pushmergeinfo/)
754 if (not defined($push_merge_info)
755 or $push_merge_info eq "false"
756 or $push_merge_info eq "no"
757 or $push_merge_info eq "never") {
758 $push_merge_info = 0;
761 unless (defined($_merge_info) || ! $push_merge_info) {
762 # Preflight check of changes to ensure no issues with mergeinfo
763 # This includes check for uncommitted-to-SVN parents
764 # (other than the first parent, which we will handle),
765 # information from different SVN repos, and paths
766 # which are not underneath this repository root.
767 my $rooturl = $gs->repos_root;
768 foreach my $d (@$linear_refs) {
770 read_commit_parents(\%parentshash, $d);
771 my @realparents = @{$parentshash{$d}};
772 if ($#realparents > 0) {
774 shift @realparents; # Remove/ignore first parent
775 foreach my $parent (@realparents) {
776 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
777 unless (defined $paruuid) {
778 # A parent is missing SVN annotations...
779 # abort the whole operation.
780 fatal "$parent is merged into revision $d, "
781 ."but does not have git-svn metadata. "
782 ."Either dcommit the branch or use a "
783 ."local cherry-pick, FF merge, or rebase "
784 ."instead of an explicit merge commit.";
787 unless ($paruuid eq $uuid) {
788 # Parent has SVN metadata from different repository
789 fatal "merge parent $parent for change $d has "
790 ."git-svn uuid $paruuid, while current change "
794 unless ($branchurl =~ /^$rooturl(.*)/) {
795 # This branch is very strange indeed.
796 fatal "merge parent $parent for $d is on branch "
797 ."$branchurl, which is not under the "
798 ."git-svn root $rooturl!";
805 my $rewritten_parent;
806 Git::SVN::remove_username($expect_url);
807 if (defined($_merge_info)) {
808 $_merge_info =~ tr{ }{\n};
811 my $d = shift @$linear_refs or last;
812 unless (defined $last_rev) {
813 (undef, $last_rev, undef) = cmt_metadata("$d~1");
814 unless (defined $last_rev) {
815 fatal "Unable to extract revision information ",
820 print "diff-tree $d~1 $d\n";
824 unless (defined($_merge_info) || ! $push_merge_info) {
825 $_merge_info = populate_merge_info($d, $gs,
831 my %ed_opts = ( r => $last_rev,
832 log => get_commit_entry($d)->{log},
833 ra => Git::SVN::Ra->new($url),
834 config => SVN::Core::config_get_config(
835 $Git::SVN::Ra::config_dir
840 print "Committed r$_[0]\n";
843 mergeinfo => $_merge_info,
845 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
846 print "No changes\n$d~1 == $d\n";
847 } elsif ($parents->{$d} && @{$parents->{$d}}) {
848 $gs->{inject_parents_dcommit}->{$cmt_rev} =
851 $_fetch_all ? $gs->fetch_all : $gs->fetch;
852 $last_rev = $cmt_rev;
855 # we always want to rebase against the current HEAD,
856 # not any head that was passed to us
857 my @diff = command('diff-tree', $d,
861 @finish = rebase_cmd();
862 print STDERR "W: $d and ", $gs->refname,
863 " differ, using @finish:\n",
864 join("\n", @diff), "\n";
866 print "No changes between current HEAD and ",
868 "\nResetting to the latest ",
870 @finish = qw/reset --mixed/;
872 command_noisy(@finish, $gs->refname);
874 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
878 my ($url_, $rev_, $uuid_, $gs_) =
879 working_head_info('HEAD', \@refs);
880 my ($linear_refs_, $parents_) =
881 linearize_history($gs_, \@refs);
882 if (scalar(@$linear_refs) !=
883 scalar(@$linear_refs_)) {
884 fatal "# of revisions changed ",
886 join("\n", @$linear_refs),
888 join("\n", @$linear_refs_), "\n",
889 'If you are attempting to commit ',
890 "merges, try running:\n\t",
891 'git rebase --interactive',
892 '--preserve-merges ',
894 "\nBefore dcommitting";
896 if ($url_ ne $expect_url) {
897 if ($url_ eq $gs->metadata_url) {
899 "Accepting rewritten URL:",
903 "URL mismatch after rebase:",
904 " $url_ != $expect_url";
907 if ($uuid_ ne $uuid) {
908 fatal "uuid mismatch after rebase: ",
913 for ($i = 0; $i < scalar @$linear_refs; $i++) {
914 my $new = $linear_refs_->[$i] or next;
916 $parents->{$linear_refs->[$i]};
926 my $new_head = command_oneline(qw/rev-parse HEAD/);
927 my $new_is_symbolic = eval {
928 command_oneline(qw/symbolic-ref -q HEAD/);
930 if ($new_is_symbolic) {
931 print "dcommitted the branch ", $head, "\n";
933 print "dcommitted on a detached HEAD because you gave ",
934 "a revision argument.\n",
935 "The rewritten commit is: ", $new_head, "\n";
937 command(['checkout', $old_head], STDERR => 0);
944 my ($branch_name, $head) = @_;
946 unless (defined $branch_name && length $branch_name) {
947 die(($_tag ? "tag" : "branch") . " name required\n");
951 my (undef, $rev, undef, $gs) = working_head_info($head);
952 my $src = $gs->full_pushurl;
954 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
955 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
957 if ($#{$allglobs} == 0) {
958 $glob = $allglobs->[0];
960 unless(defined $_branch_dest) {
962 $_tag ? "tag" : "branch",
963 " paths defined for Subversion repository.\n",
964 "You must specify where you want to create the ",
965 $_tag ? "tag" : "branch",
966 " with the --destination argument.\n";
968 foreach my $g (@{$allglobs}) {
969 # SVN::Git::Editor could probably be moved to Git.pm..
970 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
971 if ($_branch_dest =~ /$re/) {
976 unless (defined $glob) {
977 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
978 foreach my $g (@{$allglobs}) {
979 $g->{path}->{left} =~ /$dest_re/ or next;
981 die "Ambiguous destination: ",
982 $_branch_dest, "\nmatches both '",
983 $glob->{path}->{left}, "' and '",
984 $g->{path}->{left}, "'\n";
988 unless (defined $glob) {
990 $_tag ? "tag" : "branch",
991 " destination $_branch_dest\n";
995 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
997 if (defined $_commit_url) {
1000 $url = eval { command_oneline('config', '--get',
1001 "svn-remote.$gs->{repo_id}.commiturl") };
1003 $url = $remote->{pushurl} || $remote->{url};
1006 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1008 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1009 $src=~s/^http:/https:/;
1014 my $ctx = SVN::Client->new(
1015 auth => Git::SVN::Ra::_auth_providers(),
1017 ${ $_[0] } = defined $_message
1019 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1025 $ctx->ls($dst, 'HEAD', 0);
1026 } and die "branch ${branch_name} already exists\n";
1028 print "Copying ${src} at r${rev} to ${dst}...\n";
1029 $ctx->copy($src, $rev, $dst)
1036 my $revision_or_hash = shift or die "SVN or git revision required ",
1037 "as a command-line argument\n";
1039 if ($revision_or_hash =~ /^r\d+$/) {
1043 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1045 die "Unable to determine upstream SVN information from ",
1048 my $desired_revision = substr($revision_or_hash, 1);
1049 $result = $gs->rev_map_get($desired_revision, $uuid);
1051 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1054 print "$result\n" if $result;
1057 sub auto_create_empty_directories {
1059 my $var = eval { command_oneline('config', '--get', '--bool',
1060 "svn-remote.$gs->{repo_id}.automkdirs") };
1061 # By default, create empty directories by consulting the unhandled log,
1062 # but allow setting it to 'false' to skip it.
1063 return !($var && $var eq 'false');
1067 command_noisy(qw/update-index --refresh/);
1068 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1070 die "Unable to determine upstream SVN information from ",
1071 "working tree history\n";
1074 print "Remote Branch: " . $gs->refname . "\n";
1075 print "SVN URL: " . $url . "\n";
1078 if (command(qw/diff-index HEAD --/)) {
1079 print STDERR "Cannot rebase with uncommited changes:\n";
1080 command_noisy('status');
1084 # rebase will checkout for us, so no need to do it explicitly
1085 $_no_checkout = 'true';
1086 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1088 command_noisy(rebase_cmd(), $gs->refname);
1089 if (auto_create_empty_directories($gs)) {
1094 sub cmd_show_ignore {
1095 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1096 $gs ||= Git::SVN->new;
1097 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1098 $gs->prop_walk($gs->{path}, $r, sub {
1099 my ($gs, $path, $props) = @_;
1100 print STDOUT "\n# $path\n";
1101 my $s = $props->{'svn:ignore'} or return;
1102 $s =~ s/[\r\n]+/\n/g;
1106 print STDOUT "$s\n";
1110 sub cmd_show_externals {
1111 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1112 $gs ||= Git::SVN->new;
1113 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1114 $gs->prop_walk($gs->{path}, $r, sub {
1115 my ($gs, $path, $props) = @_;
1116 print STDOUT "\n# $path\n";
1117 my $s = $props->{'svn:externals'} or return;
1118 $s =~ s/[\r\n]+/\n/g;
1121 print STDOUT "$s\n";
1125 sub cmd_create_ignore {
1126 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1127 $gs ||= Git::SVN->new;
1128 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1129 $gs->prop_walk($gs->{path}, $r, sub {
1130 my ($gs, $path, $props) = @_;
1131 # $path is of the form /path/to/dir/
1132 $path = '.' . $path;
1133 # SVN can have attributes on empty directories,
1134 # which git won't track
1135 mkpath([$path]) unless -d $path;
1136 my $ignore = $path . '.gitignore';
1137 my $s = $props->{'svn:ignore'} or return;
1138 open(GITIGNORE, '>', $ignore)
1139 or fatal("Failed to open `$ignore' for writing: $!");
1140 $s =~ s/[\r\n]+/\n/g;
1143 # Prefix all patterns so that the ignore doesn't apply
1144 # to sub-directories.
1146 print GITIGNORE "$s\n";
1148 or fatal("Failed to close `$ignore': $!");
1149 command_noisy('add', '-f', $ignore);
1154 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1155 $gs ||= Git::SVN->new;
1156 $gs->mkemptydirs($_revision);
1159 sub canonicalize_path {
1161 my $dot_slash_added = 0;
1162 if (substr($path, 0, 1) ne "/") {
1163 $path = "./" . $path;
1164 $dot_slash_added = 1;
1166 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1167 # good reason), so let's do this manually.
1169 $path =~ s#/\.(?:/|$)#/#g;
1170 $path =~ s#/[^/]+/\.\.##g;
1172 $path =~ s#^\./## if $dot_slash_added;
1178 sub canonicalize_url {
1180 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1184 # get_svnprops(PATH)
1185 # ------------------
1186 # Helper for cmd_propget and cmd_proplist below.
1189 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1190 $gs ||= Git::SVN->new;
1192 # prefix THE PATH by the sub-directory from which the user
1194 $path = $cmd_dir_prefix . $path;
1195 fatal("No such file or directory: $path") unless -e $path;
1196 my $is_dir = -d $path ? 1 : 0;
1197 $path = $gs->{path} . '/' . $path;
1199 # canonicalize the path (otherwise libsvn will abort or fail to
1201 $path = canonicalize_path($path);
1203 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1206 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1209 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1214 # cmd_propget (PROP, PATH)
1215 # ------------------------
1216 # Print the SVN property PROP for PATH.
1218 my ($prop, $path) = @_;
1219 $path = '.' if not defined $path;
1220 usage(1) if not defined $prop;
1221 my $props = get_svnprops($path);
1222 if (not defined $props->{$prop}) {
1223 fatal("`$path' does not have a `$prop' SVN property.");
1225 print $props->{$prop} . "\n";
1228 # cmd_proplist (PATH)
1229 # -------------------
1230 # Print the list of SVN properties for PATH.
1233 $path = '.' if not defined $path;
1234 my $props = get_svnprops($path);
1235 print "Properties on '$path':\n";
1236 foreach (sort keys %{$props}) {
1241 sub cmd_multi_init {
1243 unless (defined $_trunk || @_branches || @_tags) {
1247 $_prefix = '' unless defined $_prefix;
1249 $url = canonicalize_url($url);
1253 if (defined $_trunk) {
1255 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1256 # try both old-style and new-style lookups:
1257 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1258 unless ($gs_trunk) {
1259 my ($trunk_url, $trunk_path) =
1260 complete_svn_url($url, $_trunk);
1261 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1265 return unless @_branches || @_tags;
1266 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1267 foreach my $path (@_branches) {
1268 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1270 foreach my $path (@_tags) {
1271 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1275 sub cmd_multi_fetch {
1276 $Git::SVN::no_reuse_existing = undef;
1277 my $remotes = Git::SVN::read_all_remotes();
1278 foreach my $repo_id (sort keys %$remotes) {
1279 if ($remotes->{$repo_id}->{url}) {
1280 Git::SVN::fetch_all($repo_id, $remotes);
1285 # this command is special because it requires no metadata
1286 sub cmd_commit_diff {
1287 my ($ta, $tb, $url) = @_;
1288 my $usage = "Usage: $0 commit-diff -r<revision> ".
1289 "<tree-ish> <tree-ish> [<URL>]";
1290 fatal($usage) if (!defined $ta || !defined $tb);
1292 if (!defined $url) {
1293 my $gs = eval { Git::SVN->new };
1295 fatal("Needed URL or usable git-svn --id in ",
1296 "the command-line\n", $usage);
1299 $svn_path = $gs->{path};
1301 unless (defined $_revision) {
1302 fatal("-r|--revision is a required argument\n", $usage);
1304 if (defined $_message && defined $_file) {
1305 fatal("Both --message/-m and --file/-F specified ",
1306 "for the commit message.\n",
1307 "I have no idea what you mean");
1309 if (defined $_file) {
1310 $_message = file_to_s($_file);
1312 $_message ||= get_commit_entry($tb)->{log};
1314 my $ra ||= Git::SVN::Ra->new($url);
1317 $r = $ra->get_latest_revnum;
1318 } elsif ($r !~ /^\d+$/) {
1319 die "revision argument: $r not understood by git-svn\n";
1321 my %ed_opts = ( r => $r,
1326 editor_cb => sub { print "Committed r$_[0]\n" },
1327 svn_path => $svn_path );
1328 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1329 print "No changes\n$ta == $tb\n";
1333 sub escape_uri_only {
1336 foreach (split m{/}, $uri) {
1337 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1345 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1346 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1347 $url = "$scheme://$domain$uri";
1353 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1354 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1356 die "Too many arguments specified\n";
1359 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1361 if (!$file_type && !$diff_status) {
1362 print STDERR "svn: '$path' is not under version control\n";
1366 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1368 die "Unable to determine upstream SVN information from ",
1369 "working tree history\n";
1372 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1373 $path = "." if $path eq "";
1375 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1378 print escape_url($full_url), "\n";
1382 my $result = "Path: $path\n";
1383 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1384 $result .= "URL: " . escape_url($full_url) . "\n";
1387 my $repos_root = $gs->repos_root;
1388 Git::SVN::remove_username($repos_root);
1389 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1392 $result .= "Repository Root: (offline)\n";
1395 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1396 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1397 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1399 $result .= "Node Kind: " .
1400 ($file_type eq "dir" ? "directory" : "file") . "\n";
1402 my $schedule = $diff_status eq "A"
1404 : ($diff_status eq "D" ? "delete" : "normal");
1405 $result .= "Schedule: $schedule\n";
1407 if ($diff_status eq "A") {
1408 print $result, "\n";
1412 my ($lc_author, $lc_rev, $lc_date_utc);
1413 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1414 my $log = command_output_pipe(@args);
1415 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1417 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1419 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1420 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1421 (undef, $lc_rev, undef) = ::extract_metadata($1);
1426 Git::SVN::Log::set_local_timezone();
1428 $result .= "Last Changed Author: $lc_author\n";
1429 $result .= "Last Changed Rev: $lc_rev\n";
1430 $result .= "Last Changed Date: " .
1431 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1433 if ($file_type ne "dir") {
1434 my $text_last_updated_date =
1435 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1437 "Text Last Updated: " .
1438 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1441 if ($diff_status eq "D") {
1443 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1444 if ($file_type eq "link") {
1445 my $file_name = <$fh>;
1446 $checksum = md5sum("link $file_name");
1448 $checksum = md5sum($fh);
1450 command_close_pipe($fh, $ctx);
1451 } elsif ($file_type eq "link") {
1453 command(qw(cat-file blob), "HEAD:$path");
1455 md5sum("link " . $file_name);
1457 open FILE, "<", $path or die $!;
1458 $checksum = md5sum(\*FILE);
1459 close FILE or die $!;
1461 $result .= "Checksum: " . $checksum . "\n";
1464 print $result, "\n";
1468 my $target = shift || $_revision or die "SVN revision required\n";
1469 $target = $1 if $target =~ /^r(\d+)$/;
1470 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1471 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1473 die "Unable to determine upstream SVN information from ".
1476 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1477 die "Cannot find SVN revision $target\n" unless defined($c);
1478 $gs->rev_map_set($r, $c, 'reset', $uuid);
1479 print "r$r = $c ($gs->{ref_id})\n";
1483 if (!$can_compress) {
1484 warn "Compress::Zlib could not be found; unhandled.log " .
1485 "files will not be compressed.\n";
1487 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1490 ########################### utility functions #########################
1493 my @cmd = qw/rebase/;
1494 push @cmd, '-v' if $_verbose;
1495 push @cmd, qw/--merge/ if $_merge;
1496 push @cmd, "--strategy=$_strategy" if $_strategy;
1500 sub post_fetch_checkout {
1501 return if $_no_checkout;
1502 my $gs = $Git::SVN::_head or return;
1503 return if verify_ref('refs/heads/master^0');
1505 # look for "trunk" ref if it exists
1506 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1507 my $fetch = $remote->{fetch};
1509 foreach my $p (keys %$fetch) {
1510 basename($fetch->{$p}) eq 'trunk' or next;
1511 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1516 my $valid_head = verify_ref('HEAD^0');
1517 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1518 return if ($valid_head || !verify_ref('HEAD^0'));
1520 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1521 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1522 return if -f $index;
1524 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1525 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1526 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1527 print STDERR "Checked out HEAD:\n ",
1528 $gs->full_url, " r", $gs->last_rev, "\n";
1529 if (auto_create_empty_directories($gs)) {
1530 $gs->mkemptydirs($gs->last_rev);
1534 sub complete_svn_url {
1535 my ($url, $path) = @_;
1537 if ($path !~ m#^[a-z\+]+://#) {
1538 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1539 fatal("E: '$path' is not a complete URL ",
1540 "and a separate URL is not specified");
1542 return ($url, $path);
1547 sub complete_url_ls_init {
1548 my ($ra, $repo_path, $switch, $pfx) = @_;
1549 unless ($repo_path) {
1550 print STDERR "W: $switch not specified\n";
1553 $repo_path =~ s#/+$##;
1554 if ($repo_path =~ m#^[a-z\+]+://#) {
1555 $ra = Git::SVN::Ra->new($repo_path);
1558 $repo_path =~ s#^/+##;
1560 fatal("E: '$repo_path' is not a complete URL ",
1561 "and a separate URL is not specified");
1564 my $url = $ra->{url};
1565 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1566 my $k = "svn-remote.$gs->{repo_id}.url";
1567 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1568 if ($orig_url && ($orig_url ne $gs->{url})) {
1569 die "$k already set: $orig_url\n",
1570 "wanted to set to: $gs->{url}\n";
1572 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1573 my $remote_path = "$gs->{path}/$repo_path";
1574 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1575 $remote_path =~ s#/+#/#g;
1576 $remote_path =~ s#^/##g;
1577 $remote_path .= "/*" if $remote_path !~ /\*/;
1578 my ($n) = ($switch =~ /^--(\w+)/);
1579 if (length $pfx && $pfx !~ m#/$#) {
1580 die "--prefix='$pfx' must have a trailing slash '/'\n";
1582 command_noisy('config',
1584 "svn-remote.$gs->{repo_id}.$n",
1585 "$remote_path:refs/remotes/$pfx*" .
1586 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1591 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1592 { STDERR => 0 }); };
1595 sub get_tree_from_treeish {
1597 # $treeish can be a symbolic ref, too:
1598 my $type = command_oneline(qw/cat-file -t/, $treeish);
1600 while ($type eq 'tag') {
1601 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1603 if ($type eq 'commit') {
1604 $expected = (grep /^tree /, command(qw/cat-file commit/,
1606 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1607 die "Unable to get tree from $treeish\n" unless $expected;
1608 } elsif ($type eq 'tree') {
1609 $expected = $treeish;
1611 die "$treeish is a $type, expected tree, tag or commit\n";
1616 sub get_commit_entry {
1617 my ($treeish) = shift;
1618 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1619 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1620 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1621 open my $log_fh, '>', $commit_editmsg or croak $!;
1623 my $type = command_oneline(qw/cat-file -t/, $treeish);
1624 if ($type eq 'commit' || $type eq 'tag') {
1625 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1633 $in_msg = 1 if (/^\s*$/);
1634 $author = $1 if (/^author (.*>)/);
1635 } elsif (/^git-svn-id: /) {
1636 # skip this for now, we regenerate the
1637 # correct one on re-fetch anyways
1638 # TODO: set *:merge properties or like...
1640 if (/^From:/ || /^Signed-off-by:/) {
1646 $msgbuf =~ s/\s+$//s;
1647 if ($Git::SVN::_add_author_from && defined($author)
1649 $msgbuf .= "\n\nFrom: $author";
1651 print $log_fh $msgbuf or croak $!;
1652 command_close_pipe($msg_fh, $ctx);
1654 close $log_fh or croak $!;
1656 if ($_edit || ($type eq 'tree')) {
1657 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1658 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1660 rename $commit_editmsg, $commit_msg or croak $!;
1663 # SVN requires messages to be UTF-8 when entering the repo
1665 open $log_fh, '<', $commit_msg or croak $!;
1667 chomp($log_entry{log} = <$log_fh>);
1669 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1670 my $msg = $log_entry{log};
1672 eval { $msg = Encode::decode($enc, $msg, 1) };
1674 die "Could not decode as $enc:\n", $msg,
1675 "\nPerhaps you need to set i18n.commitencoding\n";
1678 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1679 die "Could not encode as UTF-8:\n$msg\n" if $@;
1681 $log_entry{log} = $msg;
1683 close $log_fh or croak $!;
1690 my ($str, $file, $mode) = @_;
1691 open my $fd,'>',$file or croak $!;
1692 print $fd $str,"\n" or croak $!;
1693 close $fd or croak $!;
1694 chmod ($mode &~ umask, $file) if (defined $mode);
1699 open my $fd,'<',$file or croak "$!: file: $file\n";
1702 close $fd or croak $!;
1707 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1709 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1710 my $log = $cmd eq 'log';
1711 while (<$authors>) {
1713 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1714 my ($user, $name, $email) = ($1, $2, $3);
1716 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1718 $users{$user} = [$name, $email];
1721 close $authors or croak $!;
1724 # convert GetOpt::Long specs for use by git-config
1725 sub read_git_config {
1728 foreach my $o (keys %$opts) {
1729 # if we have mixedCase and a long option-only, then
1730 # it's a config-only variable that we don't need for
1732 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1733 my $v = $opts->{$o};
1734 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1736 my $arg = 'git config';
1737 $arg .= ' --int' if ($o =~ /[:=]i$/);
1738 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1739 if (ref $v eq 'ARRAY') {
1740 chomp(my @tmp = `$arg --get-all svn.$key`);
1743 chomp(my $tmp = `$arg --get svn.$key`);
1744 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1749 delete @$opts{@config_only} if @config_only;
1752 sub extract_metadata {
1753 my $id = shift or return (undef, undef, undef);
1754 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1755 \s([a-f\d\-]+)$/ix);
1756 if (!defined $rev || !$uuid || !$url) {
1757 # some of the original repositories I made had
1758 # identifiers like this:
1759 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1761 return ($url, $rev, $uuid);
1765 return extract_metadata((grep(/^git-svn-id: /,
1766 command(qw/cat-file commit/, shift)))[-1]);
1769 sub cmt_sha2rev_batch {
1771 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1774 foreach my $sha (@{$list}) {
1777 print $out $sha, "\n";
1779 while (my $line = <$in>) {
1780 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1783 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1787 } elsif ($line =~ /^(git-svn-id: )/) {
1788 my (undef, $rev, undef) =
1789 extract_metadata($line);
1793 $size -= length($line);
1794 last if ($size == 0);
1798 command_close_bidi_pipe($pid, $in, $out, $ctx);
1803 sub working_head_info {
1804 my ($head, $refs) = @_;
1805 my @args = qw/log --no-color --no-decorate --first-parent
1807 my ($fh, $ctx) = command_output_pipe(@args, $head);
1811 if ( m{^commit ($::sha1)$} ) {
1812 unshift @$refs, $hash if $hash and $refs;
1816 next unless s{^\s*(git-svn-id:)}{$1};
1817 my ($url, $rev, $uuid) = extract_metadata($_);
1818 if (defined $url && defined $rev) {
1819 next if $max{$url} and $max{$url} < $rev;
1820 if (my $gs = Git::SVN->find_by_url($url)) {
1821 my $c = $gs->rev_map_get($rev, $uuid);
1822 if ($c && $c eq $hash) {
1823 close $fh; # break the pipe
1824 return ($url, $rev, $uuid, $gs);
1826 $max{$url} ||= $gs->rev_map_max;
1831 command_close_pipe($fh, $ctx);
1832 (undef, undef, undef, undef);
1835 sub read_commit_parents {
1836 my ($parents, $c) = @_;
1837 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1838 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1839 @{$parents->{$c}} = split(/ /, $p);
1842 sub linearize_history {
1843 my ($gs, $refs) = @_;
1845 foreach my $c (@$refs) {
1846 read_commit_parents(\%parents, $c);
1851 my $last_svn_commit = $gs->last_commit;
1852 foreach my $c (reverse @$refs) {
1853 next if $c eq $last_svn_commit;
1856 unshift @linear_refs, $c;
1859 # we only want the first parent to diff against for linear
1860 # history, we save the rest to inject when we finalize the
1862 my $fp_a = verify_ref("$c~1");
1863 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1864 if (!$fp_a || !$fp_b) {
1866 "has no parent commit, and therefore ",
1867 "nothing to diff against.\n",
1868 "You should be working from a repository ",
1869 "originally created by git-svn\n";
1871 if ($fp_a ne $fp_b) {
1872 die "$c~1 = $fp_a, however parsing commit $c ",
1873 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1876 foreach my $p (@{$parents{$c}}) {
1880 (\@linear_refs, \%parents);
1883 sub find_file_type_and_diff_status {
1885 return ('dir', '') if $path eq '';
1888 command_oneline(qw(diff --cached --name-status --), $path) || "";
1889 my $diff_status = (split(' ', $diff_output))[0] || "";
1891 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1893 return (undef, undef) if !$diff_status && !$ls_tree;
1895 if ($diff_status eq "A") {
1896 return ("link", $diff_status) if -l $path;
1897 return ("dir", $diff_status) if -d $path;
1898 return ("file", $diff_status);
1901 my $mode = (split(' ', $ls_tree))[0] || "";
1903 return ("link", $diff_status) if $mode eq "120000";
1904 return ("dir", $diff_status) if $mode eq "040000";
1905 return ("file", $diff_status);
1911 my $md5 = Digest::MD5->new();
1912 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1913 $md5->addfile($arg) or croak $!;
1914 } elsif ($ref eq 'SCALAR') {
1915 $md5->add($$arg) or croak $!;
1917 $md5->add($arg) or croak $!;
1919 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1921 return $md5->hexdigest();
1925 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1926 my $out_filename = $_ . ".gz";
1927 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1929 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1930 die "Unable to open $out_filename: $!\n";
1933 while ($res = sysread($in_fh, my $str, 1024)) {
1934 $gz->gzwrite($str) or
1935 die "Unable to write: ".$gz->gzerror()."!\n";
1937 unlink $_ or die "unlink $File::Find::name: $!\n";
1938 } elsif (-f $_ && basename($_) eq "index") {
1939 unlink $_ or die "unlink $_: $!\n";
1946 use Fcntl qw/:DEFAULT :seek/;
1947 use constant rev_map_fmt => 'NH40';
1948 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1949 $_repack $_repack_flags $_use_svm_props $_head
1950 $_use_svnsync_props $no_reuse_existing $_minimize_url
1951 $_use_log_author $_add_author_from $_localtime/;
1953 use File::Path qw/mkpath/;
1954 use File::Copy qw/copy/;
1956 use Memoize; # core since 5.8.0, Jul 2002
1957 use Memoize::Storable;
1959 my ($_gc_nr, $_gc_period);
1961 # properties that we do not log:
1964 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1965 svn:special svn:executable
1966 svn:entry:committed-rev
1967 svn:entry:last-author
1969 svn:entry:committed-date/;
1971 # some options are read globally, but can be overridden locally
1972 # per [svn-remote "..."] section. Command-line options will *NOT*
1973 # override options set in an [svn-remote "..."] section
1975 for my $option (qw/follow_parent no_metadata use_svm_props
1976 use_svnsync_props/) {
1979 my $prop = "-$option";
1982 return $self->{$prop} if exists $self->{$prop};
1983 my $k = "svn-remote.$self->{repo_id}.$key";
1984 eval { command_oneline(qw/config --get/, $k) };
1986 $self->{$prop} = ${"Git::SVN::_$option"};
1988 my $v = command_oneline(qw/config --bool/,$k);
1989 $self->{$prop} = $v eq 'false' ? 0 : 1;
1991 return $self->{$prop};
1997 my (%LOCKFILES, %INDEX_FILES);
1999 unlink keys %LOCKFILES if %LOCKFILES;
2000 unlink keys %INDEX_FILES if %INDEX_FILES;
2003 sub resolve_local_globs {
2004 my ($url, $fetch, $glob_spec) = @_;
2005 return unless defined $glob_spec;
2006 my $ref = $glob_spec->{ref};
2007 my $path = $glob_spec->{path};
2008 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2009 next unless m#^$ref->{regex}$#;
2011 my $pathname = desanitize_refname($path->full_path($p));
2012 my $refname = desanitize_refname($ref->full_path($p));
2013 if (my $existing = $fetch->{$pathname}) {
2014 if ($existing ne $refname) {
2015 die "Refspec conflict:\n",
2016 "existing: $existing\n",
2017 " globbed: $refname\n";
2019 my $u = (::cmt_metadata("$refname"))[0];
2020 $u =~ s!^\Q$url\E(/|$)!! or die
2021 "$refname: '$url' not found in '$u'\n";
2022 if ($pathname ne $u) {
2023 warn "W: Refspec glob conflict ",
2024 "(ref: $refname):\n",
2025 "expected path: $pathname\n",
2027 "Continuing ahead with $u\n";
2031 $fetch->{$pathname} = $refname;
2036 sub parse_revision_argument {
2037 my ($base, $head) = @_;
2038 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2039 return ($base, $head);
2041 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2042 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2043 return ($head, $head) if ($::_revision eq 'HEAD');
2044 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2045 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2046 die "revision argument: $::_revision not understood by git-svn\n";
2050 my ($repo_id, $remotes) = @_;
2054 $repo_id = $gs->{repo_id};
2056 $remotes ||= read_all_remotes();
2057 my $remote = $remotes->{$repo_id} or
2058 die "[svn-remote \"$repo_id\"] unknown\n";
2059 my $fetch = $remote->{fetch};
2060 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2062 my $ra = Git::SVN::Ra->new($url);
2063 my $uuid = $ra->get_uuid;
2064 my $head = $ra->get_latest_revnum;
2066 # ignore errors, $head revision may not even exist anymore
2067 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2068 warn "W: $@\n" if $@;
2070 my $base = defined $fetch ? $head : 0;
2072 # read the max revs for wildcard expansion (branches/*, tags/*)
2073 foreach my $t (qw/branches tags/) {
2074 defined $remote->{$t} or next;
2075 push @globs, @{$remote->{$t}};
2077 my $max_rev = eval { tmp_config(qw/--int --get/,
2078 "svn-remote.$repo_id.${t}-maxRev") };
2079 if (defined $max_rev && ($max_rev < $base)) {
2081 } elsif (!defined $max_rev) {
2087 foreach my $p (sort keys %$fetch) {
2088 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2089 my $lr = $gs->rev_map_max;
2091 $base = $lr if ($lr < $base);
2097 ($base, $head) = parse_revision_argument($base, $head);
2098 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2101 sub read_all_remotes {
2103 my $use_svm_props = eval { command_oneline(qw/config --bool
2104 svn.useSvmProps/) };
2105 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2106 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2107 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2108 if (m!^(.+)\.fetch=$svn_refspec$!) {
2109 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2110 die("svn-remote.$remote: remote ref '$remote_ref' "
2111 . "must start with 'refs/'\n")
2112 unless $remote_ref =~ m{^refs/};
2113 $local_ref = uri_decode($local_ref);
2114 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2115 $r->{$remote}->{svm} = {} if $use_svm_props;
2116 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2117 $r->{$1}->{svm} = {};
2118 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2119 $r->{$1}->{url} = $2;
2120 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2121 $r->{$1}->{pushurl} = $2;
2122 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2123 my ($remote, $t, $local_ref, $remote_ref) =
2125 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2126 . "must start with 'refs/'\n")
2127 unless $remote_ref =~ m{^refs/};
2128 $local_ref = uri_decode($local_ref);
2132 path => Git::SVN::GlobSpec->new($local_ref, 1),
2133 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2134 if (length($rs->{ref}->{right}) != 0) {
2135 die "The '*' glob character must be the last ",
2136 "character of '$remote_ref'\n";
2138 push @{ $r->{$remote}->{$t} }, $rs;
2143 if (defined $r->{$_}->{svm}) {
2146 my $section = "svn-remote.$_";
2148 source => tmp_config('--get',
2149 "$section.svm-source"),
2150 replace => tmp_config('--get',
2151 "$section.svm-replace"),
2154 $r->{$_}->{svm} = $svm;
2162 $_gc_nr = $_gc_period = 1000;
2163 if (defined $_repack || defined $_repack_flags) {
2164 warn "Repack options are obsolete; they have no effect.\n";
2168 sub verify_remotes_sanity {
2169 return unless -d $ENV{GIT_DIR};
2171 foreach (command(qw/config -l/)) {
2172 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2174 die "Remote ref refs/remote/$1 is tracked by",
2175 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2176 "Please resolve this ambiguity in ",
2177 "your git configuration file before ",
2185 sub find_existing_remote {
2186 my ($url, $remotes) = @_;
2187 return undef if $no_reuse_existing;
2189 foreach my $repo_id (keys %$remotes) {
2190 my $u = $remotes->{$repo_id}->{url} or next;
2192 $existing = $repo_id;
2198 sub init_remote_config {
2199 my ($self, $url, $no_write) = @_;
2200 $url =~ s!/+$!!; # strip trailing slash
2201 my $r = read_all_remotes();
2202 my $existing = find_existing_remote($url, $r);
2204 unless ($no_write) {
2205 print STDERR "Using existing ",
2206 "[svn-remote \"$existing\"]\n";
2208 $self->{repo_id} = $existing;
2209 } elsif ($_minimize_url) {
2210 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2211 $existing = find_existing_remote($min_url, $r);
2213 unless ($no_write) {
2214 print STDERR "Using existing ",
2215 "[svn-remote \"$existing\"]\n";
2217 $self->{repo_id} = $existing;
2219 if ($min_url ne $url) {
2220 unless ($no_write) {
2221 print STDERR "Using higher level of URL: ",
2222 "$url => $min_url\n";
2224 my $old_path = $self->{path};
2225 $self->{path} = $url;
2226 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2227 if (length $old_path) {
2228 $self->{path} .= "/$old_path";
2235 # verify that we aren't overwriting anything:
2237 command_oneline('config', '--get',
2238 "svn-remote.$self->{repo_id}.url")
2240 if ($orig_url && ($orig_url ne $url)) {
2241 die "svn-remote.$self->{repo_id}.url already set: ",
2242 "$orig_url\nwanted to set to: $url\n";
2245 my ($xrepo_id, $xpath) = find_ref($self->refname);
2246 if (!$no_write && defined $xpath) {
2247 die "svn-remote.$xrepo_id.fetch already set to track ",
2248 "$xpath:", $self->refname, "\n";
2250 unless ($no_write) {
2251 command_noisy('config',
2252 "svn-remote.$self->{repo_id}.url", $url);
2253 $self->{path} =~ s{^/}{};
2254 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2255 command_noisy('config', '--add',
2256 "svn-remote.$self->{repo_id}.fetch",
2257 "$self->{path}:".$self->refname);
2259 $self->{url} = $url;
2262 sub find_by_url { # repos_root and, path are optional
2263 my ($class, $full_url, $repos_root, $path) = @_;
2265 return undef unless defined $full_url;
2266 remove_username($full_url);
2267 remove_username($repos_root) if defined $repos_root;
2268 my $remotes = read_all_remotes();
2269 if (defined $full_url && defined $repos_root && !defined $path) {
2271 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2273 foreach my $repo_id (keys %$remotes) {
2274 my $u = $remotes->{$repo_id}->{url} or next;
2275 remove_username($u);
2276 next if defined $repos_root && $repos_root ne $u;
2278 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2279 foreach my $t (qw/branches tags/) {
2280 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2281 resolve_local_globs($u, $fetch, $globspec);
2285 my $rwr = rewrite_root({repo_id => $repo_id});
2286 my $svm = $remotes->{$repo_id}->{svm}
2287 if defined $remotes->{$repo_id}->{svm};
2288 unless (defined $p) {
2294 remove_username($z);
2295 } elsif (defined $svm) {
2296 $z = $svm->{source};
2297 $prefix = $svm->{replace};
2298 $prefix =~ s#^\Q$u\E(?:/|$)##;
2301 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2303 foreach my $f (keys %$fetch) {
2305 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2312 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2313 my $self = _new($class, $repo_id, $ref_id, $path);
2315 $self->init_remote_config($url, $no_write);
2322 foreach (command(qw/config -l/)) {
2323 next unless m!^svn-remote\.(.+)\.fetch=
2324 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2325 my ($repo_id, $path, $ref) = ($1, $2, $3);
2326 if ($ref eq $ref_id) {
2327 $path = '' if ($path =~ m#^\./?#);
2328 return ($repo_id, $path);
2331 (undef, undef, undef);
2335 my ($class, $ref_id, $repo_id, $path) = @_;
2336 if (defined $ref_id && !defined $repo_id && !defined $path) {
2337 ($repo_id, $path) = find_ref($ref_id);
2338 if (!defined $repo_id) {
2339 die "Could not find a \"svn-remote.*.fetch\" key ",
2340 "in the repository configuration matching: ",
2344 my $self = _new($class, $repo_id, $ref_id, $path);
2345 if (!defined $self->{path} || !length $self->{path}) {
2346 my $fetch = command_oneline('config', '--get',
2347 "svn-remote.$repo_id.fetch",
2349 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2350 "\":$ref_id\$\" in config\n";
2351 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2353 $self->{path} =~ s{/+}{/}g;
2354 $self->{path} =~ s{\A/}{};
2355 $self->{path} =~ s{/\z}{};
2356 $self->{url} = command_oneline('config', '--get',
2357 "svn-remote.$repo_id.url") or
2358 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2359 $self->{pushurl} = eval { command_oneline('config', '--get',
2360 "svn-remote.$repo_id.pushurl") };
2366 my ($refname) = $_[0]->{ref_id} ;
2368 # It cannot end with a slash /, we'll throw up on this because
2369 # SVN can't have directories with a slash in their name, either:
2370 if ($refname =~ m{/$}) {
2371 die "ref: '$refname' ends with a trailing slash, this is ",
2372 "not permitted by git nor Subversion\n";
2375 # It cannot have ASCII control character space, tilde ~, caret ^,
2376 # colon :, question-mark ?, asterisk *, space, or open bracket [
2379 # Additionally, % must be escaped because it is used for escaping
2380 # and we want our escaped refname to be reversible
2381 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2383 # no slash-separated component can begin with a dot .
2385 $refname =~ s{/\.}{/%2E}g;
2387 # It cannot have two consecutive dots .. anywhere
2389 $refname =~ s{\.\.}{%2E%2E}g;
2391 # trailing dots and .lock are not allowed
2392 # .$ becomes %2E and .lock becomes %2Elock
2393 $refname =~ s{\.(?=$|lock$)}{%2E};
2395 # the sequence @{ is used to access the reflog
2397 $refname =~ s{\@\{}{%40\{}g;
2402 sub desanitize_refname {
2404 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2410 return $self->{svm}->{uuid} if $self->svm;
2412 unless ($self->{svm}) {
2413 die "SVM UUID not cached, and reading remotely failed\n";
2415 $self->{svm}->{uuid};
2420 return $self->{svm} if $self->{svm};
2422 # see if we have it in our config, first:
2424 my $section = "svn-remote.$self->{repo_id}";
2426 source => tmp_config('--get', "$section.svm-source"),
2427 uuid => tmp_config('--get', "$section.svm-uuid"),
2428 replace => tmp_config('--get', "$section.svm-replace"),
2431 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2432 $self->{svm} = $svm;
2438 my ($self, $ra) = @_;
2439 return $ra if $self->svm;
2441 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2442 "(svm:source, svm:uuid) ",
2443 "from the following URLs:\n" );
2444 sub read_svm_props {
2445 my ($self, $ra, $path, $r) = @_;
2446 my $props = ($ra->get_dir($path, $r))[2];
2447 my $src = $props->{'svm:source'};
2448 my $uuid = $props->{'svm:uuid'};
2449 return undef if (!$src || !$uuid);
2453 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2454 or die "doesn't look right - svm:uuid is '$uuid'\n";
2456 # the '!' is used to mark the repos_root!/relative/path
2457 $src =~ s{/?!/?}{/};
2458 $src =~ s{/+$}{}; # no trailing slashes please
2459 # username is of no interest
2460 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2462 my $replace = $ra->{url};
2463 $replace .= "/$path" if length $path;
2465 my $section = "svn-remote.$self->{repo_id}";
2466 tmp_config("$section.svm-source", $src);
2467 tmp_config("$section.svm-replace", $replace);
2468 tmp_config("$section.svm-uuid", $uuid);
2476 my $r = $ra->get_latest_revnum;
2477 my $path = $self->{path};
2479 while (length $path) {
2480 unless ($tried{"$self->{url}/$path"}) {
2481 return $ra if $self->read_svm_props($ra, $path, $r);
2482 $tried{"$self->{url}/$path"} = 1;
2484 $path =~ s#/?[^/]+$##;
2486 die "Path: '$path' should be ''\n" if $path ne '';
2487 return $ra if $self->read_svm_props($ra, $path, $r);
2488 $tried{"$self->{url}/$path"} = 1;
2490 if ($ra->{repos_root} eq $self->{url}) {
2491 die @err, (map { " $_\n" } keys %tried), "\n";
2494 # nope, make sure we're connected to the repository root:
2497 $path = $ra->{svn_path};
2498 $ra = Git::SVN::Ra->new($ra->{repos_root});
2499 while (length $path) {
2500 unless ($tried{"$ra->{url}/$path"}) {
2501 $ok = $self->read_svm_props($ra, $path, $r);
2503 $tried{"$ra->{url}/$path"} = 1;
2505 $path =~ s#/?[^/]+$##;
2507 die "Path: '$path' should be ''\n" if $path ne '';
2508 $ok ||= $self->read_svm_props($ra, $path, $r);
2509 $tried{"$ra->{url}/$path"} = 1;
2511 die @err, (map { " $_\n" } keys %tried), "\n";
2513 Git::SVN::Ra->new($self->{url});
2518 return $self->{svnsync} if $self->{svnsync};
2520 if ($self->no_metadata) {
2521 die "Can't have both 'noMetadata' and ",
2522 "'useSvnsyncProps' options set!\n";
2524 if ($self->rewrite_root) {
2525 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2528 if ($self->rewrite_uuid) {
2529 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2534 # see if we have it in our config, first:
2536 my $section = "svn-remote.$self->{repo_id}";
2538 my $url = tmp_config('--get', "$section.svnsync-url");
2539 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2540 die "doesn't look right - svn:sync-from-url is '$url'\n";
2542 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2543 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2544 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2546 $svnsync = { url => $url, uuid => $uuid }
2548 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2549 return $self->{svnsync} = $svnsync;
2552 my $err = "useSvnsyncProps set, but failed to read " .
2553 "svnsync property: svn:sync-from-";
2554 my $rp = $self->ra->rev_proplist(0);
2556 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2557 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2558 die "doesn't look right - svn:sync-from-url is '$url'\n";
2560 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2561 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2562 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2564 my $section = "svn-remote.$self->{repo_id}";
2565 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2566 tmp_config('--add', "$section.svnsync-url", $url);
2567 return $self->{svnsync} = { url => $url, uuid => $uuid };
2570 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2571 # remote lookup (useful for 'git svn log').
2574 unless ($self->{ra_uuid}) {
2575 my $key = "svn-remote.$self->{repo_id}.uuid";
2576 my $uuid = eval { tmp_config('--get', $key) };
2577 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2578 $self->{ra_uuid} = $uuid;
2580 die "ra_uuid called without URL\n" unless $self->{url};
2581 $self->{ra_uuid} = $self->ra->get_uuid;
2582 tmp_config('--add', $key, $self->{ra_uuid});
2588 sub _set_repos_root {
2589 my ($self, $repos_root) = @_;
2590 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2591 $repos_root ||= $self->ra->{repos_root};
2592 tmp_config($k, $repos_root);
2598 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2599 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2604 my $ra = Git::SVN::Ra->new($self->{url});
2605 $self->_set_repos_root($ra->{repos_root});
2606 if ($self->use_svm_props && !$self->{svm}) {
2607 if ($self->no_metadata) {
2608 die "Can't have both 'noMetadata' and ",
2609 "'useSvmProps' options set!\n";
2610 } elsif ($self->use_svnsync_props) {
2611 die "Can't have both 'useSvnsyncProps' and ",
2612 "'useSvmProps' options set!\n";
2614 $ra = $self->_set_svm_vars($ra);
2615 $self->{-want_revprops} = 1;
2620 # prop_walk(PATH, REV, SUB)
2621 # -------------------------
2622 # Recursively traverse PATH at revision REV and invoke SUB for each
2623 # directory that contains a SVN property. SUB will be invoked as
2624 # follows: &SUB(gs, path, props); where `gs' is this instance of
2625 # Git::SVN, `path' the path to the directory where the properties
2626 # `props' were found. The `path' will be relative to point of checkout,
2627 # that is, if url://repo/trunk is the current Git branch, and that
2628 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2629 # as `path' (note the trailing `/').
2631 my ($self, $path, $rev, $sub) = @_;
2634 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2637 # Strip the irrelevant part of the path.
2638 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2639 # Ensure the path is terminated by a `/'.
2642 # The properties contain all the internal SVN stuff nobody
2643 # (usually) cares about.
2644 my $interesting_props = 0;
2645 foreach (keys %{$props}) {
2646 # If it doesn't start with `svn:', it must be a
2647 # user-defined property.
2648 ++$interesting_props and next if $_ !~ /^svn:/;
2649 # FIXME: Fragile, if SVN adds new public properties,
2650 # this needs to be updated.
2651 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2652 |eol-style|mime-type
2653 |externals|needs-lock)$/x;
2655 &$sub($self, $p, $props) if $interesting_props;
2657 foreach (sort keys %$dirent) {
2658 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2659 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2663 sub last_rev { ($_[0]->last_rev_commit)[0] }
2664 sub last_commit { ($_[0]->last_rev_commit)[1] }
2666 # returns the newest SVN revision number and newest commit SHA1
2667 sub last_rev_commit {
2669 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2670 return ($self->{last_rev}, $self->{last_commit});
2672 my $c = ::verify_ref($self->refname.'^0');
2673 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2674 my $rev = (::cmt_metadata($c))[1];
2676 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2680 my $map_path = $self->map_path;
2681 unless (-e $map_path) {
2682 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2683 return (undef, undef);
2685 my ($rev, $commit) = $self->rev_map_max(1);
2686 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2687 return ($rev, $commit);
2690 sub get_fetch_range {
2691 my ($self, $min, $max) = @_;
2692 $max ||= $self->ra->get_latest_revnum;
2693 $min ||= $self->rev_map_max;
2699 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2700 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2701 if (! -f $config && -f $old_def_config) {
2702 rename $old_def_config, $config or
2703 die "Failed rename $old_def_config => $config: $!\n";
2705 my $old_config = $ENV{GIT_CONFIG};
2706 $ENV{GIT_CONFIG} = $config;
2709 unless (-f $config) {
2711 open my $fh, '>', $config or
2712 die "Can't open $config: $!\n";
2713 print $fh "; This file is used internally by ",
2715 "Couldn't write to $config: $!\n";
2716 print $fh "; You should not have to edit it\n" or
2717 die "Couldn't write to $config: $!\n";
2718 close $fh or die "Couldn't close $config: $!\n";
2720 command('config', @args);
2723 if (defined $old_config) {
2724 $ENV{GIT_CONFIG} = $old_config;
2726 delete $ENV{GIT_CONFIG};
2729 wantarray ? @ret : $ret[0];
2733 my ($self, $sub) = @_;
2734 my $old_index = $ENV{GIT_INDEX_FILE};
2735 $ENV{GIT_INDEX_FILE} = $self->{index};
2738 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2739 mkpath([$dir]) unless -d $dir;
2743 if (defined $old_index) {
2744 $ENV{GIT_INDEX_FILE} = $old_index;
2746 delete $ENV{GIT_INDEX_FILE};
2749 wantarray ? @ret : $ret[0];
2752 sub assert_index_clean {
2753 my ($self, $treeish) = @_;
2755 $self->tmp_index_do(sub {
2756 command_noisy('read-tree', $treeish) unless -e $self->{index};
2757 my $x = command_oneline('write-tree');
2758 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2759 /^tree ($::sha1)/mo);
2762 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2763 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2764 command_noisy('read-tree', $treeish);
2765 $x = command_oneline('write-tree');
2767 ::fatal "trees ($treeish) $y != $x\n",
2768 "Something is seriously wrong...";
2773 sub get_commit_parents {
2774 my ($self, $log_entry) = @_;
2775 my (%seen, @ret, @tmp);
2776 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2777 if (my $ip = $self->{inject_parents}) {
2778 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2782 if (my $cur = ::verify_ref($self->refname.'^0')) {
2785 if (my $ipd = $self->{inject_parents_dcommit}) {
2786 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2787 push @tmp, @$commit;
2790 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2791 while (my $p = shift @tmp) {
2801 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2802 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2803 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2806 if ($rwr !~ m#^[a-z\+]+://#) {
2807 die "$rwr is not a valid URL (key: $k)\n";
2810 $self->{-rewrite_root} = $rwr;
2815 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2816 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2817 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2820 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2821 die "$rwid is not a valid UUID (key: $k)\n";
2824 $self->{-rewrite_uuid} = $rwid;
2829 ($self->rewrite_root || $self->{url}) .
2830 (length $self->{path} ? '/' . $self->{path} : '');
2835 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2840 if ($self->{pushurl}) {
2841 return $self->{pushurl} . (length $self->{path} ? '/' .
2842 $self->{path} : '');
2844 return $self->full_url;
2848 sub set_commit_header_env {
2849 my ($log_entry) = @_;
2851 foreach my $ned (qw/NAME EMAIL DATE/) {
2852 foreach my $ac (qw/AUTHOR COMMITTER/) {
2853 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2857 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2858 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2859 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2861 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2862 ? $log_entry->{commit_name}
2863 : $log_entry->{name};
2864 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2865 ? $log_entry->{commit_email}
2866 : $log_entry->{email};
2870 sub restore_commit_header_env {
2872 foreach my $ned (qw/NAME EMAIL DATE/) {
2873 foreach my $ac (qw/AUTHOR COMMITTER/) {
2874 my $k = "GIT_${ac}_${ned}";
2875 if (defined $env->{$k}) {
2876 $ENV{$k} = $env->{$k};
2885 command_noisy('gc', '--auto');
2889 my ($self, $log_entry) = @_;
2890 my $lr = $self->last_rev;
2891 if (defined $lr && $lr >= $log_entry->{revision}) {
2892 die "Last fetched revision of ", $self->refname,
2893 " was r$lr, but we are about to fetch: ",
2894 "r$log_entry->{revision}!\n";
2896 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2897 croak "$log_entry->{revision} = $c already exists! ",
2898 "Why are we refetching it?\n";
2900 my $old_env = set_commit_header_env($log_entry);
2901 my $tree = $log_entry->{tree};
2902 if (!defined $tree) {
2903 $tree = $self->tmp_index_do(sub {
2904 command_oneline('write-tree') });
2906 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2908 my @exec = ('git', 'commit-tree', $tree);
2909 foreach ($self->get_commit_parents($log_entry)) {
2910 push @exec, '-p', $_;
2912 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2916 # we always get UTF-8 from SVN, but we may want our commits in
2917 # a different encoding.
2918 if (my $enc = Git::config('i18n.commitencoding')) {
2920 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2922 print $msg_fh $log_entry->{log} or croak $!;
2923 restore_commit_header_env($old_env);
2924 unless ($self->no_metadata) {
2925 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2928 $msg_fh->flush == 0 or croak $!;
2929 close $msg_fh or croak $!;
2930 chomp(my $commit = do { local $/; <$out_fh> });
2931 close $out_fh or croak $!;
2934 if ($commit !~ /^$::sha1$/o) {
2935 die "Failed to commit, invalid sha1: $commit\n";
2938 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2940 $self->{last_rev} = $log_entry->{revision};
2941 $self->{last_commit} = $commit;
2942 print "r$log_entry->{revision}" unless $::_q > 1;
2943 if (defined $log_entry->{svm_revision}) {
2944 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2945 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2946 0, $self->svm_uuid);
2948 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2949 if (--$_gc_nr == 0) {
2950 $_gc_nr = $_gc_period;
2957 my ($self, $paths, $r) = @_;
2958 return 1 if $self->{path} eq '';
2959 if (my $path = $paths->{"/$self->{path}"}) {
2960 return ($path->{action} eq 'D') ? 0 : 1;
2962 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2963 if (grep /$self->{path_regex}/, keys %$paths) {
2967 foreach (split m#/#, $self->{path}) {
2969 next unless ($paths->{$c} &&
2970 ($paths->{$c}->{action} =~ /^[AR]$/));
2971 if ($self->ra->check_path($self->{path}, $r) ==
2979 sub find_parent_branch {
2980 my ($self, $paths, $rev) = @_;
2981 return undef unless $self->follow_parent;
2982 unless (defined $paths) {
2983 my $err_handler = $SVN::Error::handler;
2984 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2985 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2986 sub { $paths = $_[0] });
2987 $SVN::Error::handler = $err_handler;
2989 return undef unless defined $paths;
2991 # look for a parent from another branch:
2992 my @b_path_components = split m#/#, $self->{path};
2993 my @a_path_components;
2995 while (@b_path_components) {
2996 $i = $paths->{'/'.join('/', @b_path_components)};
2997 last if $i && defined $i->{copyfrom_path};
2998 unshift(@a_path_components, pop(@b_path_components));
3000 return undef unless defined $i && defined $i->{copyfrom_path};
3001 my $branch_from = $i->{copyfrom_path};
3002 if (@a_path_components) {
3003 print STDERR "branch_from: $branch_from => ";
3004 $branch_from .= '/'.join('/', @a_path_components);
3005 print STDERR $branch_from, "\n";
3007 my $r = $i->{copyfrom_rev};
3008 my $repos_root = $self->ra->{repos_root};
3009 my $url = $self->ra->{url};
3010 my $new_url = $url . $branch_from;
3011 print STDERR "Found possible branch point: ",
3012 "$new_url => ", $self->full_url, ", $r\n"
3014 $branch_from =~ s#^/##;
3015 my $gs = $self->other_gs($new_url, $url,
3016 $branch_from, $r, $self->{ref_id});
3017 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3020 if (!defined $r0 || !defined $parent) {
3021 ($base, $head) = parse_revision_argument(0, $r);
3024 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3025 0, 1, sub { $base = $_[1] - 1 });
3028 if (defined $base && $base <= $r) {
3029 $gs->fetch($base, $r);
3031 ($r0, $parent) = $gs->find_rev_before($r, 1);
3033 if (defined $r0 && defined $parent) {
3034 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3037 if ($self->ra->can_do_switch) {
3038 $self->assert_index_clean($parent);
3039 print STDERR "Following parent with do_switch\n"
3041 # do_switch works with svn/trunk >= r22312, but that
3042 # is not included with SVN 1.4.3 (the latest version
3043 # at the moment), so we can't rely on it
3044 $self->{last_rev} = $r0;
3045 $self->{last_commit} = $parent;
3046 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3047 $gs->ra->gs_do_switch($r0, $rev, $gs,
3048 $self->full_url, $ed)
3049 or die "SVN connection failed somewhere...\n";
3050 } elsif ($self->ra->trees_match($new_url, $r0,
3051 $self->full_url, $rev)) {
3052 print STDERR "Trees match:\n",
3054 " ${\$self->full_url}\@$rev\n",
3055 "Following parent with no changes\n"
3057 $self->tmp_index_do(sub {
3058 command_noisy('read-tree', $parent);
3060 $self->{last_commit} = $parent;
3062 print STDERR "Following parent with do_update\n"
3064 $ed = SVN::Git::Fetcher->new($self);
3065 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3066 or die "SVN connection failed somewhere...\n";
3068 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3069 return $self->make_log_entry($rev, [$parent], $ed);
3075 my ($self, $paths, $rev) = @_;
3077 my ($last_rev, @parents);
3078 if (my $lc = $self->last_commit) {
3079 # we can have a branch that was deleted, then re-added
3080 # under the same name but copied from another path, in
3081 # which case we'll have multiple parents (we don't
3082 # want to break the original ref, nor lose copypath info):
3083 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3084 push @{$log_entry->{parents}}, $lc;
3087 $ed = SVN::Git::Fetcher->new($self);
3088 $last_rev = $self->{last_rev};
3093 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3096 $ed = SVN::Git::Fetcher->new($self);
3098 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3099 die "SVN connection failed somewhere...\n";
3101 $self->make_log_entry($rev, \@parents, $ed);
3105 my ($self, $r) = @_;
3108 my ($r, $empty_dirs, $line) = @_;
3109 if (defined $r && $line =~ /^r(\d+)$/) {
3110 return 0 if $1 > $r;
3111 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3112 $empty_dirs->{$1} = 1;
3113 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3114 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3115 delete @$empty_dirs{@d};
3120 my %empty_dirs = ();
3121 my $gz_file = "$self->{dir}/unhandled.log.gz";
3123 if (!$can_compress) {
3124 warn "Compress::Zlib could not be found; ",
3125 "empty directories in $gz_file will not be read\n";
3127 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3128 die "Unable to open $gz_file: $!\n";
3130 while ($gz->gzreadline($line) > 0) {
3131 scan($r, \%empty_dirs, $line) or last;
3137 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3138 binmode $fh or croak "binmode: $!";
3140 scan($r, \%empty_dirs, $_) or last;
3145 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3146 foreach my $d (sort keys %empty_dirs) {
3147 $d = uri_decode($d);
3149 next unless length($d);
3152 warn "$d exists but is not a directory\n";
3154 print "creating empty directory: $d\n";
3161 my ($self, $ed) = @_;
3163 my $h = $ed->{empty};
3164 foreach (sort keys %$h) {
3165 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3166 push @out, " $act: " . uri_encode($_);
3167 warn "W: $act: $_\n";
3169 foreach my $t (qw/dir_prop file_prop/) {
3170 $h = $ed->{$t} or next;
3171 foreach my $path (sort keys %$h) {
3172 my $ppath = $path eq '' ? '.' : $path;
3173 foreach my $prop (sort keys %{$h->{$path}}) {
3174 next if $SKIP_PROP{$prop};
3175 my $v = $h->{$path}->{$prop};
3176 my $t_ppath_prop = "$t: " .
3177 uri_encode($ppath) . ' ' .
3180 push @out, " +$t_ppath_prop " .
3183 push @out, " -$t_ppath_prop";
3188 foreach my $t (qw/absent_file absent_directory/) {
3189 $h = $ed->{$t} or next;
3190 foreach my $parent (sort keys %$h) {
3191 foreach my $path (sort @{$h->{$parent}}) {
3192 push @out, " $t: " .
3193 uri_encode("$parent/$path");
3194 warn "W: $t: $parent/$path ",
3195 "Insufficient permissions?\n";
3202 # parse_svn_date(DATE)
3203 # --------------------
3204 # Given a date (in UTC) from Subversion, return a string in the format
3205 # "<TZ Offset> <local date/time>" that Git will use.
3207 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3208 # is true we'll convert it to the local timezone instead.
3209 sub parse_svn_date {
3210 my $date = shift || return '+0000 1970-01-01 00:00:00';
3211 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3212 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3213 croak "Unable to parse date: $date\n";
3214 my $parsed_date; # Set next.
3216 if ($Git::SVN::_localtime) {
3217 # Translate the Subversion datetime to an epoch time.
3218 # Begin by switching ourselves to $date's timezone, UTC.
3219 my $old_env_TZ = $ENV{TZ};
3223 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3225 # Determine our local timezone (including DST) at the
3226 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3227 # value of TZ, if any, at the time we were run.
3228 if (defined $Git::SVN::Log::TZ) {
3229 $ENV{TZ} = $Git::SVN::Log::TZ;
3235 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
3237 # This converts $epoch_in_UTC into our local timezone.
3238 my ($sec, $min, $hour, $mday, $mon, $year,
3239 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3241 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3242 $our_TZ, $year + 1900, $mon + 1,
3243 $mday, $hour, $min, $sec);
3245 # Reset us to the timezone in effect when we entered
3247 if (defined $old_env_TZ) {
3248 $ENV{TZ} = $old_env_TZ;
3253 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3256 return $parsed_date;
3260 my ($self, $new_url, $url,
3261 $branch_from, $r, $old_ref_id) = @_;
3262 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3264 my $ref_id = $old_ref_id;
3265 $ref_id =~ s/\@\d+-*$//;
3267 # just grow a tail if we're not unique enough :x
3268 $ref_id .= '-' while find_ref($ref_id);
3269 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3270 if ($u =~ s#^\Q$url\E(/|$)##) {
3273 $repo_id = $self->{repo_id};
3276 # It is possible to tag two different subdirectories at
3277 # the same revision. If the url for an existing ref
3278 # does not match, we must either find a ref with a
3279 # matching url or create a new ref by growing a tail.
3280 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3281 my (undef, $max_commit) = $gs->rev_map_max(1);
3282 last if (!$max_commit);
3283 my ($url) = ::cmt_metadata($max_commit);
3284 last if ($url eq $gs->metadata_url);
3287 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3292 sub call_authors_prog {
3293 my ($orig_author) = @_;
3294 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3295 my $author = `$::_authors_prog $orig_author`;
3297 die "$::_authors_prog failed with exit code $?\n"
3299 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3300 my ($name, $email) = ($1, $2);
3301 $email = undef if length $2 == 0;
3302 return [$name, $email];
3304 die "Author: $orig_author: $::_authors_prog returned "
3305 . "invalid author format: $author\n";
3311 if (!defined $author || length $author == 0) {
3312 $author = '(no author)';
3314 if (!defined $::users{$author}) {
3315 if (defined $::_authors_prog) {
3316 $::users{$author} = call_authors_prog($author);
3317 } elsif (defined $::_authors) {
3318 die "Author: $author not defined in $::_authors file\n";
3324 sub find_extra_svk_parents {
3325 my ($self, $ed, $tickets, $parents) = @_;
3326 # aha! svk:merge property changed...
3327 my @tickets = split "\n", $tickets;
3329 for my $ticket ( @tickets ) {
3330 my ($uuid, $path, $rev) = split /:/, $ticket;
3331 if ( $uuid eq $self->ra_uuid ) {
3332 my $url = $self->{url};
3333 my $repos_root = $url;
3334 my $branch_from = $path;
3335 $branch_from =~ s{^/}{};
3336 my $gs = $self->other_gs($repos_root."/".$branch_from,
3341 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3342 # wahey! we found it, but it might be
3344 push @known_parents, [ $rev, $commit ];
3348 # Ordering matters; highest-numbered commit merge tickets
3349 # first, as they may account for later merge ticket additions
3351 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3352 for my $parent ( @known_parents ) {
3353 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3354 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3356 while ( <$msg_fh> ) {
3359 command_close_pipe($msg_fh, $ctx);
3362 "Found merge parent (svk:merge ticket): $parent\n";
3363 push @$parents, $parent;
3368 sub lookup_svn_merge {
3373 my ($source, $revs) = split ":", $merge;
3376 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3378 warn "Couldn't find revmap for $url$source\n";
3381 my @ranges = split ",", $revs;
3382 my ($tip, $tip_commit);
3383 my @merged_commit_ranges;
3385 for my $range ( @ranges ) {
3386 my ($bottom, $top) = split "-", $range;
3388 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3389 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3391 unless ($top_commit and $bottom_commit) {
3392 warn "W:unknown path/rev in svn:mergeinfo "
3393 ."dirprop: $source:$range\n";
3397 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3398 push @merged_commit_ranges,
3399 "$bottom_commit^..$top_commit";
3401 push @merged_commit_ranges, "$top_commit";
3404 if ( !defined $tip or $top > $tip ) {
3406 $tip_commit = $top_commit;
3409 return ($tip_commit, @merged_commit_ranges);
3413 my ($msg_fh, $ctx) = command_output_pipe(
3417 while ( <$msg_fh> ) {
3421 command_close_pipe($msg_fh, $ctx);
3425 sub check_cherry_pick {
3428 my $parents = shift;
3430 my %commits = map { $_ => 1 }
3431 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3432 for my $range ( @ranges ) {
3433 delete @commits{_rev_list($range, "--")};
3435 for my $commit (keys %commits) {
3436 if (has_no_changes($commit)) {
3437 delete $commits{$commit};
3440 return (keys %commits);
3443 sub has_no_changes {
3446 my @revs = split / /, command_oneline(
3447 qw(rev-list --parents -1 -m), $commit);
3449 # Commits with no parents, e.g. the start of a partial branch,
3450 # have changes by definition.
3451 return 1 if (@revs < 2);
3453 # Commits with multiple parents, e.g a merge, have no changes
3455 return 0 if (@revs > 2);
3457 return (command_oneline("rev-parse", "$commit^{tree}") eq
3458 command_oneline("rev-parse", "$commit~1^{tree}"));
3461 # The GIT_DIR environment variable is not always set until after the command
3462 # line arguments are processed, so we can't memoize in a BEGIN block.
3466 sub memoize_svn_mergeinfo_functions {
3467 return if $memoized;
3470 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3471 mkpath([$cache_path]) unless -d $cache_path;
3473 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3474 "$cache_path/lookup_svn_merge.db", 'nstore';
3475 memoize 'lookup_svn_merge',
3476 SCALAR_CACHE => 'FAULT',
3477 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3480 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3481 "$cache_path/check_cherry_pick.db", 'nstore';
3482 memoize 'check_cherry_pick',
3483 SCALAR_CACHE => 'FAULT',
3484 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3487 tie my %has_no_changes_cache => 'Memoize::Storable',
3488 "$cache_path/has_no_changes.db", 'nstore';
3489 memoize 'has_no_changes',
3490 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3491 LIST_CACHE => 'FAULT',
3495 sub unmemoize_svn_mergeinfo_functions {
3496 return if not $memoized;
3499 Memoize::unmemoize 'lookup_svn_merge';
3500 Memoize::unmemoize 'check_cherry_pick';
3501 Memoize::unmemoize 'has_no_changes';
3504 Memoize::memoize 'Git::SVN::repos_root';
3508 # Force cache writeout explicitly instead of waiting for
3509 # global destruction to avoid segfault in Storable:
3510 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3511 unmemoize_svn_mergeinfo_functions();
3514 sub parents_exclude {
3515 my $parents = shift;
3517 return unless @commits;
3522 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3523 $excluded = command_oneline(@cmd);
3527 for my $commit ( @commits ) {
3528 if ( $commit eq $excluded ) {
3529 push @excluded, $commit;
3537 die "saw commit '$excluded' in rev-list output, "
3538 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3543 while ($excluded and @commits);
3549 # note: this function should only be called if the various dirprops
3550 # have actually changed
3551 sub find_extra_svn_parents {
3552 my ($self, $ed, $mergeinfo, $parents) = @_;
3553 # aha! svk:merge property changed...
3555 memoize_svn_mergeinfo_functions();
3557 # We first search for merged tips which are not in our
3558 # history. Then, we figure out which git revisions are in
3559 # that tip, but not this revision. If all of those revisions
3560 # are now marked as merge, we can add the tip as a parent.
3561 my @merges = split "\n", $mergeinfo;
3563 my $url = $self->{url};
3564 my $uuid = $self->ra_uuid;
3566 for my $merge ( @merges ) {
3567 my ($tip_commit, @ranges) =
3568 lookup_svn_merge( $uuid, $url, $merge );
3569 unless (!$tip_commit or
3570 grep { $_ eq $tip_commit } @$parents ) {
3571 push @merge_tips, $tip_commit;
3572 $ranges{$tip_commit} = \@ranges;
3574 push @merge_tips, undef;
3578 my %excluded = map { $_ => 1 }
3579 parents_exclude($parents, grep { defined } @merge_tips);
3581 # check merge tips for new parents
3583 for my $merge_tip ( @merge_tips ) {
3584 my $spec = shift @merges;
3585 next unless $merge_tip and $excluded{$merge_tip};
3587 my $ranges = $ranges{$merge_tip};
3589 # check out 'new' tips
3592 $merge_base = command_oneline(
3594 @$parents, $merge_tip,
3598 die "An error occurred during merge-base"
3599 unless $@->isa("Git::Error::Command");
3601 warn "W: Cannot find common ancestor between ".
3602 "@$parents and $merge_tip. Ignoring merge info.\n";
3606 # double check that there are no missing non-merge commits
3607 my (@incomplete) = check_cherry_pick(
3608 $merge_base, $merge_tip,
3613 if ( @incomplete ) {
3614 warn "W:svn cherry-pick ignored ($spec) - missing "
3615 .@incomplete." commit(s) (eg $incomplete[0])\n";
3618 "Found merge parent (svn:mergeinfo prop): ",
3620 push @new_parents, $merge_tip;
3624 # cater for merges which merge commits from multiple branches
3625 if ( @new_parents > 1 ) {
3626 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3627 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3629 next unless $new_parents[$i];
3630 next unless $new_parents[$j];
3631 my $revs = command_oneline(
3633 "$new_parents[$i]..$new_parents[$j]",
3636 undef($new_parents[$j]);
3641 push @$parents, grep { defined } @new_parents;
3644 sub make_log_entry {
3645 my ($self, $rev, $parents, $ed) = @_;
3646 my $untracked = $self->get_untracked($ed);
3648 my @parents = @$parents;
3649 my $ps = $ed->{path_strip} || "";
3650 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3651 my $props = $ed->{dir_prop}{$path};
3652 if ( $props->{"svk:merge"} ) {
3653 $self->find_extra_svk_parents
3654 ($ed, $props->{"svk:merge"}, \@parents);
3656 if ( $props->{"svn:mergeinfo"} ) {
3657 $self->find_extra_svn_parents
3659 $props->{"svn:mergeinfo"},
3664 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3665 print $un "r$rev\n" or croak $!;
3666 print $un $_, "\n" foreach @$untracked;
3667 my %log_entry = ( parents => \@parents, revision => $rev,
3671 my $logged = delete $self->{logged_rev_props};
3672 if (!$logged || $self->{-want_revprops}) {
3673 my $rp = $self->ra->rev_proplist($rev);
3674 foreach (sort keys %$rp) {
3676 if (/^svn:(author|date|log)$/) {
3677 $log_entry{$1} = $v;
3678 } elsif ($_ eq 'svm:headrev') {
3681 print $un " rev_prop: ", uri_encode($_), ' ',
3682 uri_encode($v), "\n";
3686 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3688 close $un or croak $!;
3690 $log_entry{date} = parse_svn_date($log_entry{date});
3691 $log_entry{log} .= "\n";
3692 my $author = $log_entry{author} = check_author($log_entry{author});
3693 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3696 my ($commit_name, $commit_email) = ($name, $email);
3697 if ($_use_log_author) {
3699 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3701 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3704 if (!defined $name_field) {
3705 if (!defined $email) {
3708 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3709 ($name, $email) = ($1, $2);
3710 } elsif ($name_field =~ /(.*)@/) {
3711 ($name, $email) = ($1, $name_field);
3713 ($name, $email) = ($name_field, $name_field);
3716 if (defined $headrev && $self->use_svm_props) {
3717 if ($self->rewrite_root) {
3718 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3721 if ($self->rewrite_uuid) {
3722 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3725 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3726 # we don't want "SVM: initializing mirror for junk" ...
3727 return undef if $r == 0;
3728 my $svm = $self->svm;
3729 if ($uuid ne $svm->{uuid}) {
3730 die "UUID mismatch on SVM path:\n",
3731 "expected: $svm->{uuid}\n",
3734 my $full_url = $self->full_url;
3735 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3736 die "Failed to replace '$svm->{replace}' with ",
3737 "'$svm->{source}' in $full_url\n";
3738 # throw away username for storing in records
3739 remove_username($full_url);
3740 $log_entry{metadata} = "$full_url\@$r $uuid";
3741 $log_entry{svm_revision} = $r;
3742 $email ||= "$author\@$uuid";
3743 $commit_email ||= "$author\@$uuid";
3744 } elsif ($self->use_svnsync_props) {
3745 my $full_url = $self->svnsync->{url};
3746 $full_url .= "/$self->{path}" if length $self->{path};
3747 remove_username($full_url);
3748 my $uuid = $self->svnsync->{uuid};
3749 $log_entry{metadata} = "$full_url\@$rev $uuid";
3750 $email ||= "$author\@$uuid";
3751 $commit_email ||= "$author\@$uuid";
3753 my $url = $self->metadata_url;
3754 remove_username($url);
3755 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3756 $log_entry{metadata} = "$url\@$rev " . $uuid;
3757 $email ||= "$author\@" . $uuid;
3758 $commit_email ||= "$author\@" . $uuid;
3760 $log_entry{name} = $name;
3761 $log_entry{email} = $email;
3762 $log_entry{commit_name} = $commit_name;
3763 $log_entry{commit_email} = $commit_email;
3768 my ($self, $min_rev, $max_rev, @parents) = @_;
3769 my ($last_rev, $last_commit) = $self->last_rev_commit;
3770 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3771 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3775 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3776 $self->{inject_parents} = { $rev => $tree };
3777 $self->fetch(undef, undef);
3781 my ($self, $tree) = (shift, shift);
3782 my $log_entry = ::get_commit_entry($tree);
3783 unless ($self->{last_rev}) {
3784 ::fatal("Must have an existing revision to commit");
3786 my %ed_opts = ( r => $self->{last_rev},
3787 log => $log_entry->{log},
3789 tree_a => $self->{last_commit},
3792 $self->set_tree_cb($log_entry, $tree, @_) },
3793 svn_path => $self->{path} );
3794 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3795 print "No changes\nr$self->{last_rev} = $tree\n";
3799 sub rebuild_from_rev_db {
3800 my ($self, $path) = @_;
3802 open my $fh, '<', $path or croak "open: $!";
3803 binmode $fh or croak "binmode: $!";
3805 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3808 next if $_ eq ('0' x 40);
3809 $self->rev_map_set($r, $_);
3812 close $fh or croak "close: $!";
3813 unlink $path or croak "unlink: $!";
3818 my $map_path = $self->map_path;
3819 my $partial = (-e $map_path && ! -z $map_path);
3820 return unless ::verify_ref($self->refname.'^0');
3821 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3822 my $rev_db = $self->rev_db_path;
3823 $self->rebuild_from_rev_db($rev_db);
3824 if ($self->use_svm_props) {
3825 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3826 $self->rebuild_from_rev_db($svm_rev_db);
3828 $self->unlink_rev_db_symlink;
3831 print "Rebuilding $map_path ...\n" if (!$partial);
3832 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3835 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3836 ($head ? "$head.." : "") . $self->refname,
3838 my $metadata_url = $self->metadata_url;
3839 remove_username($metadata_url);
3840 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3843 if ( m{^commit ($::sha1)$} ) {
3847 next unless s{^\s*(git-svn-id:)}{$1};
3848 my ($url, $rev, $uuid) = ::extract_metadata($_);
3849 remove_username($url);
3851 # ignore merges (from set-tree)
3852 next if (!defined $rev || !$uuid);
3854 # if we merged or otherwise started elsewhere, this is
3855 # how we break out of it
3856 if (($uuid ne $svn_uuid) ||
3857 ($metadata_url && $url && ($url ne $metadata_url))) {
3860 if ($partial && $head) {
3861 print "Partial-rebuilding $map_path ...\n";
3862 print "Currently at $base_rev = $head\n";
3866 $self->rev_map_set($rev, $c);
3867 print "r$rev = $c\n";
3869 command_close_pipe($log, $ctx);
3870 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3871 my $rev_db_path = $self->rev_db_path;
3872 if (-f $self->rev_db_path) {
3873 unlink $self->rev_db_path or croak "unlink: $!";
3875 $self->unlink_rev_db_symlink;
3879 # Tie::File seems to be prone to offset errors if revisions get sparse,
3880 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3881 # one of my favorite modules is out :< Next up would be one of the DBM
3882 # modules, but I'm not sure which is most portable...
3884 # This is the replacement for the rev_db format, which was too big
3885 # and inefficient for large repositories with a lot of sparse history
3888 # The format is this:
3889 # - 24 bytes for every record,
3890 # * 4 bytes for the integer representing an SVN revision number
3891 # * 20 bytes representing the sha1 of a git commit
3892 # - No empty padding records like the old format
3893 # (except the last record, which can be overwritten)
3894 # - new records are written append-only since SVN revision numbers
3895 # increase monotonically
3896 # - lookups on SVN revision number are done via a binary search
3897 # - Piping the file to xxd -c24 is a good way of dumping it for
3898 # viewing or editing (piped back through xxd -r), should the need
3900 # - The last record can be padding revision with an all-zero sha1
3901 # This is used to optimize fetch performance when using multiple
3902 # "fetch" directives in .git/config
3904 # These files are disposable unless noMetadata or useSvmProps is set
3907 my ($fh, $rev, $commit) = @_;
3909 binmode $fh or croak "binmode: $!";
3910 my $size = (stat($fh))[7];
3911 ($size % 24) == 0 or croak "inconsistent size: $size";
3915 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3916 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3917 $read == 24 or croak "read only $read bytes (!= 24)";
3918 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3919 if ($last_commit eq ('0' x40)) {
3921 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3922 $read = sysread($fh, $buf, 24) or
3925 croak "read only $read bytes (!= 24)";
3926 ($last_rev, $last_commit) =
3927 unpack(rev_map_fmt, $buf);
3928 if ($last_commit eq ('0' x40)) {
3929 croak "inconsistent .rev_map\n";
3932 if ($last_rev >= $rev) {
3933 croak "last_rev is higher!: $last_rev >= $rev";
3938 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3939 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3943 sub _rev_map_reset {
3944 my ($fh, $rev, $commit) = @_;
3945 my $c = _rev_map_get($fh, $rev);
3946 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3947 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3948 truncate $fh, $offset or croak "truncate: $!";
3954 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3955 mkpath([$dir]) unless -d $dir;
3956 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3957 close $fh or die "Couldn't close (create) $path: $!\n";
3962 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3963 defined $commit or die "missing arg3\n";
3964 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3965 my $db = $self->map_path($uuid);
3966 my $db_lock = "$db.lock";
3970 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3971 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3975 $LOCKFILES{$db_lock} = 1;
3977 # both of these options make our .rev_db file very, very important
3978 # and we can't afford to lose it because rebuild() won't work
3979 if ($self->use_svm_props || $self->no_metadata) {
3981 copy($db, $db_lock) or die "rev_map_set(@_): ",
3983 "$db => $db_lock ($!)\n";
3985 rename $db, $db_lock or die "rev_map_set(@_): ",
3986 "Failed to rename: ",
3987 "$db => $db_lock ($!)\n";
3990 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3991 or croak "Couldn't open $db_lock: $!\n";
3992 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3993 _rev_map_set($fh, $rev, $commit);
3995 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3996 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3998 close $fh or croak $!;
4002 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4003 command_noisy('update-ref', '-m', "r$rev$note",
4004 $self->refname, $commit);
4006 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4007 "$db_lock => $db ($!)\n";
4008 delete $LOCKFILES{$db_lock};
4010 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
4011 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
4012 kill $sig, $$ if defined $sig;
4016 # If want_commit, this will return an array of (rev, commit) where
4017 # commit _must_ be a valid commit in the archive.
4018 # Otherwise, it'll return the max revision (whether or not the
4019 # commit is valid or just a 0x40 placeholder).
4021 my ($self, $want_commit) = @_;
4023 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4024 $want_commit ? ($r, $c) : $r;
4027 sub rev_map_max_norebuild {
4028 my ($self, $want_commit) = @_;
4029 my $map_path = $self->map_path;
4030 stat $map_path or return $want_commit ? (0, undef) : 0;
4031 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4032 binmode $fh or croak "binmode: $!";
4033 my $size = (stat($fh))[7];
4034 ($size % 24) == 0 or croak "inconsistent size: $size";
4037 close $fh or croak "close: $!";
4038 return $want_commit ? (0, undef) : 0;
4041 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4042 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4043 my ($r, $c) = unpack(rev_map_fmt, $buf);
4044 if ($want_commit && $c eq ('0' x40)) {
4046 return $want_commit ? (0, undef) : 0;
4048 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4049 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4050 ($r, $c) = unpack(rev_map_fmt, $buf);
4051 if ($c eq ('0'x40)) {
4052 croak "Penultimate record is all-zeroes in $map_path";
4055 close $fh or croak "close: $!";
4056 $want_commit ? ($r, $c) : $r;
4060 my ($self, $rev, $uuid) = @_;
4061 my $map_path = $self->map_path($uuid);
4062 return undef unless -e $map_path;
4064 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4065 my $c = _rev_map_get($fh, $rev);
4066 close($fh) or croak "close: $!";
4071 my ($fh, $rev) = @_;
4073 binmode $fh or croak "binmode: $!";
4074 my $size = (stat($fh))[7];
4075 ($size % 24) == 0 or croak "inconsistent size: $size";
4081 my ($l, $u) = (0, $size - 24);
4085 my $i = int(($l/24 + $u/24) / 2) * 24;
4086 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4087 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4088 my ($r, $c) = unpack(rev_map_fmt, $buf);
4092 } elsif ($r > $rev) {
4094 } else { # $r == $rev
4095 return $c eq ('0' x 40) ? undef : $c;
4101 # Finds the first svn revision that exists on (if $eq_ok is true) or
4102 # before $rev for the current branch. It will not search any lower
4103 # than $min_rev. Returns the git commit hash and svn revision number
4104 # if found, else (undef, undef).
4105 sub find_rev_before {
4106 my ($self, $rev, $eq_ok, $min_rev) = @_;
4107 --$rev unless $eq_ok;
4109 my $max_rev = $self->rev_map_max;
4110 $rev = $max_rev if ($rev > $max_rev);
4111 while ($rev >= $min_rev) {
4112 if (my $c = $self->rev_map_get($rev)) {
4117 return (undef, undef);
4120 # Finds the first svn revision that exists on (if $eq_ok is true) or
4121 # after $rev for the current branch. It will not search any higher
4122 # than $max_rev. Returns the git commit hash and svn revision number
4123 # if found, else (undef, undef).
4124 sub find_rev_after {
4125 my ($self, $rev, $eq_ok, $max_rev) = @_;
4126 ++$rev unless $eq_ok;
4127 $max_rev ||= $self->rev_map_max;
4128 while ($rev <= $max_rev) {
4129 if (my $c = $self->rev_map_get($rev)) {
4134 return (undef, undef);
4138 my ($class, $repo_id, $ref_id, $path) = @_;
4139 unless (defined $repo_id && length $repo_id) {
4140 $repo_id = $Git::SVN::default_repo_id;
4142 unless (defined $ref_id && length $ref_id) {
4143 $_prefix = '' unless defined($_prefix);
4145 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4148 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4150 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4151 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4152 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4153 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4154 if (-d $old_dir && ! -d $dir) {
4159 $_[3] = $path = '' unless (defined $path);
4162 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4163 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4164 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4167 # for read-only access of old .rev_db formats
4168 sub unlink_rev_db_symlink {
4170 my $link = $self->rev_db_path;
4171 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4173 unlink $link or croak "unlink: $link failed!";
4178 my ($self, $uuid) = @_;
4179 my $db_path = $self->map_path($uuid);
4180 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4181 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4185 # the new replacement for .rev_db
4187 my ($self, $uuid) = @_;
4188 $uuid ||= $self->ra_uuid;
4189 "$self->{map_root}.$uuid";
4194 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4200 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4204 sub remove_username {
4205 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4208 package Git::SVN::Prompt;
4212 use vars qw/$_no_auth_cache $_username/;
4215 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4216 $may_save = undef if $_no_auth_cache;
4217 $default_username = $_username if defined $_username;
4218 if (defined $default_username && length $default_username) {
4219 if (defined $realm && length $realm) {
4220 print STDERR "Authentication realm: $realm\n";
4223 $cred->username($default_username);
4225 username($cred, $realm, $may_save, $pool);
4227 $cred->password(_read_password("Password for '" .
4228 $cred->username . "': ", $realm));
4229 $cred->may_save($may_save);
4230 $SVN::_Core::SVN_NO_ERROR;
4233 sub ssl_server_trust {
4234 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4235 $may_save = undef if $_no_auth_cache;
4236 print STDERR "Error validating server certificate for '$realm':\n";
4239 # All variables SVN::Auth::SSL::* are used only once,
4240 # so we're shutting up Perl warnings about this.
4241 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4242 print STDERR " - The certificate is not issued ",
4243 "by a trusted authority. Use the\n",
4244 " fingerprint to validate ",
4245 "the certificate manually!\n";
4247 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4248 print STDERR " - The certificate hostname ",
4249 "does not match.\n";
4251 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4252 print STDERR " - The certificate is not yet valid.\n";
4254 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4255 print STDERR " - The certificate has expired.\n";
4257 if ($failures & $SVN::Auth::SSL::OTHER) {
4258 print STDERR " - The certificate has ",
4259 "an unknown error.\n";
4261 } # no warnings 'once'
4263 "Certificate information:\n".
4264 " - Hostname: %s\n".
4265 " - Valid: from %s until %s\n".
4267 " - Fingerprint: %s\n",
4268 map $cert_info->$_, qw(hostname valid_from valid_until
4269 issuer_dname fingerprint);
4272 print STDERR $may_save ?
4273 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4274 "(R)eject or accept (t)emporarily? ";
4276 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4277 if ($choice =~ /^t$/i) {
4278 $cred->may_save(undef);
4279 } elsif ($choice =~ /^r$/i) {
4281 } elsif ($may_save && $choice =~ /^p$/i) {
4282 $cred->may_save($may_save);
4286 $cred->accepted_failures($failures);
4287 $SVN::_Core::SVN_NO_ERROR;
4290 sub ssl_client_cert {
4291 my ($cred, $realm, $may_save, $pool) = @_;
4292 $may_save = undef if $_no_auth_cache;
4293 print STDERR "Client certificate filename: ";
4295 chomp(my $filename = <STDIN>);
4296 $cred->cert_file($filename);
4297 $cred->may_save($may_save);
4298 $SVN::_Core::SVN_NO_ERROR;
4301 sub ssl_client_cert_pw {
4302 my ($cred, $realm, $may_save, $pool) = @_;
4303 $may_save = undef if $_no_auth_cache;
4304 $cred->password(_read_password("Password: ", $realm));
4305 $cred->may_save($may_save);
4306 $SVN::_Core::SVN_NO_ERROR;
4310 my ($cred, $realm, $may_save, $pool) = @_;
4311 $may_save = undef if $_no_auth_cache;
4312 if (defined $realm && length $realm) {
4313 print STDERR "Authentication realm: $realm\n";
4316 if (defined $_username) {
4317 $username = $_username;
4319 print STDERR "Username: ";
4321 chomp($username = <STDIN>);
4323 $cred->username($username);
4324 $cred->may_save($may_save);
4325 $SVN::_Core::SVN_NO_ERROR;
4328 sub _read_password {
4329 my ($prompt, $realm) = @_;
4331 if (exists $ENV{GIT_ASKPASS}) {
4332 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4334 $password =~ s/[\012\015]//; # \n\r
4337 print STDERR $prompt;
4339 require Term::ReadKey;
4340 Term::ReadKey::ReadMode('noecho');
4341 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4342 last if $key =~ /[\012\015]/; # \n\r
4345 Term::ReadKey::ReadMode('restore');
4352 package SVN::Git::Fetcher;
4353 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4354 @deleted_gpath %added_placeholder $repo_id/;
4358 use File::Basename qw/dirname/;
4361 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4363 my ($class, $git_svn, $switch_path) = @_;
4364 my $self = SVN::Delta::Editor->new;
4365 bless $self, $class;
4366 if (exists $git_svn->{last_commit}) {
4367 $self->{c} = $git_svn->{last_commit};
4368 $self->{empty_symlinks} =
4369 _mark_empty_symlinks($git_svn, $switch_path);
4372 # some options are read globally, but can be overridden locally
4373 # per [svn-remote "..."] section. Command-line options will *NOT*
4374 # override options set in an [svn-remote "..."] section
4375 $repo_id = $git_svn->{repo_id};
4376 my $k = "svn-remote.$repo_id.ignore-paths";
4377 my $v = eval { command_oneline('config', '--get', $k) };
4378 $self->{ignore_regex} = $v;
4380 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4381 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4382 if ($v && $v eq 'true') {
4383 $_preserve_empty_dirs = 1;
4384 $k = "svn-remote.$repo_id.placeholder-filename";
4385 $v = eval { command_oneline('config', '--get', $k) };
4386 $_placeholder_filename = $v;
4389 # Load the list of placeholder files added during previous invocations.
4390 $k = "svn-remote.$repo_id.added-placeholder";
4391 $v = eval { command_oneline('config', '--get-all', $k) };
4392 if ($_preserve_empty_dirs && $v) {
4393 # command() prints errors to stderr, so we only call it if
4394 # command_oneline() succeeded.
4395 my @v = command('config', '--get-all', $k);
4396 $added_placeholder{ dirname($_) } = $_ foreach @v;
4399 $self->{empty} = {};
4400 $self->{dir_prop} = {};
4401 $self->{file_prop} = {};
4402 $self->{absent_dir} = {};
4403 $self->{absent_file} = {};
4404 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4405 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4409 # this uses the Ra object, so it must be called before do_{switch,update},
4410 # not inside them (when the Git::SVN::Fetcher object is passed) to
4411 # do_{switch,update}
4412 sub _mark_empty_symlinks {
4413 my ($git_svn, $switch_path) = @_;
4414 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4415 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4418 my ($rev, $cmt) = $git_svn->last_rev_commit;
4419 return {} unless ($rev && $cmt);
4421 # allow the warning to be printed for each revision we fetch to
4422 # ensure the user sees it. The user can also disable the workaround
4423 # on the repository even while git svn is running and the next
4424 # revision fetched will skip this expensive function.
4425 my $printed_warning;
4426 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4427 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4429 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4430 $pfx .= '/' if length($pfx);
4433 s/\A100644 blob $empty_blob\t//o or next;
4434 unless ($printed_warning) {
4435 print STDERR "Scanning for empty symlinks, ",
4436 "this may take a while if you have ",
4437 "many empty files\n",
4438 "You may disable this with `",
4439 "git config svn.brokenSymlinkWorkaround ",
4441 "This may be done in a different ",
4442 "terminal without restarting ",
4444 $printed_warning = 1;
4447 my (undef, $props) =
4448 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4449 if ($props->{'svn:special'}) {
4453 command_close_pipe($ls, $ctx);
4457 # returns true if a given path is inside a ".git" directory
4459 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4462 # return value: 0 -- don't ignore, 1 -- ignore
4463 sub is_path_ignored {
4464 my ($self, $path) = @_;
4465 return 1 if in_dot_git($path);
4466 return 1 if defined($self->{ignore_regex}) &&
4467 $path =~ m!$self->{ignore_regex}!;
4468 return 0 unless defined($_ignore_regex);
4469 return 1 if $path =~ m!$_ignore_regex!o;
4473 sub set_path_strip {
4474 my ($self, $path) = @_;
4475 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4482 sub open_directory {
4483 my ($self, $path, $pb, $rev) = @_;
4488 my ($self, $path) = @_;
4489 if (my $enc = $self->{pathnameencoding}) {
4491 Encode::from_to($path, 'UTF-8', $enc);
4493 if ($self->{path_strip}) {
4494 $path =~ s!$self->{path_strip}!! or
4495 die "Failed to strip path '$path' ($self->{path_strip})\n";
4501 my ($self, $path, $rev, $pb) = @_;
4502 return undef if $self->is_path_ignored($path);
4504 my $gpath = $self->git_path($path);
4505 return undef if ($gpath eq '');
4507 # remove entire directories.
4508 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4509 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4511 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4517 my $rmpath = "$gpath/$_";
4518 $self->{gii}->remove($rmpath);
4519 print "\tD\t$rmpath\n" unless $::_q;
4521 print "\tD\t$gpath/\n" unless $::_q;
4522 command_close_pipe($ls, $ctx);
4524 $self->{gii}->remove($gpath);
4525 print "\tD\t$gpath\n" unless $::_q;
4527 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4528 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4529 $self->{empty}->{$path} = 0;
4534 my ($self, $path, $pb, $rev) = @_;
4537 goto out if $self->is_path_ignored($path);
4539 my $gpath = $self->git_path($path);
4540 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4541 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4542 unless (defined $mode && defined $blob) {
4543 die "$path was not found in commit $self->{c} (r$rev)\n";
4545 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4549 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4550 pool => SVN::Pool->new, action => 'M' };
4554 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4557 if (!$self->is_path_ignored($path)) {
4558 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4559 delete $self->{empty}->{$dir};
4562 if ($added_placeholder{$dir}) {
4563 # Remove our placeholder file, if we created one.
4564 delete_entry($self, $added_placeholder{$dir})
4565 unless $path eq $added_placeholder{$dir};
4566 delete $added_placeholder{$dir}
4570 { path => $path, mode_a => $mode, mode_b => $mode,
4571 pool => SVN::Pool->new, action => 'A' };
4575 my ($self, $path, $cp_path, $cp_rev) = @_;
4576 goto out if $self->is_path_ignored($path);
4577 my $gpath = $self->git_path($path);
4579 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4585 $self->{gii}->remove($_);
4586 print "\tD\t$_\n" unless $::_q;
4587 push @deleted_gpath, $gpath;
4589 command_close_pipe($ls, $ctx);
4590 $self->{empty}->{$path} = 0;
4592 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4593 delete $self->{empty}->{$dir};
4594 $self->{empty}->{$path} = 1;
4596 if ($added_placeholder{$dir}) {
4597 # Remove our placeholder file, if we created one.
4598 delete_entry($self, $added_placeholder{$dir});
4599 delete $added_placeholder{$dir}
4606 sub change_dir_prop {
4607 my ($self, $db, $prop, $value) = @_;
4608 return undef if $self->is_path_ignored($db->{path});
4609 $self->{dir_prop}->{$db->{path}} ||= {};
4610 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4614 sub absent_directory {
4615 my ($self, $path, $pb) = @_;
4616 return undef if $self->is_path_ignored($path);
4617 $self->{absent_dir}->{$pb->{path}} ||= [];
4618 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4623 my ($self, $path, $pb) = @_;
4624 return undef if $self->is_path_ignored($path);
4625 $self->{absent_file}->{$pb->{path}} ||= [];
4626 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4630 sub change_file_prop {
4631 my ($self, $fb, $prop, $value) = @_;
4632 return undef if $self->is_path_ignored($fb->{path});
4633 if ($prop eq 'svn:executable') {
4634 if ($fb->{mode_b} != 120000) {
4635 $fb->{mode_b} = defined $value ? 100755 : 100644;
4637 } elsif ($prop eq 'svn:special') {
4638 $fb->{mode_b} = defined $value ? 120000 : 100644;
4640 $self->{file_prop}->{$fb->{path}} ||= {};
4641 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4646 sub apply_textdelta {
4647 my ($self, $fb, $exp) = @_;
4648 return undef if $self->is_path_ignored($fb->{path});
4649 my $fh = $::_repository->temp_acquire('svn_delta');
4650 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4651 # (but $base does not,) so dup() it for reading in close_file
4652 open my $dup, '<&', $fh or croak $!;
4653 my $base = $::_repository->temp_acquire('git_blob');
4656 my ($base_is_link, $size);
4658 if ($fb->{mode_a} eq '120000' &&
4659 ! $self->{empty_symlinks}->{$fb->{path}}) {
4660 print $base 'link ' or die "print $!\n";
4664 $size = $::_repository->cat_blob($fb->{blob}, $base);
4665 die "Failed to read object $fb->{blob}" if ($size < 0);
4668 seek $base, 0, 0 or croak $!;
4669 my $got = ::md5sum($base);
4671 my $err = "Checksum mismatch: ".
4672 "$fb->{path} $fb->{blob}\n" .
4673 "expected: $exp\n" .
4675 if ($base_is_link) {
4677 "Retrying... (possibly ",
4678 "a bad symlink from SVN)\n";
4679 $::_repository->temp_reset($base);
4687 seek $base, 0, 0 or croak $!;
4689 $fb->{base} = $base;
4690 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4694 my ($self, $fb, $exp) = @_;
4695 return undef if $self->is_path_ignored($fb->{path});
4698 my $path = $self->git_path($fb->{path});
4699 if (my $fh = $fb->{fh}) {
4701 seek($fh, 0, 0) or croak $!;
4702 my $got = ::md5sum($fh);
4704 die "Checksum mismatch: $path\n",
4705 "expected: $exp\n got: $got\n";
4708 if ($fb->{mode_b} == 120000) {
4709 sysseek($fh, 0, 0) or croak $!;
4710 my $rd = sysread($fh, my $buf, 5);
4713 croak "sysread: $!\n";
4714 } elsif ($rd == 0) {
4715 warn "$path has mode 120000",
4716 " but it points to nothing\n",
4717 "converting to an empty file with mode",
4719 $fb->{mode_b} = '100644';
4720 } elsif ($buf ne 'link ') {
4721 warn "$path has mode 120000",
4722 " but is not a link\n";
4724 my $tmp_fh = $::_repository->temp_acquire(
4727 while ($res = sysread($fh, my $str, 1024)) {
4728 my $out = syswrite($tmp_fh, $str, $res);
4729 defined($out) && $out == $res
4731 Git::temp_path($tmp_fh),
4734 defined $res or croak $!;
4736 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4737 Git::temp_release($tmp_fh, 1);
4741 $hash = $::_repository->hash_and_insert_object(
4742 Git::temp_path($fh));
4743 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4745 Git::temp_release($fb->{base}, 1);
4746 Git::temp_release($fh, 1);
4748 $hash = $fb->{blob} or die "no blob information\n";
4751 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4752 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4758 $self->{nr} = $self->{gii}->{nr};
4759 delete $self->{gii};
4760 $self->SUPER::abort_edit(@_);
4766 if ($_preserve_empty_dirs) {
4769 # Any entry flagged as empty that also has an associated
4770 # dir_prop represents a newly created empty directory.
4771 foreach my $i (keys %{$self->{empty}}) {
4772 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4775 # Search for directories that have become empty due subsequent
4777 push @empty_dirs, $self->find_empty_directories();
4779 # Finally, add a placeholder file to each empty directory.
4780 $self->add_placeholder_file($_) foreach (@empty_dirs);
4782 $self->stash_placeholder_list();
4785 $self->{git_commit_ok} = 1;
4786 $self->{nr} = $self->{gii}->{nr};
4787 delete $self->{gii};
4788 $self->SUPER::close_edit(@_);
4791 sub find_empty_directories {
4794 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4796 foreach my $dir (sort keys %dirs) {
4797 next if $dir eq ".";
4799 # If there have been any additions to this directory, there is
4800 # no reason to check if it is empty.
4802 foreach my $t (qw/dir_prop file_prop/) {
4803 foreach my $path (keys %{ $self->{$t} }) {
4804 if (exists $self->{$t}->{dirname($path)}) {
4809 last if $skip_added;
4811 next if $skip_added;
4813 # Use `git ls-tree` to get the filenames of this directory
4814 # that existed prior to this particular commit.
4815 my $ls = command('ls-tree', '-z', '--name-only',
4816 $self->{c}, "$dir/");
4817 my %files = map { $_ => 1 } split(/\0/, $ls);
4819 # Remove the filenames that were deleted during this commit.
4820 delete $files{$_} foreach (@deleted_gpath);
4822 # Report the directory if there are no filenames left.
4823 push @empty_dirs, $dir unless (scalar %files);
4828 sub add_placeholder_file {
4829 my ($self, $dir) = @_;
4830 my $path = "$dir/$_placeholder_filename";
4831 my $gpath = $self->git_path($path);
4833 my $fh = $::_repository->temp_acquire($gpath);
4834 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4835 Git::temp_release($fh, 1);
4836 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4838 # The directory should no longer be considered empty.
4839 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4841 # Keep track of any placeholder files we create.
4842 $added_placeholder{$dir} = $path;
4845 sub stash_placeholder_list {
4847 my $k = "svn-remote.$repo_id.added-placeholder";
4848 my $v = eval { command_oneline('config', '--get-all', $k) };
4849 command_noisy('config', '--unset-all', $k) if $v;
4850 foreach (values %added_placeholder) {
4851 command_noisy('config', '--add', $k, $_);
4855 package SVN::Git::Editor;
4856 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4863 my ($class, $opts) = @_;
4864 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4865 die "$_ required!\n" unless (defined $opts->{$_});
4868 my $pool = SVN::Pool->new;
4869 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4870 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4873 # $opts->{ra} functions should not be used after this:
4874 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4875 $opts->{editor_cb}, $pool);
4876 my $self = SVN::Delta::Editor->new(@ce, $pool);
4877 bless $self, $class;
4878 foreach (qw/svn_path r tree_a tree_b/) {
4879 $self->{$_} = $opts->{$_};
4881 $self->{url} = $opts->{ra}->{url};
4882 $self->{mods} = $mods;
4883 $self->{types} = $types;
4884 $self->{pool} = $pool;
4885 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4887 $self->{path_prefix} = length $self->{svn_path} ?
4888 "$self->{svn_path}/" : '';
4889 $self->{config} = $opts->{config};
4890 $self->{mergeinfo} = $opts->{mergeinfo};
4895 my ($tree_a, $tree_b) = @_;
4896 my @diff_tree = qw(diff-tree -z -r);
4897 if ($_cp_similarity) {
4898 push @diff_tree, "-C$_cp_similarity";
4900 push @diff_tree, '-C';
4902 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4903 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4904 push @diff_tree, $tree_a, $tree_b;
4905 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4909 while (<$diff_fh>) {
4910 chomp $_; # this gets rid of the trailing "\0"
4911 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4912 ($::sha1)\s($::sha1)\s
4913 ([MTCRAD])\d*$/xo) {
4914 push @mods, { mode_a => $1, mode_b => $2,
4915 sha1_a => $3, sha1_b => $4,
4917 if ($5 =~ /^(?:C|R)$/) {
4922 } elsif ($state eq 'file_a') {
4923 my $x = $mods[$#mods] or croak "Empty array\n";
4924 if ($x->{chg} !~ /^(?:C|R)$/) {
4925 croak "Error parsing $_, $x->{chg}\n";
4929 } elsif ($state eq 'file_b') {
4930 my $x = $mods[$#mods] or croak "Empty array\n";
4931 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4932 croak "Error parsing $_, $x->{chg}\n";
4934 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4935 croak "Error parsing $_, $x->{chg}\n";
4940 croak "Error parsing $_\n";
4943 command_close_pipe($diff_fh, $ctx);
4947 sub check_diff_paths {
4948 my ($ra, $pfx, $rev, $mods) = @_;
4950 $pfx .= '/' if length $pfx;
4952 sub type_diff_paths {
4953 my ($ra, $types, $path, $rev) = @_;
4954 my @p = split m#/+#, $path;
4956 unless (defined $types->{$c}) {
4957 $types->{$c} = $ra->check_path($c, $rev);
4960 $c .= '/' . shift @p;
4961 next if defined $types->{$c};
4962 $types->{$c} = $ra->check_path($c, $rev);
4966 foreach my $m (@$mods) {
4967 foreach my $f (qw/file_a file_b/) {
4968 next unless defined $m->{$f};
4969 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4970 if (length $pfx.$dir && ! defined $types{$dir}) {
4971 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4979 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4983 my ($self, $path) = @_;
4984 if (my $enc = $self->{pathnameencoding}) {
4986 Encode::from_to($path, $enc, 'UTF-8');
4988 $self->{path_prefix}.(defined $path ? $path : '');
4992 my ($self, $path) = @_;
4993 if ($self->{url} =~ m#^https?://#) {
4994 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4996 $self->{url} . '/' . $self->repo_path($path);
5001 my $rm = $self->{rm};
5002 delete $rm->{''}; # we never delete the url we're tracking
5005 foreach (keys %$rm) {
5006 my @d = split m#/#, $_;
5010 $c .= '/' . shift @d;
5014 delete $rm->{$self->{svn_path}};
5015 delete $rm->{''}; # we never delete the url we're tracking
5018 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5023 my @dn = split m#/#, $_;
5025 delete $rm->{join '/', @dn};
5032 command_close_pipe($fh, $ctx);
5034 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5035 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5036 $self->close_directory($bat->{$d}, $p);
5037 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5038 print "\tD+\t$d/\n" unless $::_q;
5039 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5044 sub open_or_add_dir {
5045 my ($self, $full_path, $baton) = @_;
5046 my $t = $self->{types}->{$full_path};
5048 die "$full_path not known in r$self->{r} or we have a bug!\n";
5052 # SVN::Node::none and SVN::Node::file are used only once,
5053 # so we're shutting up Perl's warnings about them.
5054 if ($t == $SVN::Node::none) {
5055 return $self->add_directory($full_path, $baton,
5056 undef, -1, $self->{pool});
5057 } elsif ($t == $SVN::Node::dir) {
5058 return $self->open_directory($full_path, $baton,
5059 $self->{r}, $self->{pool});
5060 } # no warnings 'once'
5061 print STDERR "$full_path already exists in repository at ",
5062 "r$self->{r} and it is not a directory (",
5063 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5064 } # no warnings 'once'
5069 my ($self, $path) = @_;
5070 my $bat = $self->{bat};
5071 my $repo_path = $self->repo_path($path);
5072 return $bat->{''} unless (length $repo_path);
5073 my @p = split m#/+#, $repo_path;
5075 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
5078 $c .= '/' . shift @p;
5079 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
5084 # Subroutine to convert a globbing pattern to a regular expression.
5085 # From perl cookbook.
5087 my $globstr = shift;
5088 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5089 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5090 return '^' . $globstr . '$';
5093 sub check_autoprop {
5094 my ($self, $pattern, $properties, $file, $fbat) = @_;
5095 # Convert the globbing pattern to a regular expression.
5096 my $regex = glob2pat($pattern);
5097 # Check if the pattern matches the file name.
5098 if($file =~ m/($regex)/) {
5099 # Parse the list of properties to set.
5100 my @props = split(/;/, $properties);
5101 foreach my $prop (@props) {
5102 # Parse 'name=value' syntax and set the property.
5103 if ($prop =~ /([^=]+)=(.*)/) {
5104 my ($n,$v) = ($1,$2);
5108 $self->change_file_prop($fbat, $n, $v);
5114 sub apply_autoprops {
5115 my ($self, $file, $fbat) = @_;
5116 my $conf_t = ${$self->{config}}{'config'};
5118 # Check [miscellany]/enable-auto-props in svn configuration.
5119 if (SVN::_Core::svn_config_get_bool(
5121 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5122 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5124 # Auto-props are enabled. Enumerate them to look for matches.
5125 my $callback = sub {
5126 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5128 SVN::_Core::svn_config_enumerate(
5130 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5136 my ($self, $m) = @_;
5137 my ($dir, $file) = split_path($m->{file_b});
5138 my $pbat = $self->ensure_path($dir);
5139 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5141 print "\tA\t$m->{file_b}\n" unless $::_q;
5142 $self->apply_autoprops($file, $fbat);
5143 $self->chg_file($fbat, $m);
5144 $self->close_file($fbat,undef,$self->{pool});
5148 my ($self, $m) = @_;
5149 my ($dir, $file) = split_path($m->{file_b});
5150 my $pbat = $self->ensure_path($dir);
5151 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5152 $self->url_path($m->{file_a}), $self->{r});
5153 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5154 $self->chg_file($fbat, $m);
5155 $self->close_file($fbat,undef,$self->{pool});
5159 my ($self, $path, $pbat) = @_;
5160 my $rpath = $self->repo_path($path);
5161 my ($dir, $file) = split_path($rpath);
5162 $self->{rm}->{$dir} = 1;
5163 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5167 my ($self, $m) = @_;
5168 my ($dir, $file) = split_path($m->{file_b});
5169 my $pbat = $self->ensure_path($dir);
5170 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5171 $self->url_path($m->{file_a}), $self->{r});
5172 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5173 $self->apply_autoprops($file, $fbat);
5174 $self->chg_file($fbat, $m);
5175 $self->close_file($fbat,undef,$self->{pool});
5177 ($dir, $file) = split_path($m->{file_a});
5178 $pbat = $self->ensure_path($dir);
5179 $self->delete_entry($m->{file_a}, $pbat);
5183 my ($self, $m) = @_;
5184 my ($dir, $file) = split_path($m->{file_b});
5185 my $pbat = $self->ensure_path($dir);
5186 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5187 $pbat,$self->{r},$self->{pool});
5188 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5189 $self->chg_file($fbat, $m);
5190 $self->close_file($fbat,undef,$self->{pool});
5193 sub T { shift->M(@_) }
5195 sub change_file_prop {
5196 my ($self, $fbat, $pname, $pval) = @_;
5197 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5200 sub change_dir_prop {
5201 my ($self, $pbat, $pname, $pval) = @_;
5202 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5205 sub _chg_file_get_blob ($$$$) {
5206 my ($self, $fbat, $m, $which) = @_;
5207 my $fh = $::_repository->temp_acquire("git_blob_$which");
5208 if ($m->{"mode_$which"} =~ /^120/) {
5209 print $fh 'link ' or croak $!;
5210 $self->change_file_prop($fbat,'svn:special','*');
5211 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5212 $self->change_file_prop($fbat,'svn:special',undef);
5214 my $blob = $m->{"sha1_$which"};
5215 return ($fh,) if ($blob =~ /^0{40}$/);
5216 my $size = $::_repository->cat_blob($blob, $fh);
5217 croak "Failed to read object $blob" if ($size < 0);
5218 $fh->flush == 0 or croak $!;
5219 seek $fh, 0, 0 or croak $!;
5221 my $exp = ::md5sum($fh);
5222 seek $fh, 0, 0 or croak $!;
5227 my ($self, $fbat, $m) = @_;
5228 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5229 $self->change_file_prop($fbat,'svn:executable','*');
5230 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5231 $self->change_file_prop($fbat,'svn:executable',undef);
5233 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5234 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5235 my $pool = SVN::Pool->new;
5236 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5238 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5239 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5241 die "Unexpected result from send_txstream: $res\n",
5242 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5245 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5246 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5247 if ($got ne $exp_b);
5249 Git::temp_release($fh_b, 1);
5250 Git::temp_release($fh_a, 1);
5255 my ($self, $m) = @_;
5256 my ($dir, $file) = split_path($m->{file_b});
5257 my $pbat = $self->ensure_path($dir);
5258 print "\tD\t$m->{file_b}\n" unless $::_q;
5259 $self->delete_entry($m->{file_b}, $pbat);
5264 my ($p,$bat) = ($self->{pool}, $self->{bat});
5265 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5267 $self->close_directory($bat->{$_}, $p);
5269 $self->close_directory($bat->{''}, $p);
5270 $self->SUPER::close_edit($p);
5276 $self->SUPER::abort_edit($self->{pool});
5281 $self->SUPER::DESTROY(@_);
5282 $self->{pool}->clear;
5285 # this drives the editor
5288 my $mods = $self->{mods};
5289 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
5290 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5292 if (defined $o{$f}) {
5295 fatal("Invalid change type: $f");
5299 if (defined($self->{mergeinfo})) {
5300 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5301 $self->{mergeinfo});
5303 $self->rmdirs if $_rmdir;
5309 return scalar @$mods;
5312 package Git::SVN::Ra;
5313 use vars qw/@ISA $config_dir $_log_window_size/;
5316 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5319 # enforce temporary pool usage for some simple functions
5321 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5323 my $SUPER = "SUPER::$f";
5326 my $pool = SVN::Pool->new;
5327 my @ret = $self->$SUPER(@_,$pool);
5329 wantarray ? @ret : $ret[0];
5334 sub _auth_providers () {
5336 SVN::Client::get_simple_provider(),
5337 SVN::Client::get_ssl_server_trust_file_provider(),
5338 SVN::Client::get_simple_prompt_provider(
5339 \&Git::SVN::Prompt::simple, 2),
5340 SVN::Client::get_ssl_client_cert_file_provider(),
5341 SVN::Client::get_ssl_client_cert_prompt_provider(
5342 \&Git::SVN::Prompt::ssl_client_cert, 2),
5343 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5344 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5345 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5346 SVN::Client::get_username_provider(),
5347 SVN::Client::get_ssl_server_trust_prompt_provider(
5348 \&Git::SVN::Prompt::ssl_server_trust),
5349 SVN::Client::get_username_prompt_provider(
5350 \&Git::SVN::Prompt::username, 2)
5354 sub escape_uri_only {
5357 foreach (split m{/}, $uri) {
5358 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5366 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5367 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5368 $url = "$scheme://$domain$uri";
5374 my ($class, $url) = @_;
5376 return $RA if ($RA && $RA->{url} eq $url);
5380 SVN::_Core::svn_config_ensure($config_dir, undef);
5381 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5382 my $config = SVN::Core::config_get_config($config_dir);
5384 my $dont_store_passwords = 1;
5385 my $conf_t = ${$config}{'config'};
5388 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5389 # produces warnings that variables are used only once.
5390 # I had not found the better way to shut them up, so
5391 # the warnings of type 'once' are disabled in this block.
5392 if (SVN::_Core::svn_config_get_bool($conf_t,
5393 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5394 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5396 SVN::_Core::svn_auth_set_parameter($baton,
5397 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5398 bless (\$dont_store_passwords, "_p_void"));
5400 if (SVN::_Core::svn_config_get_bool($conf_t,
5401 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5402 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5404 $Git::SVN::Prompt::_no_auth_cache = 1;
5406 } # no warnings 'once'
5407 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5409 pool => SVN::Pool->new,
5410 auth_provider_callbacks => $callbacks);
5411 $self->{url} = $url;
5412 $self->{svn_path} = $url;
5413 $self->{repos_root} = $self->get_repos_root;
5414 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5415 $self->{cache} = { check_path => { r => 0, data => {} },
5416 get_dir => { r => 0, data => {} } };
5417 $RA = bless $self, $class;
5421 my ($self, $path, $r) = @_;
5422 my $cache = $self->{cache}->{check_path};
5423 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5424 return $cache->{data}->{$path};
5426 my $pool = SVN::Pool->new;
5427 my $t = $self->SUPER::check_path($path, $r, $pool);
5429 if ($r != $cache->{r}) {
5430 %{$cache->{data}} = ();
5433 $cache->{data}->{$path} = $t;
5437 my ($self, $dir, $r) = @_;
5438 my $cache = $self->{cache}->{get_dir};
5439 if ($r == $cache->{r}) {
5440 if (my $x = $cache->{data}->{$dir}) {
5441 return wantarray ? @$x : $x->[0];
5444 my $pool = SVN::Pool->new;
5445 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5446 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5448 if ($r != $cache->{r}) {
5449 %{$cache->{data}} = ();
5452 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5453 wantarray ? (\%dirents, $r, $props) : \%dirents;
5457 # do not call the real DESTROY since we store ourselves in $RA
5460 # get_log(paths, start, end, limit,
5461 # discover_changed_paths, strict_node_history, receiver)
5463 my ($self, @args) = @_;
5464 my $pool = SVN::Pool->new;
5466 # svn_log_changed_path_t objects passed to get_log are likely to be
5467 # overwritten even if only the refs are copied to an external variable,
5468 # so we should dup the structures in their entirety. Using an
5469 # externally passed pool (instead of our temporary and quickly cleared
5470 # pool in Git::SVN::Ra) does not help matters at all...
5471 my $receiver = pop @args;
5472 my $prefix = "/".$self->{svn_path};
5473 $prefix =~ s#/+($)##;
5474 my $prefix_regex = qr#^\Q$prefix\E#;
5476 my ($paths) = $_[0];
5477 return &$receiver(@_) unless $paths;
5479 foreach my $p (keys %$paths) {
5480 my $i = $paths->{$p};
5481 # Make path relative to our url, not repos_root
5482 $p =~ s/$prefix_regex//;
5483 my %s = map { $_ => $i->$_; }
5484 qw/copyfrom_path copyfrom_rev action/;
5485 if ($s{'copyfrom_path'}) {
5486 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5494 # the limit parameter was not supported in SVN 1.1.x, so we
5495 # drop it. Therefore, the receiver callback passed to it
5496 # is made aware of this limitation by being wrapped if
5497 # the limit passed to is being wrapped.
5498 if ($SVN::Core::VERSION le '1.2.0') {
5499 my $limit = splice(@args, 3, 1);
5501 my $receiver = pop @args;
5502 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5505 my $ret = $self->SUPER::get_log(@args, $pool);
5511 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5512 my $ctx = SVN::Client->new(auth => _auth_providers);
5513 my $out = IO::File->new_tmpfile;
5515 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5516 # $ctx->diff(), so we'll create a default one
5517 my $pool = SVN::Pool->new_default_sub;
5519 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5520 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5522 my $ret = (($out->stat)[7] == 0);
5523 close $out or croak $!;
5528 sub get_commit_editor {
5529 my ($self, $log, $cb, $pool) = @_;
5530 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5531 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5535 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5536 my $new = ($rev_a == $rev_b);
5537 my $path = $gs->{path};
5539 if ($new && -e $gs->{index}) {
5540 unlink $gs->{index} or die
5541 "Couldn't unlink index: $gs->{index}: $!\n";
5543 my $pool = SVN::Pool->new;
5544 $editor->set_path_strip($path);
5545 my (@pc) = split m#/#, $path;
5546 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5548 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5550 # Since we can't rely on svn_ra_reparent being available, we'll
5551 # just have to do some magic with set_path to make it so
5552 # we only want a partial path.
5554 my $final = join('/', @pc);
5556 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5557 $sp .= '/' if length $sp;
5560 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5562 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5564 $reporter->finish_report($pool);
5566 $editor->{git_commit_ok};
5569 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5570 # svn_ra_reparent didn't work before 1.4)
5572 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5573 my $path = $gs->{path};
5574 my $pool = SVN::Pool->new;
5576 my $full_url = $self->{url};
5577 my $old_url = $full_url;
5578 $full_url .= '/' . $path if length $path;
5579 my ($ra, $reparented);
5581 if ($old_url =~ m#^svn(\+ssh)?://# ||
5582 ($full_url =~ m#^https?://# &&
5583 escape_url($full_url) ne $full_url)) {
5587 $ra = Git::SVN::Ra->new($full_url);
5589 } elsif ($old_url ne $full_url) {
5590 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5591 $self->{url} = $full_url;
5596 $url_b = escape_url($url_b);
5597 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5598 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5599 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5600 $reporter->finish_report($pool);
5603 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5604 $self->{url} = $old_url;
5608 $editor->{git_commit_ok};
5611 sub longest_common_path {
5612 my ($gsv, $globs) = @_;
5614 my $common_max = scalar @$gsv;
5616 foreach my $gs (@$gsv) {
5617 my @tmp = split m#/#, $gs->{path};
5620 $p .= length($p) ? "/$_" : $_;
5626 $common_max += scalar @$globs;
5627 foreach my $glob (@$globs) {
5628 my @tmp = split m#/#, $glob->{path}->{left};
5631 $p .= length($p) ? "/$_" : $_;
5637 my $longest_path = '';
5638 foreach (sort {length $b <=> length $a} keys %common) {
5639 if ($common{$_} == $common_max) {
5647 sub gs_fetch_loop_common {
5648 my ($self, $base, $head, $gsv, $globs) = @_;
5649 return if ($base > $head);
5650 my $inc = $_log_window_size;
5651 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5652 my $longest_path = longest_common_path($gsv, $globs);
5653 my $ra_url = $self->{url};
5654 my $find_trailing_edge;
5658 my $err_handler = $SVN::Error::handler;
5659 $SVN::Error::handler = sub {
5661 skip_unknown_revs($err);
5664 my ($paths, $r, $author, $date, $log) = @_;
5666 { author => $author, date => $date, log => $log } ];
5668 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5669 sub { $revs{$_[1]} = _cb(@_) });
5671 print "Checked through r$max\r";
5673 $find_trailing_edge = 1;
5675 if ($err and $find_trailing_edge) {
5676 print STDERR "Path '$longest_path' ",
5677 "was probably deleted:\n",
5678 $err->expanded_message,
5679 "\nWill attempt to follow ",
5680 "revisions r$min .. r$max ",
5681 "committed before the deletion\n";
5683 while (--$hi >= $min) {
5685 $self->get_log([$longest_path], $min, $hi,
5688 $revs{$_[1]} = _cb(@_) });
5690 print STDERR "r$min .. r$ok OK\n";
5694 $find_trailing_edge = 0;
5696 $SVN::Error::handler = $err_handler;
5698 my %exists = map { $_->{path} => $_ } @$gsv;
5699 foreach my $r (sort {$a <=> $b} keys %revs) {
5700 my ($paths, $logged) = @{$revs{$r}};
5702 foreach my $gs ($self->match_globs(\%exists, $paths,
5704 if ($gs->rev_map_max >= $r) {
5707 next unless $gs->match_paths($paths, $r);
5708 $gs->{logged_rev_props} = $logged;
5709 if (my $last_commit = $gs->last_commit) {
5710 $gs->assert_index_clean($last_commit);
5712 my $log_entry = $gs->do_fetch($paths, $r);
5714 $gs->do_git_commit($log_entry);
5716 $INDEX_FILES{$gs->{index}} = 1;
5718 foreach my $g (@$globs) {
5719 my $k = "svn-remote.$g->{remote}." .
5721 Git::SVN::tmp_config($k, $r);
5727 $self = Git::SVN::Ra->new($ra_url);
5728 $ra_invalid = undef;
5731 # pre-fill the .rev_db since it'll eventually get filled in
5732 # with '0' x40 if something new gets committed
5733 foreach my $gs (@$gsv) {
5734 next if $gs->rev_map_max >= $max;
5735 next if defined $gs->rev_map_get($max);
5736 $gs->rev_map_set($max, 0 x40);
5738 foreach my $g (@$globs) {
5739 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5740 Git::SVN::tmp_config($k, $max);
5742 last if $max >= $head;
5745 $max = $head if ($max > $head);
5750 sub get_dir_globbed {
5751 my ($self, $left, $depth, $r) = @_;
5753 my @x = eval { $self->get_dir($left, $r) };
5754 return unless scalar @x == 3;
5755 my $dirents = $x[0];
5757 foreach my $de (keys %$dirents) {
5758 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5760 my @args = ("$left/$de", $depth - 1, $r);
5761 foreach my $dir ($self->get_dir_globbed(@args)) {
5762 push @finalents, "$de/$dir";
5765 push @finalents, $de;
5772 my ($self, $exists, $paths, $globs, $r) = @_;
5775 my ($self, $exists, $g, $r) = @_;
5777 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5778 $g->{path}->{depth},
5781 foreach my $de (@dirs) {
5782 my $p = $g->{path}->full_path($de);
5783 next if $exists->{$p};
5784 next if (length $g->{path}->{right} &&
5785 ($self->check_path($p, $r) !=
5787 next unless $p =~ /$g->{path}->{regex}/;
5788 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5789 $g->{ref}->full_path($de), 1);
5792 foreach my $g (@$globs) {
5793 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5794 if ($path->{action} =~ /^[AR]$/) {
5795 get_dir_check($self, $exists, $g, $r);
5798 foreach (keys %$paths) {
5799 if (/$g->{path}->{left_regex}/ &&
5800 !/$g->{path}->{regex}/) {
5801 next if $paths->{$_}->{action} !~ /^[AR]$/;
5802 get_dir_check($self, $exists, $g, $r);
5804 next unless /$g->{path}->{regex}/;
5806 my $pathname = $g->{path}->full_path($p);
5807 next if $exists->{$pathname};
5808 next if ($self->check_path($pathname, $r) !=
5810 $exists->{$pathname} = Git::SVN->init(
5811 $self->{url}, $pathname, undef,
5812 $g->{ref}->full_path($p), 1);
5815 foreach (split m#/#, $g->{path}->{left}) {
5817 next unless ($paths->{$c} &&
5818 ($paths->{$c}->{action} =~ /^[AR]$/));
5819 get_dir_check($self, $exists, $g, $r);
5827 return $self->{url} if ($self->{url} eq $self->{repos_root});
5828 my $url = $self->{repos_root};
5829 my @components = split(m!/!, $self->{svn_path});
5832 $url .= "/$c" if length $c;
5834 my $ra = (ref $self)->new($url);
5835 my $latest = $ra->get_latest_revnum;
5836 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5838 } while ($@ && ($c = shift @components));
5844 unless (defined $can_do_switch) {
5845 my $pool = SVN::Pool->new;
5847 $self->do_switch(1, '', 0, $self->{url},
5848 SVN::Delta::Editor->new, $pool);
5853 $rep->abort_report($pool);
5861 sub skip_unknown_revs {
5863 my $errno = $err->apr_err();
5864 # Maybe the branch we're tracking didn't
5865 # exist when the repo started, so it's
5866 # not an error if it doesn't, just continue
5868 # Wonderfully consistent library, eh?
5869 # 160013 - svn:// and file://
5870 # 175002 - http(s)://
5871 # 175007 - http(s):// (this repo required authorization, too...)
5872 # More codes may be discovered later...
5873 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5874 my $err_key = $err->expanded_message;
5875 # revision numbers change every time, filter them out
5876 $err_key =~ s/\d+/\0/g;
5877 $err_key = "$errno\0$err_key";
5878 unless ($ignored_err{$err_key}) {
5879 warn "W: Ignoring error from SVN, path probably ",
5880 "does not exist: ($errno): ",
5881 $err->expanded_message,"\n";
5882 warn "W: Do not be alarmed at the above message ",
5883 "git-svn is just searching aggressively for ",
5885 "This may take a while on large repositories\n";
5886 $ignored_err{$err_key} = 1;
5890 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5893 package Git::SVN::Log;
5896 use POSIX qw/strftime/;
5898 use constant commit_log_separator => ('-' x 72) . "\n";
5899 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5900 %rusers $show_commit $incremental/;
5905 return 1 if defined $c->{r};
5907 # big commit message got truncated by the 16k pretty buffer in rev-list
5908 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5909 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5911 my @log = command(qw/cat-file commit/, $c->{c});
5913 # shift off the headers
5914 shift @log while ($log[0] ne '');
5917 # TODO: make $c->{l} not have a trailing newline in the future
5918 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5920 (undef, $c->{r}, undef) = ::extract_metadata(
5921 (grep(/^git-svn-id: /, @log))[-1]);
5923 return defined $c->{r};
5927 return $color || Git->repository->get_colorbool('color.diff');
5930 sub git_svn_log_cmd {
5931 my ($r_min, $r_max, @args) = @_;
5933 my (@files, @log_opts);
5934 foreach my $x (@args) {
5935 if ($x eq '--' || @files) {
5938 if (::verify_ref("$x^0")) {
5946 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5947 $gs ||= Git::SVN->_new;
5948 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5950 push @cmd, '-r' unless $non_recursive;
5951 push @cmd, qw/--raw --name-status/ if $verbose;
5952 push @cmd, '--color' if log_use_color();
5953 push @cmd, @log_opts;
5954 if (defined $r_max && $r_max == $r_min) {
5955 push @cmd, '--max-count=1';
5956 if (my $c = $gs->rev_map_get($r_max)) {
5959 } elsif (defined $r_max) {
5960 if ($r_max < $r_min) {
5961 ($r_min, $r_max) = ($r_max, $r_min);
5963 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5964 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5965 # If there are no commits in the range, both $c_max and $c_min
5966 # will be undefined. If there is at least 1 commit in the
5967 # range, both will be defined.
5968 return () if !defined $c_min || !defined $c_max;
5969 if ($c_min eq $c_max) {
5970 push @cmd, '--max-count=1', $c_min;
5972 push @cmd, '--boundary', "$c_min..$c_max";
5975 return (@cmd, @files);
5978 # adapted from pager.c
5981 $ENV{GIT_PAGER_IN_USE} = 'false';
5985 chomp($pager = command_oneline(qw(var GIT_PAGER)));
5986 if ($pager eq 'cat') {
5989 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5993 return unless defined $pager;
5994 pipe my ($rfd, $wfd) or return;
5995 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5997 open STDOUT, '>&', $wfd or
5998 ::fatal "Can't redirect to stdout: $!";
6001 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6002 $ENV{LESS} ||= 'FRSX';
6003 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6006 sub format_svn_date {
6007 # some systmes don't handle or mishandle %z, so be creative.
6008 my $t = shift || time;
6009 my $gm = timelocal(gmtime($t));
6010 my $sign = qw( + + - )[ $t <=> $gm ];
6011 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
6012 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6015 sub parse_git_date {
6017 # Date::Parse isn't in the standard Perl distro :(
6018 if ($tz =~ s/^\+//) {
6019 $t += tz_to_s_offset($tz);
6020 } elsif ($tz =~ s/^\-//) {
6021 $t -= tz_to_s_offset($tz);
6026 sub set_local_timezone {
6034 sub tz_to_s_offset {
6037 return ($1 * 60) + ($tz * 3600);
6040 sub get_author_info {
6041 my ($dest, $author, $t, $tz) = @_;
6042 $author =~ s/(?:^\s*|\s*$)//g;
6043 $dest->{a_raw} = $author;
6046 $au = $rusers{$author} || undef;
6049 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6054 $dest->{t_utc} = parse_git_date($t, $tz);
6057 sub process_commit {
6058 my ($c, $r_min, $r_max, $defer) = @_;
6059 if (defined $r_min && defined $r_max) {
6060 if ($r_min == $c->{r} && $r_min == $r_max) {
6064 return 1 if $r_min == $r_max;
6065 if ($r_min < $r_max) {
6066 # we need to reverse the print order
6067 return 0 if (defined $limit && --$limit < 0);
6071 if ($r_min != $r_max) {
6072 return 1 if ($r_min < $c->{r});
6073 return 1 if ($r_max > $c->{r});
6076 return 0 if (defined $limit && --$limit < 0);
6085 if (my $l = $c->{l}) {
6086 while ($l->[0] =~ /^\s*$/) { shift @$l }
6089 $l_fmt ||= 'A' . length($c->{r});
6090 print 'r',pack($l_fmt, $c->{r}),' | ';
6091 print "$c->{c} | " if $show_commit;
6094 show_commit_normal($c);
6098 sub show_commit_changed_paths {
6100 return unless $c->{changed};
6101 print "Changed paths:\n", @{$c->{changed}};
6104 sub show_commit_normal {
6106 print commit_log_separator, "r$c->{r} | ";
6107 print "$c->{c} | " if $show_commit;
6108 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6111 if (my $l = $c->{l}) {
6112 while ($l->[$#$l] eq "\n" && $#$l > 0
6113 && $l->[($#$l - 1)] eq "\n") {
6116 $nr_line = scalar @$l;
6118 print "1 line\n\n\n";
6120 if ($nr_line == 1) {
6121 $nr_line = '1 line';
6123 $nr_line .= ' lines';
6125 print $nr_line, "\n";
6126 show_commit_changed_paths($c);
6128 print $_ foreach @$l;
6132 show_commit_changed_paths($c);
6136 foreach my $x (qw/raw stat diff/) {
6139 print $_ foreach @{$c->{$x}}
6146 my ($r_min, $r_max);
6147 my $r_last = -1; # prevent dupes
6148 set_local_timezone();
6149 if (defined $::_revision) {
6150 if ($::_revision =~ /^(\d+):(\d+)$/) {
6151 ($r_min, $r_max) = ($1, $2);
6152 } elsif ($::_revision =~ /^\d+$/) {
6153 $r_min = $r_max = $::_revision;
6155 ::fatal "-r$::_revision is not supported, use ",
6156 "standard 'git log' arguments instead";
6161 @args = git_svn_log_cmd($r_min, $r_max, @args);
6163 print commit_log_separator unless $incremental || $oneline;
6166 my $log = command_output_pipe(@args);
6168 my (@k, $c, $d, $stat);
6169 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6171 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6173 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6175 process_commit($c, $r_min, $r_max, \@k) or
6180 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6181 get_author_info($c, $1, $2, $3);
6182 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6184 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6185 push @{$c->{raw}}, $_;
6186 } elsif (/^${esc_color}[ACRMDT]\t/) {
6187 # we could add $SVN->{svn_path} here, but that requires
6188 # remote access at the moment (repo_path_split)...
6189 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6190 push @{$c->{changed}}, $_;
6191 } elsif (/^${esc_color}diff /o) {
6193 push @{$c->{diff}}, $_;
6195 push @{$c->{diff}}, $_;
6196 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6197 $esc_color*[\+\-]*$esc_color$/x) {
6199 push @{$c->{stat}}, $_;
6200 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6201 push @{$c->{stat}}, $_;
6203 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6204 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6205 } elsif (s/^${esc_color} //o) {
6206 push @{$c->{l}}, $_;
6209 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6211 process_commit($c, $r_min, $r_max, \@k);
6214 ($r_min, $r_max) = ($r_max, $r_min);
6215 process_commit($_, $r_min, $r_max) foreach reverse @k;
6219 print commit_log_separator unless $incremental || $oneline;
6228 my ($fh, $ctx, $rev);
6231 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6232 while (my $line = <$fh>) {
6233 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6234 # Uncommitted edits show up as a rev ID of
6235 # all zeros, which we can't look up with
6238 (undef, $rev, undef) =
6240 $rev = '0' if (!$rev);
6244 $rev = sprintf('%-10s', $rev);
6245 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6250 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6255 my %dsha; #distinct sha keys
6257 while (my $line = <$fh>) {
6258 push @buffer, $line;
6259 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6264 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6266 foreach my $line (@buffer) {
6267 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6269 $rev = '0' if (!$rev)
6271 elsif ($line =~ /^author (.*)/) {
6272 $authors{$rev} = $1;
6273 $authors{$rev} =~ s/\s/_/g;
6275 elsif ($line =~ /^\t(.*)$/) {
6276 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6280 command_close_pipe($fh, $ctx);
6283 package Git::SVN::Migration;
6284 # these version numbers do NOT correspond to actual version numbers
6285 # of git nor git-svn. They are just relative.
6287 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6289 # v1 layout: .git/$id/info/url, refs/remotes/$id
6291 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6293 # v3 layout: .git/svn/$id, refs/remotes/$id
6294 # - info/url may remain for backwards compatibility
6295 # - this is what we migrate up to this layout automatically,
6296 # - this will be used by git svn init on single branches
6297 # v3.1 layout (auto migrated):
6298 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6299 # for backwards compatibility
6301 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6302 # - this is only created for newly multi-init-ed
6303 # repositories. Similar in spirit to the
6304 # --use-separate-remotes option in git-clone (now default)
6305 # - we do not automatically migrate to this (following
6306 # the example set by core git)
6308 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6309 # - newer, more-efficient format that uses 24-bytes per record
6310 # with no filler space.
6311 # - use xxd -c24 < .rev_map.$UUID to view and debug
6312 # - This is a one-way migration, repositories updated to the
6313 # new format will not be able to use old git-svn without
6314 # rebuilding the .rev_db. Rebuilding the rev_db is not
6315 # possible if noMetadata or useSvmProps are set; but should
6316 # be no problem for users that use the (sensible) defaults.
6320 use File::Path qw/mkpath/;
6321 use File::Basename qw/dirname basename/;
6322 use vars qw/$_minimize/;
6324 sub migrate_from_v0 {
6325 my $git_dir = $ENV{GIT_DIR};
6326 return undef unless -d $git_dir;
6327 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6331 my ($id, $orig_ref) = ($_, $_);
6332 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6333 next unless -f "$git_dir/$id/info/url";
6334 my $new_ref = "refs/remotes/$id";
6335 if (::verify_ref("$new_ref^0")) {
6336 print STDERR "W: $orig_ref is probably an old ",
6337 "branch used by an ancient version of ",
6339 "However, $new_ref also exists.\n",
6340 "We will not be able ",
6341 "to use this branch until this ",
6342 "ambiguity is resolved.\n";
6345 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6346 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6347 command_noisy('update-ref', $new_ref, $orig_ref);
6348 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6351 command_close_pipe($fh, $ctx);
6352 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6356 sub migrate_from_v1 {
6357 my $git_dir = $ENV{GIT_DIR};
6359 return $migrated unless -d $git_dir;
6360 my $svn_dir = "$git_dir/svn";
6362 # just in case somebody used 'svn' as their $id at some point...
6363 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6365 print STDERR "Migrating from a git-svn v1 layout...\n";
6367 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6368 "$svn_dir\n\t(required for this version ",
6369 "($::VERSION) of git-svn) does not exist.\n";
6370 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6373 next unless $x =~ s#^refs/remotes/##;
6375 next unless -f "$git_dir/$x/info/url";
6376 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6378 my $dn = dirname("$git_dir/svn/$x");
6379 mkpath([$dn]) unless -d $dn;
6380 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6381 mkpath(["$git_dir/svn/svn"]);
6382 print STDERR " - $git_dir/$x/info => ",
6383 "$git_dir/svn/$x/info\n";
6384 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6386 # don't worry too much about these, they probably
6387 # don't exist with repos this old (save for index,
6388 # and we can easily regenerate that)
6389 foreach my $f (qw/unhandled.log index .rev_db/) {
6390 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6393 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6394 rename "$git_dir/$x", "$git_dir/svn/$x" or
6399 command_close_pipe($fh, $ctx);
6400 print STDERR "Done migrating from a git-svn v1 layout\n";
6405 my ($l_map, $pfx, $path) = @_;
6407 foreach (<$path/*>) {
6408 if (-r "$_/info/url") {
6409 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6410 my $ref_id = $pfx . basename $_;
6411 my $url = ::file_to_s("$_/info/url");
6412 $l_map->{$ref_id} = $url;
6419 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6420 read_old_urls($l_map, $x, $_);
6424 sub migrate_from_v2 {
6425 my @cfg = command(qw/config -l/);
6426 return if grep /^svn-remote\..+\.url=/, @cfg;
6428 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6431 foreach my $ref_id (sort keys %l_map) {
6432 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6434 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6441 sub minimize_connections {
6442 my $r = Git::SVN::read_all_remotes();
6444 my $root_repos = {};
6445 foreach my $repo_id (keys %$r) {
6446 my $url = $r->{$repo_id}->{url} or next;
6447 my $fetch = $r->{$repo_id}->{fetch} or next;
6448 my $ra = Git::SVN::Ra->new($url);
6450 # skip existing cases where we already connect to the root
6451 if (($ra->{url} eq $ra->{repos_root}) ||
6452 ($ra->{repos_root} eq $repo_id)) {
6453 $root_repos->{$ra->{url}} = $repo_id;
6457 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6458 my $root_path = $ra->{url};
6459 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6460 foreach my $path (keys %$fetch) {
6461 my $ref_id = $fetch->{$path};
6462 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6464 # make sure we can read when connecting to
6465 # a higher level of a repository
6466 my ($last_rev, undef) = $gs->last_rev_commit;
6467 if (!defined $last_rev) {
6469 $root_ra->get_latest_revnum;
6473 my $new = $root_path;
6474 $new .= length $path ? "/$path" : '';
6476 $root_ra->get_log([$new], $last_rev, $last_rev,
6480 $new_urls->{$ra->{repos_root}}->{$new} =
6481 { ref_id => $ref_id,
6482 old_repo_id => $repo_id,
6483 old_path => $path };
6488 foreach my $url (keys %$new_urls) {
6489 # see if we can re-use an existing [svn-remote "repo_id"]
6490 # instead of creating a(n ugly) new section:
6491 my $repo_id = $root_repos->{$url} || $url;
6493 my $fetch = $new_urls->{$url};
6494 foreach my $path (keys %$fetch) {
6495 my $x = $fetch->{$path};
6496 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6497 my $pfx = "svn-remote.$x->{old_repo_id}";
6499 my $old_fetch = quotemeta("$x->{old_path}:".
6501 command_noisy(qw/config --unset/,
6502 "$pfx.fetch", '^'. $old_fetch . '$');
6503 delete $r->{$x->{old_repo_id}}->
6504 {fetch}->{$x->{old_path}};
6505 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6506 command_noisy(qw/config --unset/,
6508 push @emptied, $x->{old_repo_id}
6513 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6515 The following [svn-remote] sections in your config file ($file) are empty
6516 and can be safely removed:
6518 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6522 sub migration_check {
6526 minimize_connections() if $_minimize;
6529 package Git::IndexInfo;
6532 use Git qw/command_input_pipe command_close_pipe/;
6536 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6537 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6541 my ($self, $path) = @_;
6542 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6543 return ++$self->{nr};
6549 my ($self, $mode, $hash, $path) = @_;
6550 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6551 return ++$self->{nr};
6558 command_close_pipe($self->{gui}, $self->{ctx});
6561 package Git::SVN::GlobSpec;
6566 my ($class, $glob, $pattern_ok) = @_;
6568 $re =~ s!/+$!!g; # no need for trailing slashes
6569 my (@left, @right, @patterns);
6571 my $die_msg = "Only one set of wildcard directories " .
6572 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6573 for my $part (split(m|/|, $glob)) {
6574 if ($part =~ /\*/ && $part ne "*") {
6575 die "Invalid pattern in '$glob': $part\n";
6576 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6577 $part !~ /^\{[^{}]+\}/) {
6578 die "Invalid pattern in '$glob': $part\n";
6581 die $die_msg if $state eq "right";
6583 push(@patterns, "[^/]*");
6584 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6585 die $die_msg if $state eq "right";
6587 my $p = quotemeta($1);
6589 push(@patterns, "(?:$p)");
6591 if ($state eq "left") {
6594 push(@right, $part);
6599 my $depth = @patterns;
6601 die "One '*' is needed in glob: '$glob'\n";
6603 my $left = join('/', @left);
6604 my $right = join('/', @right);
6605 $re = join('/', @patterns);
6607 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6608 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6609 bless { left => $left, right => $right, left_regex => $left_re,
6610 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6614 my ($self, $path) = @_;
6615 return (length $self->{left} ? "$self->{left}/" : '') .
6616 $path . (length $self->{right} ? "/$self->{right}" : '');
6624 $remotes = { # returned by read_all_remotes()
6626 # svn-remote.svn.url=https://svn.musicpd.org
6627 url => 'https://svn.musicpd.org',
6628 # svn-remote.svn.fetch=mpd/trunk:trunk
6630 'mpd/trunk' => 'trunk',
6632 # svn-remote.svn.tags=mpd/tags/*:tags/*
6637 regex => qr!mpd/tags/([^/]+)$!,
6643 regex => qr!tags/([^/]+)$!,
6650 $log_entry hashref as returned by libsvn_log_entry()
6652 log => 'whitespace-formatted log entry
6653 ', # trailing newline is preserved
6654 revision => '8', # integer
6655 date => '2004-02-24T17:01:44.108345Z', # commit date
6656 author => 'committer name'
6660 # this is generated by generate_diff();
6661 @mods = array of diff-index line hashes, each element represents one line
6662 of diff-index output
6664 diff-index line ($m hash)
6666 mode_a => first column of diff-index output, no leading ':',
6667 mode_b => second column of diff-index output,
6668 sha1_b => sha1sum of the final blob,
6669 chg => change type [MCRADT],
6670 file_a => original file name of a file (iff chg is 'C' or 'R')
6671 file_b => new/current file name of a file (any chg)
6675 # retval of read_url_paths{,_all}();
6677 # repository root url
6678 'https://svn.musicpd.org' => {
6679 # repository path # GIT_SVN_ID
6680 'mpd/trunk' => 'trunk',
6681 'mpd/tags/0.11.5' => 'tags/0.11.5',
6686 I don't trust the each() function on unless I created %hash myself
6687 because the internal iterator may not have started at base.