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} && exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
29 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
34 $Git::SVN::Log::TZ = $ENV{TZ};
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
41 # repository decides to close the connection which we expect to be kept alive.
42 $SIG{PIPE} = 'IGNORE';
44 # Given a dot separated version number, "subtract" it from
45 # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
46 # is at least at the version the caller asked for.
47 sub compare_svn_version {
48 my (@ours) = split(/\./, $SVN::Core::VERSION);
49 my (@theirs) = split(/\./, $_[0]);
52 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
53 $diff = $ours[$i] - $theirs[$i];
54 return $diff if ($diff);
56 return 1 if ($i < @ours);
57 return -1 if ($i < @theirs);
62 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
65 if (::compare_svn_version('1.1.0') < 0) {
66 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
69 my $can_compress = eval { require Compress::Zlib; 1};
70 push @Git::SVN::Ra::ISA, 'SVN::Ra';
71 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
72 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
76 use File::Basename qw/dirname basename/;
77 use File::Path qw/mkpath/;
80 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
83 use Memoize; # core since 5.8.0, Jul 2002
86 # import functions from Git into our packages, en masse
88 foreach (qw/command command_oneline command_noisy command_output_pipe
89 command_input_pipe command_close_pipe
90 command_bidi_pipe command_close_bidi_pipe/) {
91 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
92 Git::SVN::Migration Git::SVN::Log Git::SVN),
94 *{"${package}::$_"} = \&{"Git::$_"};
97 Memoize::memoize 'Git::config';
98 Memoize::memoize 'Git::config_bool';
103 $sha1 = qr/[a-f\d]{40}/;
104 $sha1_short = qr/[a-f\d]{4,40}/;
105 my ($_stdin, $_help, $_edit,
106 $_message, $_file, $_branch_dest,
107 $_template, $_shared,
108 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
109 $_merge, $_strategy, $_dry_run, $_local,
110 $_prefix, $_no_checkout, $_url, $_verbose,
111 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
112 $Git::SVN::_follow_parent = 1;
113 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
115 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
116 'config-dir=s' => \$Git::SVN::Ra::config_dir,
117 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
118 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
119 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
120 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
121 'authors-file|A=s' => \$_authors,
122 'authors-prog=s' => \$_authors_prog,
123 'repack:i' => \$Git::SVN::_repack,
124 'noMetadata' => \$Git::SVN::_no_metadata,
125 'useSvmProps' => \$Git::SVN::_use_svm_props,
126 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
127 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
128 'no-checkout' => \$_no_checkout,
130 'repack-flags|repack-args|repack-opts=s' =>
131 \$Git::SVN::_repack_flags,
132 'use-log-author' => \$Git::SVN::_use_log_author,
133 'add-author-from' => \$Git::SVN::_add_author_from,
134 'localtime' => \$Git::SVN::_localtime,
137 my ($_trunk, @_tags, @_branches, $_stdlayout);
139 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
140 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
141 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
142 'stdlayout|s' => \$_stdlayout,
143 'minimize-url|m!' => \$Git::SVN::_minimize_url,
144 'no-metadata' => sub { $icv{noMetadata} = 1 },
145 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
146 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
147 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
148 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
150 my %cmt_opts = ( 'edit|e' => \$_edit,
151 'rmdir' => \$SVN::Git::Editor::_rmdir,
152 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
153 'l=i' => \$SVN::Git::Editor::_rename_limit,
154 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
158 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
159 { 'revision|r=s' => \$_revision,
160 'fetch-all|all' => \$_fetch_all,
161 'parent|p' => \$_fetch_parent,
163 clone => [ \&cmd_clone, "Initialize and fetch revisions",
164 { 'revision|r=s' => \$_revision,
165 'preserve-empty-dirs' =>
166 \$SVN::Git::Fetcher::_preserve_empty_dirs,
167 'placeholder-filename=s' =>
168 \$SVN::Git::Fetcher::_placeholder_filename,
169 %fc_opts, %init_opts } ],
170 init => [ \&cmd_init, "Initialize a repo for tracking" .
171 " (requires URL argument)",
173 'multi-init' => [ \&cmd_multi_init,
174 "Deprecated alias for ".
175 "'$0 init -T<trunk> -b<branches> -t<tags>'",
177 dcommit => [ \&cmd_dcommit,
178 'Commit several diffs to merge with upstream',
179 { 'merge|m|M' => \$_merge,
180 'strategy|s=s' => \$_strategy,
181 'verbose|v' => \$_verbose,
182 'dry-run|n' => \$_dry_run,
183 'fetch-all|all' => \$_fetch_all,
184 'commit-url=s' => \$_commit_url,
185 'revision|r=i' => \$_revision,
186 'no-rebase' => \$_no_rebase,
187 'mergeinfo=s' => \$_merge_info,
188 'interactive|i' => \$_interactive,
189 %cmt_opts, %fc_opts } ],
190 branch => [ \&cmd_branch,
191 'Create a branch in the SVN repository',
192 { 'message|m=s' => \$_message,
193 'destination|d=s' => \$_branch_dest,
194 'dry-run|n' => \$_dry_run,
196 'username=s' => \$Git::SVN::Prompt::_username,
197 'commit-url=s' => \$_commit_url } ],
198 tag => [ sub { $_tag = 1; cmd_branch(@_) },
199 'Create a tag in the SVN repository',
200 { 'message|m=s' => \$_message,
201 'destination|d=s' => \$_branch_dest,
202 'dry-run|n' => \$_dry_run,
203 'username=s' => \$Git::SVN::Prompt::_username,
204 'commit-url=s' => \$_commit_url } ],
205 'set-tree' => [ \&cmd_set_tree,
206 "Set an SVN repository to a git tree-ish",
207 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
208 'create-ignore' => [ \&cmd_create_ignore,
209 'Create a .gitignore per svn:ignore',
210 { 'revision|r=i' => \$_revision
212 'mkdirs' => [ \&cmd_mkdirs ,
213 "recreate empty directories after a checkout",
214 { 'revision|r=i' => \$_revision } ],
215 'propget' => [ \&cmd_propget,
216 'Print the value of a property on a file or directory',
217 { 'revision|r=i' => \$_revision } ],
218 'proplist' => [ \&cmd_proplist,
219 'List all properties of a file or directory',
220 { 'revision|r=i' => \$_revision } ],
221 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
222 { 'revision|r=i' => \$_revision
224 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
225 { 'revision|r=i' => \$_revision
227 'multi-fetch' => [ \&cmd_multi_fetch,
228 "Deprecated alias for $0 fetch --all",
229 { 'revision|r=s' => \$_revision, %fc_opts } ],
230 'migrate' => [ sub { },
231 # no-op, we automatically run this anyways,
232 'Migrate configuration/metadata/layout from
233 previous versions of git-svn',
234 { 'minimize' => \$Git::SVN::Migration::_minimize,
236 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
237 { 'limit=i' => \$Git::SVN::Log::limit,
238 'revision|r=s' => \$_revision,
239 'verbose|v' => \$Git::SVN::Log::verbose,
240 'incremental' => \$Git::SVN::Log::incremental,
241 'oneline' => \$Git::SVN::Log::oneline,
242 'show-commit' => \$Git::SVN::Log::show_commit,
243 'non-recursive' => \$Git::SVN::Log::non_recursive,
244 'authors-file|A=s' => \$_authors,
245 'color' => \$Git::SVN::Log::color,
246 'pager=s' => \$Git::SVN::Log::pager
248 'find-rev' => [ \&cmd_find_rev,
249 "Translate between SVN revision numbers and tree-ish",
251 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
252 { 'merge|m|M' => \$_merge,
253 'verbose|v' => \$_verbose,
254 'strategy|s=s' => \$_strategy,
255 'local|l' => \$_local,
256 'fetch-all|all' => \$_fetch_all,
257 'dry-run|n' => \$_dry_run,
259 'commit-diff' => [ \&cmd_commit_diff,
260 'Commit a diff between two trees',
261 { 'message|m=s' => \$_message,
262 'file|F=s' => \$_file,
263 'revision|r=s' => \$_revision,
265 'info' => [ \&cmd_info,
266 "Show info about the latest SVN revision
267 on the current branch",
268 { 'url' => \$_url, } ],
269 'blame' => [ \&Git::SVN::Log::cmd_blame,
270 "Show what revision and author last modified each line of a file",
271 { 'git-format' => \$_git_format } ],
272 'reset' => [ \&cmd_reset,
273 "Undo fetches back to the specified SVN revision",
274 { 'revision|r=s' => \$_revision,
275 'parent|p' => \$_fetch_parent } ],
277 "Compress unhandled.log files in .git/svn and remove " .
278 "index files in .git/svn",
285 my ($class, $reason) = @_;
286 return bless \$reason, shift;
290 die "Cannot use readline on FakeTerm: $$self";
295 $ENV{"GIT_SVN_NOTTY"}
296 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
297 : new Term::ReadLine 'git-svn';
300 $term = new FakeTerm "$@: going non-interactive";
304 for (my $i = 0; $i < @ARGV; $i++) {
305 if (defined $cmd{$ARGV[$i]}) {
309 } elsif ($ARGV[$i] eq 'help') {
315 # make sure we're always running at the top-level working directory
316 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
317 unless (-d $ENV{GIT_DIR}) {
318 if ($git_dir_user_set) {
319 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
320 "but it is not a directory\n";
322 my $git_dir = delete $ENV{GIT_DIR};
325 $cdup = command_oneline(qw/rev-parse --show-cdup/);
326 $git_dir = '.' unless ($cdup);
327 chomp $cdup if ($cdup);
328 $cdup = "." unless ($cdup && length $cdup);
329 } "Already at toplevel, but $git_dir not found\n";
330 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
331 unless (-d $git_dir) {
332 die "$git_dir still not found after going to ",
335 $ENV{GIT_DIR} = $git_dir;
337 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
340 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
342 read_git_config(\%opts);
343 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
344 Getopt::Long::Configure('pass_through');
346 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
347 'minimize-connections' => \$Git::SVN::Migration::_minimize,
348 'id|i=s' => \$Git::SVN::default_ref_id,
349 'svn-remote|remote|R=s' => sub {
350 $Git::SVN::no_reuse_existing = 1;
351 $Git::SVN::default_repo_id = $_[1] });
352 exit 1 if (!$rv && $cmd && $cmd ne 'log');
355 version() if $_version;
356 usage(1) unless defined $cmd;
357 load_authors() if $_authors;
358 if (defined $_authors_prog) {
359 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
362 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
363 Git::SVN::Migration::migration_check();
365 Git::SVN::init_vars();
367 Git::SVN::verify_remotes_sanity();
368 $cmd{$cmd}->[0]->(@ARGV);
371 post_fetch_checkout();
374 ####################### primary functions ######################
376 my $exit = shift || 0;
377 my $fd = $exit ? \*STDERR : \*STDOUT;
379 git-svn - bidirectional operations between a single Subversion tree and git
380 Usage: git svn <command> [options] [arguments]\n
382 print $fd "Available commands:\n" unless $cmd;
384 foreach (sort keys %cmd) {
385 next if $cmd && $cmd ne $_;
386 next if /^multi-/; # don't show deprecated commands
387 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
388 foreach (sort keys %{$cmd{$_}->[2]}) {
389 # mixed-case options are for .git/config only
390 next if /[A-Z]/ && /^[a-z]+$/i;
391 # prints out arguments as they should be passed:
392 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
393 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
395 split /\|/,$_)," $x\n";
399 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
400 arbitrary identifier if you're tracking multiple SVN branches/repositories in
401 one git repository and want to keep them separate. See git-svn(1) for more
409 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
414 my ($prompt, %arg) = @_;
415 my $valid_re = $arg{valid_re};
416 my $default = $arg{default};
420 if ( !( defined($term->IN)
421 && defined( fileno($term->IN) )
422 && defined( $term->OUT )
423 && defined( fileno($term->OUT) ) ) ){
424 return defined($default) ? $default : undef;
428 $resp = $term->readline($prompt);
429 if (!defined $resp) { # EOF
431 return defined $default ? $default : undef;
433 if ($resp eq '' and defined $default) {
436 if (!defined $valid_re or $resp =~ /$valid_re/) {
444 unless (-d $ENV{GIT_DIR}) {
445 my @init_db = ('init');
446 push @init_db, "--template=$_template" if defined $_template;
447 if (defined $_shared) {
448 if ($_shared =~ /[a-z]/) {
449 push @init_db, "--shared=$_shared";
451 push @init_db, "--shared";
454 command_noisy(@init_db);
455 $_repository = Git->repository(Repository => ".git");
458 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
459 foreach my $i (keys %icv) {
460 die "'$set' and '$i' cannot both be set\n" if $set;
461 next unless defined $icv{$i};
462 command_noisy('config', "$pfx.$i", $icv{$i});
465 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
466 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
467 if defined $$ignore_paths_regex;
468 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
469 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
470 if defined $$ignore_refs_regex;
472 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
473 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
474 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
475 command_noisy('config', "$pfx.placeholder-filename", $$fname);
480 my $repo_path = shift or return;
481 mkpath([$repo_path]) unless -d $repo_path;
482 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
483 $ENV{GIT_DIR} = '.git';
484 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
488 my ($url, $path) = @_;
489 if (!defined $path &&
490 (defined $_trunk || @_branches || @_tags ||
491 defined $_stdlayout) &&
492 $url !~ m#^[a-z\+]+://#) {
495 $path = basename($url) if !defined $path || !length $path;
496 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
497 cmd_init($url, $path);
498 command_oneline('config', 'svn.authorsfile', $authors_absolute)
500 Git::SVN::fetch_all($Git::SVN::default_repo_id);
504 if (defined $_stdlayout) {
505 $_trunk = 'trunk' if (!defined $_trunk);
506 @_tags = 'tags' if (! @_tags);
507 @_branches = 'branches' if (! @_branches);
509 if (defined $_trunk || @_branches || @_tags) {
510 return cmd_multi_init(@_);
512 my $url = shift or die "SVN repository location required ",
513 "as a command-line argument\n";
514 $url = canonicalize_url($url);
518 if ($Git::SVN::_minimize_url eq 'unset') {
519 $Git::SVN::_minimize_url = 0;
522 Git::SVN->init($url);
526 if (grep /^\d+=./, @_) {
527 die "'<rev>=<commit>' fetch arguments are ",
528 "no longer supported.\n";
532 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
534 $Git::SVN::no_reuse_existing = undef;
535 if ($_fetch_parent) {
536 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
538 die "Unable to determine upstream SVN information from ",
539 "working tree history\n";
541 # just fetch, don't checkout.
542 $_no_checkout = 'true';
543 $_fetch_all ? $gs->fetch_all : $gs->fetch;
544 } elsif ($_fetch_all) {
547 $remote ||= $Git::SVN::default_repo_id;
548 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
554 if ($_stdin || !@commits) {
555 print "Reading from stdin...\n";
558 if (/\b($sha1_short)\b/o) {
559 unshift @commits, $1;
564 foreach my $c (@commits) {
565 my @tmp = command('rev-parse',$c);
566 if (scalar @tmp == 1) {
568 } elsif (scalar @tmp > 1) {
569 push @revs, reverse(command('rev-list',@tmp));
571 fatal "Failed to rev-parse $c";
574 my $gs = Git::SVN->new;
575 my ($r_last, $cmt_last) = $gs->last_rev_commit;
577 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
578 fatal "There are new revisions that were fetched ",
579 "and need to be merged (or acknowledged) ",
580 "before committing.\nlast rev: $r_last\n",
581 " current: $gs->{last_rev}";
583 $gs->set_tree($_) foreach @revs;
584 print "Done committing ",scalar @revs," revisions to SVN\n";
588 sub split_merge_info_range {
590 if ($range =~ /(\d+)-(\d+)/) {
591 return (int($1), int($2));
593 return (int($range), int($range));
601 my @arr = split(/,/, $in);
602 for my $element (@arr) {
603 my ($start, $end) = split_merge_info_range($element);
607 my @sorted = @arr [ sort {
608 $fnums[$a] <=> $fnums[$b]
614 for my $element (@sorted) {
615 my ($start, $end) = split_merge_info_range($element);
622 if ($start <= $last+1) {
628 if ($first == $last) {
629 push @return, "$first";
631 push @return, "$first-$last";
638 if ($first == $last) {
639 push @return, "$first";
641 push @return, "$first-$last";
645 return join(',', @return);
648 sub merge_revs_into_hash {
649 my ($hash, $minfo) = @_;
650 my @lines = split(' ', $minfo);
652 for my $line (@lines) {
653 my ($branchpath, $revs) = split(/:/, $line);
655 if (exists($hash->{$branchpath})) {
656 # Merge the two revision sets
657 my $combined = "$hash->{$branchpath},$revs";
658 $hash->{$branchpath} = combine_ranges($combined);
660 # Just do range combining for consolidation
661 $hash->{$branchpath} = combine_ranges($revs);
666 sub merge_merge_info {
667 my ($mergeinfo_one, $mergeinfo_two) = @_;
668 my %result_hash = ();
670 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
671 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
674 # Sort below is for consistency's sake
675 for my $branchname (sort keys(%result_hash)) {
676 my $revlist = $result_hash{$branchname};
677 $result .= "$branchname:$revlist\n"
682 sub populate_merge_info {
683 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
686 read_commit_parents(\%parentshash, $d);
687 my @parents = @{$parentshash{$d}};
690 my $all_parents_ok = 1;
691 my $aggregate_mergeinfo = '';
692 my $rooturl = $gs->repos_root;
694 if (defined($rewritten_parent)) {
695 # Replace first parent with newly-rewritten version
697 unshift @parents, $rewritten_parent;
700 foreach my $parent (@parents) {
701 my ($branchurl, $svnrev, $paruuid) =
702 cmt_metadata($parent);
704 unless (defined($svnrev)) {
705 # Should have been caught be preflight check
706 fatal "merge commit $d has ancestor $parent, but that change "
707 ."does not have git-svn metadata!";
709 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
710 fatal "commit $parent git-svn metadata changed mid-run!";
714 my $ra = Git::SVN::Ra->new($branchurl);
715 my (undef, undef, $props) =
716 $ra->get_dir(canonicalize_path("."), $svnrev);
717 my $par_mergeinfo = $props->{'svn:mergeinfo'};
718 unless (defined $par_mergeinfo) {
721 # Merge previous mergeinfo values
722 $aggregate_mergeinfo =
723 merge_merge_info($aggregate_mergeinfo,
726 next if $parent eq $parents[0]; # Skip first parent
727 # Add new changes being placed in tree by merge
728 my @cmd = (qw/rev-list --reverse/,
730 foreach my $par (@parents) {
731 unless ($par eq $parent) {
736 my ($revlist, $ctx) = command_output_pipe(@cmd);
740 my (undef, $csvnrev, undef) =
742 unless (defined $csvnrev) {
743 # A child is missing SVN annotations...
744 # this might be OK, or might not be.
745 warn "W:child $irev is merged into revision "
746 ."$d but does not have git-svn metadata. "
747 ."This means git-svn cannot determine the "
748 ."svn revision numbers to place into the "
749 ."svn:mergeinfo property. You must ensure "
750 ."a branch is entirely committed to "
751 ."SVN before merging it in order for "
752 ."svn:mergeinfo population to function "
755 push @revsin, $csvnrev;
757 command_close_pipe($revlist, $ctx);
759 last unless $all_parents_ok;
761 # We now have a list of all SVN revnos which are
762 # merged by this particular parent. Integrate them.
763 next if $#revsin == -1;
764 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
765 $aggregate_mergeinfo =
766 merge_merge_info($aggregate_mergeinfo,
769 if ($all_parents_ok and $aggregate_mergeinfo) {
770 return $aggregate_mergeinfo;
779 command_noisy(qw/update-index --refresh/);
780 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
781 'Cannot dcommit with a dirty index. Commit your changes first, '
782 . "or stash them with `git stash'.\n";
786 if ($head ne 'HEAD') {
788 command_oneline([qw/symbolic-ref -q HEAD/])
791 $old_head =~ s{^refs/heads/}{};
793 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
795 command(['checkout', $head], STDERR => 0);
799 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
801 die "Unable to determine upstream SVN information from ",
802 "$head history.\nPerhaps the repository is empty.";
805 if (defined $_commit_url) {
808 $url = eval { command_oneline('config', '--get',
809 "svn-remote.$gs->{repo_id}.commiturl") };
811 $url = $gs->full_pushurl
815 my $last_rev = $_revision if defined $_revision;
817 print "Committing to $url ...\n";
819 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
820 if ($_no_rebase && scalar(@$linear_refs) > 1) {
821 warn "Attempting to commit more than one change while ",
822 "--no-rebase is enabled.\n",
823 "If these changes depend on each other, re-running ",
824 "without --no-rebase may be required."
827 if (defined $_interactive){
828 my $ask_default = "y";
829 foreach my $d (@$linear_refs){
830 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
834 command_close_pipe($fh, $ctx);
835 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
836 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
837 default => $ask_default);
838 die "Commit this patch reply required" unless defined $_;
847 my $expect_url = $url;
849 my $push_merge_info = eval {
850 command_oneline(qw/config --get svn.pushmergeinfo/)
852 if (not defined($push_merge_info)
853 or $push_merge_info eq "false"
854 or $push_merge_info eq "no"
855 or $push_merge_info eq "never") {
856 $push_merge_info = 0;
859 unless (defined($_merge_info) || ! $push_merge_info) {
860 # Preflight check of changes to ensure no issues with mergeinfo
861 # This includes check for uncommitted-to-SVN parents
862 # (other than the first parent, which we will handle),
863 # information from different SVN repos, and paths
864 # which are not underneath this repository root.
865 my $rooturl = $gs->repos_root;
866 foreach my $d (@$linear_refs) {
868 read_commit_parents(\%parentshash, $d);
869 my @realparents = @{$parentshash{$d}};
870 if ($#realparents > 0) {
872 shift @realparents; # Remove/ignore first parent
873 foreach my $parent (@realparents) {
874 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
875 unless (defined $paruuid) {
876 # A parent is missing SVN annotations...
877 # abort the whole operation.
878 fatal "$parent is merged into revision $d, "
879 ."but does not have git-svn metadata. "
880 ."Either dcommit the branch or use a "
881 ."local cherry-pick, FF merge, or rebase "
882 ."instead of an explicit merge commit.";
885 unless ($paruuid eq $uuid) {
886 # Parent has SVN metadata from different repository
887 fatal "merge parent $parent for change $d has "
888 ."git-svn uuid $paruuid, while current change "
892 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
893 # This branch is very strange indeed.
894 fatal "merge parent $parent for $d is on branch "
895 ."$branchurl, which is not under the "
896 ."git-svn root $rooturl!";
903 my $rewritten_parent;
904 Git::SVN::remove_username($expect_url);
905 if (defined($_merge_info)) {
906 $_merge_info =~ tr{ }{\n};
909 my $d = shift @$linear_refs or last;
910 unless (defined $last_rev) {
911 (undef, $last_rev, undef) = cmt_metadata("$d~1");
912 unless (defined $last_rev) {
913 fatal "Unable to extract revision information ",
918 print "diff-tree $d~1 $d\n";
922 unless (defined($_merge_info) || ! $push_merge_info) {
923 $_merge_info = populate_merge_info($d, $gs,
929 my %ed_opts = ( r => $last_rev,
930 log => get_commit_entry($d)->{log},
931 ra => Git::SVN::Ra->new($url),
932 config => SVN::Core::config_get_config(
933 $Git::SVN::Ra::config_dir
938 print "Committed r$_[0]\n";
941 mergeinfo => $_merge_info,
943 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
944 print "No changes\n$d~1 == $d\n";
945 } elsif ($parents->{$d} && @{$parents->{$d}}) {
946 $gs->{inject_parents_dcommit}->{$cmt_rev} =
949 $_fetch_all ? $gs->fetch_all : $gs->fetch;
950 $last_rev = $cmt_rev;
953 # we always want to rebase against the current HEAD,
954 # not any head that was passed to us
955 my @diff = command('diff-tree', $d,
959 @finish = rebase_cmd();
960 print STDERR "W: $d and ", $gs->refname,
961 " differ, using @finish:\n",
962 join("\n", @diff), "\n";
964 print "No changes between current HEAD and ",
966 "\nResetting to the latest ",
968 @finish = qw/reset --mixed/;
970 command_noisy(@finish, $gs->refname);
972 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
976 my ($url_, $rev_, $uuid_, $gs_) =
977 working_head_info('HEAD', \@refs);
978 my ($linear_refs_, $parents_) =
979 linearize_history($gs_, \@refs);
980 if (scalar(@$linear_refs) !=
981 scalar(@$linear_refs_)) {
982 fatal "# of revisions changed ",
984 join("\n", @$linear_refs),
986 join("\n", @$linear_refs_), "\n",
987 'If you are attempting to commit ',
988 "merges, try running:\n\t",
989 'git rebase --interactive',
990 '--preserve-merges ',
992 "\nBefore dcommitting";
994 if ($url_ ne $expect_url) {
995 if ($url_ eq $gs->metadata_url) {
997 "Accepting rewritten URL:",
1001 "URL mismatch after rebase:",
1002 " $url_ != $expect_url";
1005 if ($uuid_ ne $uuid) {
1006 fatal "uuid mismatch after rebase: ",
1011 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1012 my $new = $linear_refs_->[$i] or next;
1014 $parents->{$linear_refs->[$i]};
1024 my $new_head = command_oneline(qw/rev-parse HEAD/);
1025 my $new_is_symbolic = eval {
1026 command_oneline(qw/symbolic-ref -q HEAD/);
1028 if ($new_is_symbolic) {
1029 print "dcommitted the branch ", $head, "\n";
1031 print "dcommitted on a detached HEAD because you gave ",
1032 "a revision argument.\n",
1033 "The rewritten commit is: ", $new_head, "\n";
1035 command(['checkout', $old_head], STDERR => 0);
1038 unlink $gs->{index};
1042 my ($branch_name, $head) = @_;
1044 unless (defined $branch_name && length $branch_name) {
1045 die(($_tag ? "tag" : "branch") . " name required\n");
1049 my (undef, $rev, undef, $gs) = working_head_info($head);
1050 my $src = $gs->full_pushurl;
1052 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1053 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1055 if ($#{$allglobs} == 0) {
1056 $glob = $allglobs->[0];
1058 unless(defined $_branch_dest) {
1060 $_tag ? "tag" : "branch",
1061 " paths defined for Subversion repository.\n",
1062 "You must specify where you want to create the ",
1063 $_tag ? "tag" : "branch",
1064 " with the --destination argument.\n";
1066 foreach my $g (@{$allglobs}) {
1067 # SVN::Git::Editor could probably be moved to Git.pm..
1068 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1069 if ($_branch_dest =~ /$re/) {
1074 unless (defined $glob) {
1075 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1076 foreach my $g (@{$allglobs}) {
1077 $g->{path}->{left} =~ /$dest_re/ or next;
1078 if (defined $glob) {
1079 die "Ambiguous destination: ",
1080 $_branch_dest, "\nmatches both '",
1081 $glob->{path}->{left}, "' and '",
1082 $g->{path}->{left}, "'\n";
1086 unless (defined $glob) {
1088 $_tag ? "tag" : "branch",
1089 " destination $_branch_dest\n";
1093 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1095 if (defined $_commit_url) {
1096 $url = $_commit_url;
1098 $url = eval { command_oneline('config', '--get',
1099 "svn-remote.$gs->{repo_id}.commiturl") };
1101 $url = $remote->{pushurl} || $remote->{url};
1104 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1106 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1107 $src=~s/^http:/https:/;
1112 my $ctx = SVN::Client->new(
1113 auth => Git::SVN::Ra::_auth_providers(),
1115 ${ $_[0] } = defined $_message
1117 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1123 $ctx->ls($dst, 'HEAD', 0);
1124 } and die "branch ${branch_name} already exists\n";
1126 print "Copying ${src} at r${rev} to ${dst}...\n";
1127 $ctx->copy($src, $rev, $dst)
1134 my $revision_or_hash = shift or die "SVN or git revision required ",
1135 "as a command-line argument\n";
1137 if ($revision_or_hash =~ /^r\d+$/) {
1141 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1143 die "Unable to determine upstream SVN information from ",
1146 my $desired_revision = substr($revision_or_hash, 1);
1147 $result = $gs->rev_map_get($desired_revision, $uuid);
1149 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1152 print "$result\n" if $result;
1155 sub auto_create_empty_directories {
1157 my $var = eval { command_oneline('config', '--get', '--bool',
1158 "svn-remote.$gs->{repo_id}.automkdirs") };
1159 # By default, create empty directories by consulting the unhandled log,
1160 # but allow setting it to 'false' to skip it.
1161 return !($var && $var eq 'false');
1165 command_noisy(qw/update-index --refresh/);
1166 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1168 die "Unable to determine upstream SVN information from ",
1169 "working tree history\n";
1172 print "Remote Branch: " . $gs->refname . "\n";
1173 print "SVN URL: " . $url . "\n";
1176 if (command(qw/diff-index HEAD --/)) {
1177 print STDERR "Cannot rebase with uncommited changes:\n";
1178 command_noisy('status');
1182 # rebase will checkout for us, so no need to do it explicitly
1183 $_no_checkout = 'true';
1184 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1186 command_noisy(rebase_cmd(), $gs->refname);
1187 if (auto_create_empty_directories($gs)) {
1192 sub cmd_show_ignore {
1193 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1194 $gs ||= Git::SVN->new;
1195 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1196 $gs->prop_walk($gs->{path}, $r, sub {
1197 my ($gs, $path, $props) = @_;
1198 print STDOUT "\n# $path\n";
1199 my $s = $props->{'svn:ignore'} or return;
1200 $s =~ s/[\r\n]+/\n/g;
1204 print STDOUT "$s\n";
1208 sub cmd_show_externals {
1209 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1210 $gs ||= Git::SVN->new;
1211 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1212 $gs->prop_walk($gs->{path}, $r, sub {
1213 my ($gs, $path, $props) = @_;
1214 print STDOUT "\n# $path\n";
1215 my $s = $props->{'svn:externals'} or return;
1216 $s =~ s/[\r\n]+/\n/g;
1219 print STDOUT "$s\n";
1223 sub cmd_create_ignore {
1224 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1225 $gs ||= Git::SVN->new;
1226 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1227 $gs->prop_walk($gs->{path}, $r, sub {
1228 my ($gs, $path, $props) = @_;
1229 # $path is of the form /path/to/dir/
1230 $path = '.' . $path;
1231 # SVN can have attributes on empty directories,
1232 # which git won't track
1233 mkpath([$path]) unless -d $path;
1234 my $ignore = $path . '.gitignore';
1235 my $s = $props->{'svn:ignore'} or return;
1236 open(GITIGNORE, '>', $ignore)
1237 or fatal("Failed to open `$ignore' for writing: $!");
1238 $s =~ s/[\r\n]+/\n/g;
1241 # Prefix all patterns so that the ignore doesn't apply
1242 # to sub-directories.
1244 print GITIGNORE "$s\n";
1246 or fatal("Failed to close `$ignore': $!");
1247 command_noisy('add', '-f', $ignore);
1252 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1253 $gs ||= Git::SVN->new;
1254 $gs->mkemptydirs($_revision);
1257 sub canonicalize_path {
1259 my $dot_slash_added = 0;
1260 if (substr($path, 0, 1) ne "/") {
1261 $path = "./" . $path;
1262 $dot_slash_added = 1;
1264 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1265 # good reason), so let's do this manually.
1267 $path =~ s#/\.(?:/|$)#/#g;
1268 $path =~ s#/[^/]+/\.\.##g;
1270 $path =~ s#^\./## if $dot_slash_added;
1276 sub canonicalize_url {
1278 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1282 # get_svnprops(PATH)
1283 # ------------------
1284 # Helper for cmd_propget and cmd_proplist below.
1287 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1288 $gs ||= Git::SVN->new;
1290 # prefix THE PATH by the sub-directory from which the user
1292 $path = $cmd_dir_prefix . $path;
1293 fatal("No such file or directory: $path") unless -e $path;
1294 my $is_dir = -d $path ? 1 : 0;
1295 $path = $gs->{path} . '/' . $path;
1297 # canonicalize the path (otherwise libsvn will abort or fail to
1299 $path = canonicalize_path($path);
1301 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1304 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1307 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1312 # cmd_propget (PROP, PATH)
1313 # ------------------------
1314 # Print the SVN property PROP for PATH.
1316 my ($prop, $path) = @_;
1317 $path = '.' if not defined $path;
1318 usage(1) if not defined $prop;
1319 my $props = get_svnprops($path);
1320 if (not defined $props->{$prop}) {
1321 fatal("`$path' does not have a `$prop' SVN property.");
1323 print $props->{$prop} . "\n";
1326 # cmd_proplist (PATH)
1327 # -------------------
1328 # Print the list of SVN properties for PATH.
1331 $path = '.' if not defined $path;
1332 my $props = get_svnprops($path);
1333 print "Properties on '$path':\n";
1334 foreach (sort keys %{$props}) {
1339 sub cmd_multi_init {
1341 unless (defined $_trunk || @_branches || @_tags) {
1345 $_prefix = '' unless defined $_prefix;
1347 $url = canonicalize_url($url);
1351 if (defined $_trunk) {
1353 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1354 # try both old-style and new-style lookups:
1355 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1356 unless ($gs_trunk) {
1357 my ($trunk_url, $trunk_path) =
1358 complete_svn_url($url, $_trunk);
1359 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1363 return unless @_branches || @_tags;
1364 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1365 foreach my $path (@_branches) {
1366 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1368 foreach my $path (@_tags) {
1369 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1373 sub cmd_multi_fetch {
1374 $Git::SVN::no_reuse_existing = undef;
1375 my $remotes = Git::SVN::read_all_remotes();
1376 foreach my $repo_id (sort keys %$remotes) {
1377 if ($remotes->{$repo_id}->{url}) {
1378 Git::SVN::fetch_all($repo_id, $remotes);
1383 # this command is special because it requires no metadata
1384 sub cmd_commit_diff {
1385 my ($ta, $tb, $url) = @_;
1386 my $usage = "Usage: $0 commit-diff -r<revision> ".
1387 "<tree-ish> <tree-ish> [<URL>]";
1388 fatal($usage) if (!defined $ta || !defined $tb);
1390 if (!defined $url) {
1391 my $gs = eval { Git::SVN->new };
1393 fatal("Needed URL or usable git-svn --id in ",
1394 "the command-line\n", $usage);
1397 $svn_path = $gs->{path};
1399 unless (defined $_revision) {
1400 fatal("-r|--revision is a required argument\n", $usage);
1402 if (defined $_message && defined $_file) {
1403 fatal("Both --message/-m and --file/-F specified ",
1404 "for the commit message.\n",
1405 "I have no idea what you mean");
1407 if (defined $_file) {
1408 $_message = file_to_s($_file);
1410 $_message ||= get_commit_entry($tb)->{log};
1412 my $ra ||= Git::SVN::Ra->new($url);
1415 $r = $ra->get_latest_revnum;
1416 } elsif ($r !~ /^\d+$/) {
1417 die "revision argument: $r not understood by git-svn\n";
1419 my %ed_opts = ( r => $r,
1424 editor_cb => sub { print "Committed r$_[0]\n" },
1425 svn_path => $svn_path );
1426 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1427 print "No changes\n$ta == $tb\n";
1431 sub escape_uri_only {
1434 foreach (split m{/}, $uri) {
1435 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1443 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1444 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1445 $url = "$scheme://$domain$uri";
1451 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1452 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1454 die "Too many arguments specified\n";
1457 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1459 if (!$file_type && !$diff_status) {
1460 print STDERR "svn: '$path' is not under version control\n";
1464 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1466 die "Unable to determine upstream SVN information from ",
1467 "working tree history\n";
1470 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1471 $path = "." if $path eq "";
1473 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1476 print escape_url($full_url), "\n";
1480 my $result = "Path: $path\n";
1481 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1482 $result .= "URL: " . escape_url($full_url) . "\n";
1485 my $repos_root = $gs->repos_root;
1486 Git::SVN::remove_username($repos_root);
1487 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1490 $result .= "Repository Root: (offline)\n";
1493 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1494 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1495 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1497 $result .= "Node Kind: " .
1498 ($file_type eq "dir" ? "directory" : "file") . "\n";
1500 my $schedule = $diff_status eq "A"
1502 : ($diff_status eq "D" ? "delete" : "normal");
1503 $result .= "Schedule: $schedule\n";
1505 if ($diff_status eq "A") {
1506 print $result, "\n";
1510 my ($lc_author, $lc_rev, $lc_date_utc);
1511 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1512 my $log = command_output_pipe(@args);
1513 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1515 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1517 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1518 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1519 (undef, $lc_rev, undef) = ::extract_metadata($1);
1524 Git::SVN::Log::set_local_timezone();
1526 $result .= "Last Changed Author: $lc_author\n";
1527 $result .= "Last Changed Rev: $lc_rev\n";
1528 $result .= "Last Changed Date: " .
1529 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1531 if ($file_type ne "dir") {
1532 my $text_last_updated_date =
1533 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1535 "Text Last Updated: " .
1536 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1539 if ($diff_status eq "D") {
1541 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1542 if ($file_type eq "link") {
1543 my $file_name = <$fh>;
1544 $checksum = md5sum("link $file_name");
1546 $checksum = md5sum($fh);
1548 command_close_pipe($fh, $ctx);
1549 } elsif ($file_type eq "link") {
1551 command(qw(cat-file blob), "HEAD:$path");
1553 md5sum("link " . $file_name);
1555 open FILE, "<", $path or die $!;
1556 $checksum = md5sum(\*FILE);
1557 close FILE or die $!;
1559 $result .= "Checksum: " . $checksum . "\n";
1562 print $result, "\n";
1566 my $target = shift || $_revision or die "SVN revision required\n";
1567 $target = $1 if $target =~ /^r(\d+)$/;
1568 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1569 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1571 die "Unable to determine upstream SVN information from ".
1574 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1575 die "Cannot find SVN revision $target\n" unless defined($c);
1576 $gs->rev_map_set($r, $c, 'reset', $uuid);
1577 print "r$r = $c ($gs->{ref_id})\n";
1581 if (!$can_compress) {
1582 warn "Compress::Zlib could not be found; unhandled.log " .
1583 "files will not be compressed.\n";
1585 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1588 ########################### utility functions #########################
1591 my @cmd = qw/rebase/;
1592 push @cmd, '-v' if $_verbose;
1593 push @cmd, qw/--merge/ if $_merge;
1594 push @cmd, "--strategy=$_strategy" if $_strategy;
1598 sub post_fetch_checkout {
1599 return if $_no_checkout;
1600 my $gs = $Git::SVN::_head or return;
1601 return if verify_ref('refs/heads/master^0');
1603 # look for "trunk" ref if it exists
1604 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1605 my $fetch = $remote->{fetch};
1607 foreach my $p (keys %$fetch) {
1608 basename($fetch->{$p}) eq 'trunk' or next;
1609 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1614 my $valid_head = verify_ref('HEAD^0');
1615 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1616 return if ($valid_head || !verify_ref('HEAD^0'));
1618 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1619 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1620 return if -f $index;
1622 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1623 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1624 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1625 print STDERR "Checked out HEAD:\n ",
1626 $gs->full_url, " r", $gs->last_rev, "\n";
1627 if (auto_create_empty_directories($gs)) {
1628 $gs->mkemptydirs($gs->last_rev);
1632 sub complete_svn_url {
1633 my ($url, $path) = @_;
1635 if ($path !~ m#^[a-z\+]+://#) {
1636 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1637 fatal("E: '$path' is not a complete URL ",
1638 "and a separate URL is not specified");
1640 return ($url, $path);
1645 sub complete_url_ls_init {
1646 my ($ra, $repo_path, $switch, $pfx) = @_;
1647 unless ($repo_path) {
1648 print STDERR "W: $switch not specified\n";
1651 $repo_path =~ s#/+$##;
1652 if ($repo_path =~ m#^[a-z\+]+://#) {
1653 $ra = Git::SVN::Ra->new($repo_path);
1656 $repo_path =~ s#^/+##;
1658 fatal("E: '$repo_path' is not a complete URL ",
1659 "and a separate URL is not specified");
1662 my $url = $ra->{url};
1663 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1664 my $k = "svn-remote.$gs->{repo_id}.url";
1665 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1666 if ($orig_url && ($orig_url ne $gs->{url})) {
1667 die "$k already set: $orig_url\n",
1668 "wanted to set to: $gs->{url}\n";
1670 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1671 my $remote_path = "$gs->{path}/$repo_path";
1672 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1673 $remote_path =~ s#/+#/#g;
1674 $remote_path =~ s#^/##g;
1675 $remote_path .= "/*" if $remote_path !~ /\*/;
1676 my ($n) = ($switch =~ /^--(\w+)/);
1677 if (length $pfx && $pfx !~ m#/$#) {
1678 die "--prefix='$pfx' must have a trailing slash '/'\n";
1680 command_noisy('config',
1682 "svn-remote.$gs->{repo_id}.$n",
1683 "$remote_path:refs/remotes/$pfx*" .
1684 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1689 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1690 { STDERR => 0 }); };
1693 sub get_tree_from_treeish {
1695 # $treeish can be a symbolic ref, too:
1696 my $type = command_oneline(qw/cat-file -t/, $treeish);
1698 while ($type eq 'tag') {
1699 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1701 if ($type eq 'commit') {
1702 $expected = (grep /^tree /, command(qw/cat-file commit/,
1704 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1705 die "Unable to get tree from $treeish\n" unless $expected;
1706 } elsif ($type eq 'tree') {
1707 $expected = $treeish;
1709 die "$treeish is a $type, expected tree, tag or commit\n";
1714 sub get_commit_entry {
1715 my ($treeish) = shift;
1716 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1717 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1718 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1719 open my $log_fh, '>', $commit_editmsg or croak $!;
1721 my $type = command_oneline(qw/cat-file -t/, $treeish);
1722 if ($type eq 'commit' || $type eq 'tag') {
1723 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1731 $in_msg = 1 if (/^\s*$/);
1732 $author = $1 if (/^author (.*>)/);
1733 } elsif (/^git-svn-id: /) {
1734 # skip this for now, we regenerate the
1735 # correct one on re-fetch anyways
1736 # TODO: set *:merge properties or like...
1738 if (/^From:/ || /^Signed-off-by:/) {
1744 $msgbuf =~ s/\s+$//s;
1745 if ($Git::SVN::_add_author_from && defined($author)
1747 $msgbuf .= "\n\nFrom: $author";
1749 print $log_fh $msgbuf or croak $!;
1750 command_close_pipe($msg_fh, $ctx);
1752 close $log_fh or croak $!;
1754 if ($_edit || ($type eq 'tree')) {
1755 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1756 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1758 rename $commit_editmsg, $commit_msg or croak $!;
1761 # SVN requires messages to be UTF-8 when entering the repo
1763 open $log_fh, '<', $commit_msg or croak $!;
1765 chomp($log_entry{log} = <$log_fh>);
1767 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1768 my $msg = $log_entry{log};
1770 eval { $msg = Encode::decode($enc, $msg, 1) };
1772 die "Could not decode as $enc:\n", $msg,
1773 "\nPerhaps you need to set i18n.commitencoding\n";
1776 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1777 die "Could not encode as UTF-8:\n$msg\n" if $@;
1779 $log_entry{log} = $msg;
1781 close $log_fh or croak $!;
1788 my ($str, $file, $mode) = @_;
1789 open my $fd,'>',$file or croak $!;
1790 print $fd $str,"\n" or croak $!;
1791 close $fd or croak $!;
1792 chmod ($mode &~ umask, $file) if (defined $mode);
1797 open my $fd,'<',$file or croak "$!: file: $file\n";
1800 close $fd or croak $!;
1805 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1807 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1808 my $log = $cmd eq 'log';
1809 while (<$authors>) {
1811 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1812 my ($user, $name, $email) = ($1, $2, $3);
1814 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1816 $users{$user} = [$name, $email];
1819 close $authors or croak $!;
1822 # convert GetOpt::Long specs for use by git-config
1823 sub read_git_config {
1826 foreach my $o (keys %$opts) {
1827 # if we have mixedCase and a long option-only, then
1828 # it's a config-only variable that we don't need for
1830 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1831 my $v = $opts->{$o};
1832 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1834 my $arg = 'git config';
1835 $arg .= ' --int' if ($o =~ /[:=]i$/);
1836 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1837 if (ref $v eq 'ARRAY') {
1838 chomp(my @tmp = `$arg --get-all svn.$key`);
1841 chomp(my $tmp = `$arg --get svn.$key`);
1842 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1847 delete @$opts{@config_only} if @config_only;
1850 sub extract_metadata {
1851 my $id = shift or return (undef, undef, undef);
1852 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1853 \s([a-f\d\-]+)$/ix);
1854 if (!defined $rev || !$uuid || !$url) {
1855 # some of the original repositories I made had
1856 # identifiers like this:
1857 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1859 return ($url, $rev, $uuid);
1863 return extract_metadata((grep(/^git-svn-id: /,
1864 command(qw/cat-file commit/, shift)))[-1]);
1867 sub cmt_sha2rev_batch {
1869 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1872 foreach my $sha (@{$list}) {
1875 print $out $sha, "\n";
1877 while (my $line = <$in>) {
1878 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1881 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1885 } elsif ($line =~ /^(git-svn-id: )/) {
1886 my (undef, $rev, undef) =
1887 extract_metadata($line);
1891 $size -= length($line);
1892 last if ($size == 0);
1896 command_close_bidi_pipe($pid, $in, $out, $ctx);
1901 sub working_head_info {
1902 my ($head, $refs) = @_;
1903 my @args = qw/rev-list --first-parent --pretty=medium/;
1904 my ($fh, $ctx) = command_output_pipe(@args, $head);
1908 if ( m{^commit ($::sha1)$} ) {
1909 unshift @$refs, $hash if $hash and $refs;
1913 next unless s{^\s*(git-svn-id:)}{$1};
1914 my ($url, $rev, $uuid) = extract_metadata($_);
1915 if (defined $url && defined $rev) {
1916 next if $max{$url} and $max{$url} < $rev;
1917 if (my $gs = Git::SVN->find_by_url($url)) {
1918 my $c = $gs->rev_map_get($rev, $uuid);
1919 if ($c && $c eq $hash) {
1920 close $fh; # break the pipe
1921 return ($url, $rev, $uuid, $gs);
1923 $max{$url} ||= $gs->rev_map_max;
1928 command_close_pipe($fh, $ctx);
1929 (undef, undef, undef, undef);
1932 sub read_commit_parents {
1933 my ($parents, $c) = @_;
1934 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1935 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1936 @{$parents->{$c}} = split(/ /, $p);
1939 sub linearize_history {
1940 my ($gs, $refs) = @_;
1942 foreach my $c (@$refs) {
1943 read_commit_parents(\%parents, $c);
1948 my $last_svn_commit = $gs->last_commit;
1949 foreach my $c (reverse @$refs) {
1950 next if $c eq $last_svn_commit;
1953 unshift @linear_refs, $c;
1956 # we only want the first parent to diff against for linear
1957 # history, we save the rest to inject when we finalize the
1959 my $fp_a = verify_ref("$c~1");
1960 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1961 if (!$fp_a || !$fp_b) {
1963 "has no parent commit, and therefore ",
1964 "nothing to diff against.\n",
1965 "You should be working from a repository ",
1966 "originally created by git-svn\n";
1968 if ($fp_a ne $fp_b) {
1969 die "$c~1 = $fp_a, however parsing commit $c ",
1970 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1973 foreach my $p (@{$parents{$c}}) {
1977 (\@linear_refs, \%parents);
1980 sub find_file_type_and_diff_status {
1982 return ('dir', '') if $path eq '';
1985 command_oneline(qw(diff --cached --name-status --), $path) || "";
1986 my $diff_status = (split(' ', $diff_output))[0] || "";
1988 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1990 return (undef, undef) if !$diff_status && !$ls_tree;
1992 if ($diff_status eq "A") {
1993 return ("link", $diff_status) if -l $path;
1994 return ("dir", $diff_status) if -d $path;
1995 return ("file", $diff_status);
1998 my $mode = (split(' ', $ls_tree))[0] || "";
2000 return ("link", $diff_status) if $mode eq "120000";
2001 return ("dir", $diff_status) if $mode eq "040000";
2002 return ("file", $diff_status);
2008 my $md5 = Digest::MD5->new();
2009 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2010 $md5->addfile($arg) or croak $!;
2011 } elsif ($ref eq 'SCALAR') {
2012 $md5->add($$arg) or croak $!;
2014 $md5->add($arg) or croak $!;
2016 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2018 return $md5->hexdigest();
2022 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2023 my $out_filename = $_ . ".gz";
2024 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2026 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2027 die "Unable to open $out_filename: $!\n";
2030 while ($res = sysread($in_fh, my $str, 1024)) {
2031 $gz->gzwrite($str) or
2032 die "Unable to write: ".$gz->gzerror()."!\n";
2034 unlink $_ or die "unlink $File::Find::name: $!\n";
2035 } elsif (-f $_ && basename($_) eq "index") {
2036 unlink $_ or die "unlink $_: $!\n";
2043 use Fcntl qw/:DEFAULT :seek/;
2044 use constant rev_map_fmt => 'NH40';
2045 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2046 $_repack $_repack_flags $_use_svm_props $_head
2047 $_use_svnsync_props $no_reuse_existing $_minimize_url
2048 $_use_log_author $_add_author_from $_localtime/;
2050 use File::Path qw/mkpath/;
2051 use File::Copy qw/copy/;
2054 use Memoize; # core since 5.8.0, Jul 2002
2055 use Memoize::Storable;
2056 use POSIX qw(:signal_h);
2058 my ($_gc_nr, $_gc_period);
2060 # properties that we do not log:
2063 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2064 svn:special svn:executable
2065 svn:entry:committed-rev
2066 svn:entry:last-author
2068 svn:entry:committed-date/;
2070 # some options are read globally, but can be overridden locally
2071 # per [svn-remote "..."] section. Command-line options will *NOT*
2072 # override options set in an [svn-remote "..."] section
2074 for my $option (qw/follow_parent no_metadata use_svm_props
2075 use_svnsync_props/) {
2078 my $prop = "-$option";
2081 return $self->{$prop} if exists $self->{$prop};
2082 my $k = "svn-remote.$self->{repo_id}.$key";
2083 eval { command_oneline(qw/config --get/, $k) };
2085 $self->{$prop} = ${"Git::SVN::_$option"};
2087 my $v = command_oneline(qw/config --bool/,$k);
2088 $self->{$prop} = $v eq 'false' ? 0 : 1;
2090 return $self->{$prop};
2096 my (%LOCKFILES, %INDEX_FILES);
2098 unlink keys %LOCKFILES if %LOCKFILES;
2099 unlink keys %INDEX_FILES if %INDEX_FILES;
2102 sub resolve_local_globs {
2103 my ($url, $fetch, $glob_spec) = @_;
2104 return unless defined $glob_spec;
2105 my $ref = $glob_spec->{ref};
2106 my $path = $glob_spec->{path};
2107 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2108 next unless m#^$ref->{regex}$#;
2110 my $pathname = desanitize_refname($path->full_path($p));
2111 my $refname = desanitize_refname($ref->full_path($p));
2112 if (my $existing = $fetch->{$pathname}) {
2113 if ($existing ne $refname) {
2114 die "Refspec conflict:\n",
2115 "existing: $existing\n",
2116 " globbed: $refname\n";
2118 my $u = (::cmt_metadata("$refname"))[0];
2119 $u =~ s!^\Q$url\E(/|$)!! or die
2120 "$refname: '$url' not found in '$u'\n";
2121 if ($pathname ne $u) {
2122 warn "W: Refspec glob conflict ",
2123 "(ref: $refname):\n",
2124 "expected path: $pathname\n",
2126 "Continuing ahead with $u\n";
2130 $fetch->{$pathname} = $refname;
2135 sub parse_revision_argument {
2136 my ($base, $head) = @_;
2137 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2138 return ($base, $head);
2140 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2141 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2142 return ($head, $head) if ($::_revision eq 'HEAD');
2143 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2144 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2145 die "revision argument: $::_revision not understood by git-svn\n";
2149 my ($repo_id, $remotes) = @_;
2153 $repo_id = $gs->{repo_id};
2155 $remotes ||= read_all_remotes();
2156 my $remote = $remotes->{$repo_id} or
2157 die "[svn-remote \"$repo_id\"] unknown\n";
2158 my $fetch = $remote->{fetch};
2159 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2161 my $ra = Git::SVN::Ra->new($url);
2162 my $uuid = $ra->get_uuid;
2163 my $head = $ra->get_latest_revnum;
2165 # ignore errors, $head revision may not even exist anymore
2166 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2167 warn "W: $@\n" if $@;
2169 my $base = defined $fetch ? $head : 0;
2171 # read the max revs for wildcard expansion (branches/*, tags/*)
2172 foreach my $t (qw/branches tags/) {
2173 defined $remote->{$t} or next;
2174 push @globs, @{$remote->{$t}};
2176 my $max_rev = eval { tmp_config(qw/--int --get/,
2177 "svn-remote.$repo_id.${t}-maxRev") };
2178 if (defined $max_rev && ($max_rev < $base)) {
2180 } elsif (!defined $max_rev) {
2186 foreach my $p (sort keys %$fetch) {
2187 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2188 my $lr = $gs->rev_map_max;
2190 $base = $lr if ($lr < $base);
2196 ($base, $head) = parse_revision_argument($base, $head);
2197 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2200 sub read_all_remotes {
2202 my $use_svm_props = eval { command_oneline(qw/config --bool
2203 svn.useSvmProps/) };
2204 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2205 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2206 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2207 if (m!^(.+)\.fetch=$svn_refspec$!) {
2208 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2209 die("svn-remote.$remote: remote ref '$remote_ref' "
2210 . "must start with 'refs/'\n")
2211 unless $remote_ref =~ m{^refs/};
2212 $local_ref = uri_decode($local_ref);
2213 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2214 $r->{$remote}->{svm} = {} if $use_svm_props;
2215 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2216 $r->{$1}->{svm} = {};
2217 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2218 $r->{$1}->{url} = $2;
2219 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2220 $r->{$1}->{pushurl} = $2;
2221 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2222 $r->{$1}->{ignore_refs_regex} = $2;
2223 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2224 my ($remote, $t, $local_ref, $remote_ref) =
2226 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2227 . "must start with 'refs/'\n")
2228 unless $remote_ref =~ m{^refs/};
2229 $local_ref = uri_decode($local_ref);
2233 path => Git::SVN::GlobSpec->new($local_ref, 1),
2234 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2235 if (length($rs->{ref}->{right}) != 0) {
2236 die "The '*' glob character must be the last ",
2237 "character of '$remote_ref'\n";
2239 push @{ $r->{$remote}->{$t} }, $rs;
2244 if (defined $r->{$_}->{svm}) {
2247 my $section = "svn-remote.$_";
2249 source => tmp_config('--get',
2250 "$section.svm-source"),
2251 replace => tmp_config('--get',
2252 "$section.svm-replace"),
2255 $r->{$_}->{svm} = $svm;
2259 foreach my $remote (keys %$r) {
2260 foreach ( grep { defined $_ }
2261 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2262 foreach my $rs ( @$_ ) {
2263 $rs->{ignore_refs_regex} =
2264 $r->{$remote}->{ignore_refs_regex};
2273 $_gc_nr = $_gc_period = 1000;
2274 if (defined $_repack || defined $_repack_flags) {
2275 warn "Repack options are obsolete; they have no effect.\n";
2279 sub verify_remotes_sanity {
2280 return unless -d $ENV{GIT_DIR};
2282 foreach (command(qw/config -l/)) {
2283 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2285 die "Remote ref refs/remote/$1 is tracked by",
2286 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2287 "Please resolve this ambiguity in ",
2288 "your git configuration file before ",
2296 sub find_existing_remote {
2297 my ($url, $remotes) = @_;
2298 return undef if $no_reuse_existing;
2300 foreach my $repo_id (keys %$remotes) {
2301 my $u = $remotes->{$repo_id}->{url} or next;
2303 $existing = $repo_id;
2309 sub init_remote_config {
2310 my ($self, $url, $no_write) = @_;
2311 $url =~ s!/+$!!; # strip trailing slash
2312 my $r = read_all_remotes();
2313 my $existing = find_existing_remote($url, $r);
2315 unless ($no_write) {
2316 print STDERR "Using existing ",
2317 "[svn-remote \"$existing\"]\n";
2319 $self->{repo_id} = $existing;
2320 } elsif ($_minimize_url) {
2321 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2322 $existing = find_existing_remote($min_url, $r);
2324 unless ($no_write) {
2325 print STDERR "Using existing ",
2326 "[svn-remote \"$existing\"]\n";
2328 $self->{repo_id} = $existing;
2330 if ($min_url ne $url) {
2331 unless ($no_write) {
2332 print STDERR "Using higher level of URL: ",
2333 "$url => $min_url\n";
2335 my $old_path = $self->{path};
2336 $self->{path} = $url;
2337 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2338 if (length $old_path) {
2339 $self->{path} .= "/$old_path";
2346 # verify that we aren't overwriting anything:
2348 command_oneline('config', '--get',
2349 "svn-remote.$self->{repo_id}.url")
2351 if ($orig_url && ($orig_url ne $url)) {
2352 die "svn-remote.$self->{repo_id}.url already set: ",
2353 "$orig_url\nwanted to set to: $url\n";
2356 my ($xrepo_id, $xpath) = find_ref($self->refname);
2357 if (!$no_write && defined $xpath) {
2358 die "svn-remote.$xrepo_id.fetch already set to track ",
2359 "$xpath:", $self->refname, "\n";
2361 unless ($no_write) {
2362 command_noisy('config',
2363 "svn-remote.$self->{repo_id}.url", $url);
2364 $self->{path} =~ s{^/}{};
2365 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2366 command_noisy('config', '--add',
2367 "svn-remote.$self->{repo_id}.fetch",
2368 "$self->{path}:".$self->refname);
2370 $self->{url} = $url;
2373 sub find_by_url { # repos_root and, path are optional
2374 my ($class, $full_url, $repos_root, $path) = @_;
2376 return undef unless defined $full_url;
2377 remove_username($full_url);
2378 remove_username($repos_root) if defined $repos_root;
2379 my $remotes = read_all_remotes();
2380 if (defined $full_url && defined $repos_root && !defined $path) {
2382 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2384 foreach my $repo_id (keys %$remotes) {
2385 my $u = $remotes->{$repo_id}->{url} or next;
2386 remove_username($u);
2387 next if defined $repos_root && $repos_root ne $u;
2389 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2390 foreach my $t (qw/branches tags/) {
2391 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2392 resolve_local_globs($u, $fetch, $globspec);
2396 my $rwr = rewrite_root({repo_id => $repo_id});
2397 my $svm = $remotes->{$repo_id}->{svm}
2398 if defined $remotes->{$repo_id}->{svm};
2399 unless (defined $p) {
2405 remove_username($z);
2406 } elsif (defined $svm) {
2407 $z = $svm->{source};
2408 $prefix = $svm->{replace};
2409 $prefix =~ s#^\Q$u\E(?:/|$)##;
2412 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2414 foreach my $f (keys %$fetch) {
2416 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2423 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2424 my $self = _new($class, $repo_id, $ref_id, $path);
2426 $self->init_remote_config($url, $no_write);
2433 foreach (command(qw/config -l/)) {
2434 next unless m!^svn-remote\.(.+)\.fetch=
2435 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2436 my ($repo_id, $path, $ref) = ($1, $2, $3);
2437 if ($ref eq $ref_id) {
2438 $path = '' if ($path =~ m#^\./?#);
2439 return ($repo_id, $path);
2442 (undef, undef, undef);
2446 my ($class, $ref_id, $repo_id, $path) = @_;
2447 if (defined $ref_id && !defined $repo_id && !defined $path) {
2448 ($repo_id, $path) = find_ref($ref_id);
2449 if (!defined $repo_id) {
2450 die "Could not find a \"svn-remote.*.fetch\" key ",
2451 "in the repository configuration matching: ",
2455 my $self = _new($class, $repo_id, $ref_id, $path);
2456 if (!defined $self->{path} || !length $self->{path}) {
2457 my $fetch = command_oneline('config', '--get',
2458 "svn-remote.$repo_id.fetch",
2460 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2461 "\":$ref_id\$\" in config\n";
2462 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2464 $self->{path} =~ s{/+}{/}g;
2465 $self->{path} =~ s{\A/}{};
2466 $self->{path} =~ s{/\z}{};
2467 $self->{url} = command_oneline('config', '--get',
2468 "svn-remote.$repo_id.url") or
2469 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2470 $self->{pushurl} = eval { command_oneline('config', '--get',
2471 "svn-remote.$repo_id.pushurl") };
2477 my ($refname) = $_[0]->{ref_id} ;
2479 # It cannot end with a slash /, we'll throw up on this because
2480 # SVN can't have directories with a slash in their name, either:
2481 if ($refname =~ m{/$}) {
2482 die "ref: '$refname' ends with a trailing slash, this is ",
2483 "not permitted by git nor Subversion\n";
2486 # It cannot have ASCII control character space, tilde ~, caret ^,
2487 # colon :, question-mark ?, asterisk *, space, or open bracket [
2490 # Additionally, % must be escaped because it is used for escaping
2491 # and we want our escaped refname to be reversible
2492 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2494 # no slash-separated component can begin with a dot .
2496 $refname =~ s{/\.}{/%2E}g;
2498 # It cannot have two consecutive dots .. anywhere
2500 $refname =~ s{\.\.}{%2E%2E}g;
2502 # trailing dots and .lock are not allowed
2503 # .$ becomes %2E and .lock becomes %2Elock
2504 $refname =~ s{\.(?=$|lock$)}{%2E};
2506 # the sequence @{ is used to access the reflog
2508 $refname =~ s{\@\{}{%40\{}g;
2513 sub desanitize_refname {
2515 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2521 return $self->{svm}->{uuid} if $self->svm;
2523 unless ($self->{svm}) {
2524 die "SVM UUID not cached, and reading remotely failed\n";
2526 $self->{svm}->{uuid};
2531 return $self->{svm} if $self->{svm};
2533 # see if we have it in our config, first:
2535 my $section = "svn-remote.$self->{repo_id}";
2537 source => tmp_config('--get', "$section.svm-source"),
2538 uuid => tmp_config('--get', "$section.svm-uuid"),
2539 replace => tmp_config('--get', "$section.svm-replace"),
2542 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2543 $self->{svm} = $svm;
2549 my ($self, $ra) = @_;
2550 return $ra if $self->svm;
2552 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2553 "(svm:source, svm:uuid) ",
2554 "from the following URLs:\n" );
2555 sub read_svm_props {
2556 my ($self, $ra, $path, $r) = @_;
2557 my $props = ($ra->get_dir($path, $r))[2];
2558 my $src = $props->{'svm:source'};
2559 my $uuid = $props->{'svm:uuid'};
2560 return undef if (!$src || !$uuid);
2564 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2565 or die "doesn't look right - svm:uuid is '$uuid'\n";
2567 # the '!' is used to mark the repos_root!/relative/path
2568 $src =~ s{/?!/?}{/};
2569 $src =~ s{/+$}{}; # no trailing slashes please
2570 # username is of no interest
2571 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2573 my $replace = $ra->{url};
2574 $replace .= "/$path" if length $path;
2576 my $section = "svn-remote.$self->{repo_id}";
2577 tmp_config("$section.svm-source", $src);
2578 tmp_config("$section.svm-replace", $replace);
2579 tmp_config("$section.svm-uuid", $uuid);
2587 my $r = $ra->get_latest_revnum;
2588 my $path = $self->{path};
2590 while (length $path) {
2591 unless ($tried{"$self->{url}/$path"}) {
2592 return $ra if $self->read_svm_props($ra, $path, $r);
2593 $tried{"$self->{url}/$path"} = 1;
2595 $path =~ s#/?[^/]+$##;
2597 die "Path: '$path' should be ''\n" if $path ne '';
2598 return $ra if $self->read_svm_props($ra, $path, $r);
2599 $tried{"$self->{url}/$path"} = 1;
2601 if ($ra->{repos_root} eq $self->{url}) {
2602 die @err, (map { " $_\n" } keys %tried), "\n";
2605 # nope, make sure we're connected to the repository root:
2608 $path = $ra->{svn_path};
2609 $ra = Git::SVN::Ra->new($ra->{repos_root});
2610 while (length $path) {
2611 unless ($tried{"$ra->{url}/$path"}) {
2612 $ok = $self->read_svm_props($ra, $path, $r);
2614 $tried{"$ra->{url}/$path"} = 1;
2616 $path =~ s#/?[^/]+$##;
2618 die "Path: '$path' should be ''\n" if $path ne '';
2619 $ok ||= $self->read_svm_props($ra, $path, $r);
2620 $tried{"$ra->{url}/$path"} = 1;
2622 die @err, (map { " $_\n" } keys %tried), "\n";
2624 Git::SVN::Ra->new($self->{url});
2629 return $self->{svnsync} if $self->{svnsync};
2631 if ($self->no_metadata) {
2632 die "Can't have both 'noMetadata' and ",
2633 "'useSvnsyncProps' options set!\n";
2635 if ($self->rewrite_root) {
2636 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2639 if ($self->rewrite_uuid) {
2640 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2645 # see if we have it in our config, first:
2647 my $section = "svn-remote.$self->{repo_id}";
2649 my $url = tmp_config('--get', "$section.svnsync-url");
2650 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2651 die "doesn't look right - svn:sync-from-url is '$url'\n";
2653 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2654 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2655 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2657 $svnsync = { url => $url, uuid => $uuid }
2659 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2660 return $self->{svnsync} = $svnsync;
2663 my $err = "useSvnsyncProps set, but failed to read " .
2664 "svnsync property: svn:sync-from-";
2665 my $rp = $self->ra->rev_proplist(0);
2667 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2668 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2669 die "doesn't look right - svn:sync-from-url is '$url'\n";
2671 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2672 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2673 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2675 my $section = "svn-remote.$self->{repo_id}";
2676 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2677 tmp_config('--add', "$section.svnsync-url", $url);
2678 return $self->{svnsync} = { url => $url, uuid => $uuid };
2681 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2682 # remote lookup (useful for 'git svn log').
2685 unless ($self->{ra_uuid}) {
2686 my $key = "svn-remote.$self->{repo_id}.uuid";
2687 my $uuid = eval { tmp_config('--get', $key) };
2688 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2689 $self->{ra_uuid} = $uuid;
2691 die "ra_uuid called without URL\n" unless $self->{url};
2692 $self->{ra_uuid} = $self->ra->get_uuid;
2693 tmp_config('--add', $key, $self->{ra_uuid});
2699 sub _set_repos_root {
2700 my ($self, $repos_root) = @_;
2701 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2702 $repos_root ||= $self->ra->{repos_root};
2703 tmp_config($k, $repos_root);
2709 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2710 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2715 my $ra = Git::SVN::Ra->new($self->{url});
2716 $self->_set_repos_root($ra->{repos_root});
2717 if ($self->use_svm_props && !$self->{svm}) {
2718 if ($self->no_metadata) {
2719 die "Can't have both 'noMetadata' and ",
2720 "'useSvmProps' options set!\n";
2721 } elsif ($self->use_svnsync_props) {
2722 die "Can't have both 'useSvnsyncProps' and ",
2723 "'useSvmProps' options set!\n";
2725 $ra = $self->_set_svm_vars($ra);
2726 $self->{-want_revprops} = 1;
2731 # prop_walk(PATH, REV, SUB)
2732 # -------------------------
2733 # Recursively traverse PATH at revision REV and invoke SUB for each
2734 # directory that contains a SVN property. SUB will be invoked as
2735 # follows: &SUB(gs, path, props); where `gs' is this instance of
2736 # Git::SVN, `path' the path to the directory where the properties
2737 # `props' were found. The `path' will be relative to point of checkout,
2738 # that is, if url://repo/trunk is the current Git branch, and that
2739 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2740 # as `path' (note the trailing `/').
2742 my ($self, $path, $rev, $sub) = @_;
2745 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2748 # Strip the irrelevant part of the path.
2749 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2750 # Ensure the path is terminated by a `/'.
2753 # The properties contain all the internal SVN stuff nobody
2754 # (usually) cares about.
2755 my $interesting_props = 0;
2756 foreach (keys %{$props}) {
2757 # If it doesn't start with `svn:', it must be a
2758 # user-defined property.
2759 ++$interesting_props and next if $_ !~ /^svn:/;
2760 # FIXME: Fragile, if SVN adds new public properties,
2761 # this needs to be updated.
2762 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2763 |eol-style|mime-type
2764 |externals|needs-lock)$/x;
2766 &$sub($self, $p, $props) if $interesting_props;
2768 foreach (sort keys %$dirent) {
2769 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2770 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2774 sub last_rev { ($_[0]->last_rev_commit)[0] }
2775 sub last_commit { ($_[0]->last_rev_commit)[1] }
2777 # returns the newest SVN revision number and newest commit SHA1
2778 sub last_rev_commit {
2780 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2781 return ($self->{last_rev}, $self->{last_commit});
2783 my $c = ::verify_ref($self->refname.'^0');
2784 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2785 my $rev = (::cmt_metadata($c))[1];
2787 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2791 my $map_path = $self->map_path;
2792 unless (-e $map_path) {
2793 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2794 return (undef, undef);
2796 my ($rev, $commit) = $self->rev_map_max(1);
2797 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2798 return ($rev, $commit);
2801 sub get_fetch_range {
2802 my ($self, $min, $max) = @_;
2803 $max ||= $self->ra->get_latest_revnum;
2804 $min ||= $self->rev_map_max;
2810 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2811 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2812 if (! -f $config && -f $old_def_config) {
2813 rename $old_def_config, $config or
2814 die "Failed rename $old_def_config => $config: $!\n";
2816 my $old_config = $ENV{GIT_CONFIG};
2817 $ENV{GIT_CONFIG} = $config;
2820 unless (-f $config) {
2822 open my $fh, '>', $config or
2823 die "Can't open $config: $!\n";
2824 print $fh "; This file is used internally by ",
2826 "Couldn't write to $config: $!\n";
2827 print $fh "; You should not have to edit it\n" or
2828 die "Couldn't write to $config: $!\n";
2829 close $fh or die "Couldn't close $config: $!\n";
2831 command('config', @args);
2834 if (defined $old_config) {
2835 $ENV{GIT_CONFIG} = $old_config;
2837 delete $ENV{GIT_CONFIG};
2840 wantarray ? @ret : $ret[0];
2844 my ($self, $sub) = @_;
2845 my $old_index = $ENV{GIT_INDEX_FILE};
2846 $ENV{GIT_INDEX_FILE} = $self->{index};
2849 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2850 mkpath([$dir]) unless -d $dir;
2854 if (defined $old_index) {
2855 $ENV{GIT_INDEX_FILE} = $old_index;
2857 delete $ENV{GIT_INDEX_FILE};
2860 wantarray ? @ret : $ret[0];
2863 sub assert_index_clean {
2864 my ($self, $treeish) = @_;
2866 $self->tmp_index_do(sub {
2867 command_noisy('read-tree', $treeish) unless -e $self->{index};
2868 my $x = command_oneline('write-tree');
2869 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2870 /^tree ($::sha1)/mo);
2873 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2874 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2875 command_noisy('read-tree', $treeish);
2876 $x = command_oneline('write-tree');
2878 ::fatal "trees ($treeish) $y != $x\n",
2879 "Something is seriously wrong...";
2884 sub get_commit_parents {
2885 my ($self, $log_entry) = @_;
2886 my (%seen, @ret, @tmp);
2887 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2888 if (my $ip = $self->{inject_parents}) {
2889 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2893 if (my $cur = ::verify_ref($self->refname.'^0')) {
2896 if (my $ipd = $self->{inject_parents_dcommit}) {
2897 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2898 push @tmp, @$commit;
2901 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2902 while (my $p = shift @tmp) {
2912 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2913 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2914 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2917 if ($rwr !~ m#^[a-z\+]+://#) {
2918 die "$rwr is not a valid URL (key: $k)\n";
2921 $self->{-rewrite_root} = $rwr;
2926 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2927 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2928 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2931 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2932 die "$rwid is not a valid UUID (key: $k)\n";
2935 $self->{-rewrite_uuid} = $rwid;
2940 ($self->rewrite_root || $self->{url}) .
2941 (length $self->{path} ? '/' . $self->{path} : '');
2946 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2951 if ($self->{pushurl}) {
2952 return $self->{pushurl} . (length $self->{path} ? '/' .
2953 $self->{path} : '');
2955 return $self->full_url;
2959 sub set_commit_header_env {
2960 my ($log_entry) = @_;
2962 foreach my $ned (qw/NAME EMAIL DATE/) {
2963 foreach my $ac (qw/AUTHOR COMMITTER/) {
2964 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2968 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2969 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2970 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2972 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2973 ? $log_entry->{commit_name}
2974 : $log_entry->{name};
2975 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2976 ? $log_entry->{commit_email}
2977 : $log_entry->{email};
2981 sub restore_commit_header_env {
2983 foreach my $ned (qw/NAME EMAIL DATE/) {
2984 foreach my $ac (qw/AUTHOR COMMITTER/) {
2985 my $k = "GIT_${ac}_${ned}";
2986 if (defined $env->{$k}) {
2987 $ENV{$k} = $env->{$k};
2996 command_noisy('gc', '--auto');
3000 my ($self, $log_entry) = @_;
3001 my $lr = $self->last_rev;
3002 if (defined $lr && $lr >= $log_entry->{revision}) {
3003 die "Last fetched revision of ", $self->refname,
3004 " was r$lr, but we are about to fetch: ",
3005 "r$log_entry->{revision}!\n";
3007 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3008 croak "$log_entry->{revision} = $c already exists! ",
3009 "Why are we refetching it?\n";
3011 my $old_env = set_commit_header_env($log_entry);
3012 my $tree = $log_entry->{tree};
3013 if (!defined $tree) {
3014 $tree = $self->tmp_index_do(sub {
3015 command_oneline('write-tree') });
3017 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3019 my @exec = ('git', 'commit-tree', $tree);
3020 foreach ($self->get_commit_parents($log_entry)) {
3021 push @exec, '-p', $_;
3023 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3027 # we always get UTF-8 from SVN, but we may want our commits in
3028 # a different encoding.
3029 if (my $enc = Git::config('i18n.commitencoding')) {
3031 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3033 print $msg_fh $log_entry->{log} or croak $!;
3034 restore_commit_header_env($old_env);
3035 unless ($self->no_metadata) {
3036 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3039 $msg_fh->flush == 0 or croak $!;
3040 close $msg_fh or croak $!;
3041 chomp(my $commit = do { local $/; <$out_fh> });
3042 close $out_fh or croak $!;
3045 if ($commit !~ /^$::sha1$/o) {
3046 die "Failed to commit, invalid sha1: $commit\n";
3049 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3051 $self->{last_rev} = $log_entry->{revision};
3052 $self->{last_commit} = $commit;
3053 print "r$log_entry->{revision}" unless $::_q > 1;
3054 if (defined $log_entry->{svm_revision}) {
3055 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3056 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3057 0, $self->svm_uuid);
3059 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3060 if (--$_gc_nr == 0) {
3061 $_gc_nr = $_gc_period;
3068 my ($self, $paths, $r) = @_;
3069 return 1 if $self->{path} eq '';
3070 if (my $path = $paths->{"/$self->{path}"}) {
3071 return ($path->{action} eq 'D') ? 0 : 1;
3073 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3074 if (grep /$self->{path_regex}/, keys %$paths) {
3078 foreach (split m#/#, $self->{path}) {
3080 next unless ($paths->{$c} &&
3081 ($paths->{$c}->{action} =~ /^[AR]$/));
3082 if ($self->ra->check_path($self->{path}, $r) ==
3090 sub find_parent_branch {
3091 my ($self, $paths, $rev) = @_;
3092 return undef unless $self->follow_parent;
3093 unless (defined $paths) {
3094 my $err_handler = $SVN::Error::handler;
3095 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3096 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3097 sub { $paths = $_[0] });
3098 $SVN::Error::handler = $err_handler;
3100 return undef unless defined $paths;
3102 # look for a parent from another branch:
3103 my @b_path_components = split m#/#, $self->{path};
3104 my @a_path_components;
3106 while (@b_path_components) {
3107 $i = $paths->{'/'.join('/', @b_path_components)};
3108 last if $i && defined $i->{copyfrom_path};
3109 unshift(@a_path_components, pop(@b_path_components));
3111 return undef unless defined $i && defined $i->{copyfrom_path};
3112 my $branch_from = $i->{copyfrom_path};
3113 if (@a_path_components) {
3114 print STDERR "branch_from: $branch_from => ";
3115 $branch_from .= '/'.join('/', @a_path_components);
3116 print STDERR $branch_from, "\n";
3118 my $r = $i->{copyfrom_rev};
3119 my $repos_root = $self->ra->{repos_root};
3120 my $url = $self->ra->{url};
3121 my $new_url = $url . $branch_from;
3122 print STDERR "Found possible branch point: ",
3123 "$new_url => ", $self->full_url, ", $r\n"
3125 $branch_from =~ s#^/##;
3126 my $gs = $self->other_gs($new_url, $url,
3127 $branch_from, $r, $self->{ref_id});
3128 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3131 if (!defined $r0 || !defined $parent) {
3132 ($base, $head) = parse_revision_argument(0, $r);
3135 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3136 0, 1, sub { $base = $_[1] - 1 });
3139 if (defined $base && $base <= $r) {
3140 $gs->fetch($base, $r);
3142 ($r0, $parent) = $gs->find_rev_before($r, 1);
3144 if (defined $r0 && defined $parent) {
3145 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3148 if ($self->ra->can_do_switch) {
3149 $self->assert_index_clean($parent);
3150 print STDERR "Following parent with do_switch\n"
3152 # do_switch works with svn/trunk >= r22312, but that
3153 # is not included with SVN 1.4.3 (the latest version
3154 # at the moment), so we can't rely on it
3155 $self->{last_rev} = $r0;
3156 $self->{last_commit} = $parent;
3157 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3158 $gs->ra->gs_do_switch($r0, $rev, $gs,
3159 $self->full_url, $ed)
3160 or die "SVN connection failed somewhere...\n";
3161 } elsif ($self->ra->trees_match($new_url, $r0,
3162 $self->full_url, $rev)) {
3163 print STDERR "Trees match:\n",
3165 " ${\$self->full_url}\@$rev\n",
3166 "Following parent with no changes\n"
3168 $self->tmp_index_do(sub {
3169 command_noisy('read-tree', $parent);
3171 $self->{last_commit} = $parent;
3173 print STDERR "Following parent with do_update\n"
3175 $ed = SVN::Git::Fetcher->new($self);
3176 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3177 or die "SVN connection failed somewhere...\n";
3179 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3180 return $self->make_log_entry($rev, [$parent], $ed);
3186 my ($self, $paths, $rev) = @_;
3188 my ($last_rev, @parents);
3189 if (my $lc = $self->last_commit) {
3190 # we can have a branch that was deleted, then re-added
3191 # under the same name but copied from another path, in
3192 # which case we'll have multiple parents (we don't
3193 # want to break the original ref, nor lose copypath info):
3194 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3195 push @{$log_entry->{parents}}, $lc;
3198 $ed = SVN::Git::Fetcher->new($self);
3199 $last_rev = $self->{last_rev};
3204 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3207 $ed = SVN::Git::Fetcher->new($self);
3209 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3210 die "SVN connection failed somewhere...\n";
3212 $self->make_log_entry($rev, \@parents, $ed);
3216 my ($self, $r) = @_;
3219 my ($r, $empty_dirs, $line) = @_;
3220 if (defined $r && $line =~ /^r(\d+)$/) {
3221 return 0 if $1 > $r;
3222 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3223 $empty_dirs->{$1} = 1;
3224 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3225 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3226 delete @$empty_dirs{@d};
3231 my %empty_dirs = ();
3232 my $gz_file = "$self->{dir}/unhandled.log.gz";
3234 if (!$can_compress) {
3235 warn "Compress::Zlib could not be found; ",
3236 "empty directories in $gz_file will not be read\n";
3238 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3239 die "Unable to open $gz_file: $!\n";
3241 while ($gz->gzreadline($line) > 0) {
3242 scan($r, \%empty_dirs, $line) or last;
3248 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3249 binmode $fh or croak "binmode: $!";
3251 scan($r, \%empty_dirs, $_) or last;
3256 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3257 foreach my $d (sort keys %empty_dirs) {
3258 $d = uri_decode($d);
3260 next unless length($d);
3263 warn "$d exists but is not a directory\n";
3265 print "creating empty directory: $d\n";
3272 my ($self, $ed) = @_;
3274 my $h = $ed->{empty};
3275 foreach (sort keys %$h) {
3276 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3277 push @out, " $act: " . uri_encode($_);
3278 warn "W: $act: $_\n";
3280 foreach my $t (qw/dir_prop file_prop/) {
3281 $h = $ed->{$t} or next;
3282 foreach my $path (sort keys %$h) {
3283 my $ppath = $path eq '' ? '.' : $path;
3284 foreach my $prop (sort keys %{$h->{$path}}) {
3285 next if $SKIP_PROP{$prop};
3286 my $v = $h->{$path}->{$prop};
3287 my $t_ppath_prop = "$t: " .
3288 uri_encode($ppath) . ' ' .
3291 push @out, " +$t_ppath_prop " .
3294 push @out, " -$t_ppath_prop";
3299 foreach my $t (qw/absent_file absent_directory/) {
3300 $h = $ed->{$t} or next;
3301 foreach my $parent (sort keys %$h) {
3302 foreach my $path (sort @{$h->{$parent}}) {
3303 push @out, " $t: " .
3304 uri_encode("$parent/$path");
3305 warn "W: $t: $parent/$path ",
3306 "Insufficient permissions?\n";
3314 # some systmes don't handle or mishandle %z, so be creative.
3315 my $t = shift || time;
3316 my $gm = timelocal(gmtime($t));
3317 my $sign = qw( + + - )[ $t <=> $gm ];
3318 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3321 # parse_svn_date(DATE)
3322 # --------------------
3323 # Given a date (in UTC) from Subversion, return a string in the format
3324 # "<TZ Offset> <local date/time>" that Git will use.
3326 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3327 # is true we'll convert it to the local timezone instead.
3328 sub parse_svn_date {
3329 my $date = shift || return '+0000 1970-01-01 00:00:00';
3330 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3331 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3332 croak "Unable to parse date: $date\n";
3333 my $parsed_date; # Set next.
3335 if ($Git::SVN::_localtime) {
3336 # Translate the Subversion datetime to an epoch time.
3337 # Begin by switching ourselves to $date's timezone, UTC.
3338 my $old_env_TZ = $ENV{TZ};
3342 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3344 # Determine our local timezone (including DST) at the
3345 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3346 # value of TZ, if any, at the time we were run.
3347 if (defined $Git::SVN::Log::TZ) {
3348 $ENV{TZ} = $Git::SVN::Log::TZ;
3353 my $our_TZ = get_tz();
3355 # This converts $epoch_in_UTC into our local timezone.
3356 my ($sec, $min, $hour, $mday, $mon, $year,
3357 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3359 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3360 $our_TZ, $year + 1900, $mon + 1,
3361 $mday, $hour, $min, $sec);
3363 # Reset us to the timezone in effect when we entered
3365 if (defined $old_env_TZ) {
3366 $ENV{TZ} = $old_env_TZ;
3371 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3374 return $parsed_date;
3378 my ($self, $new_url, $url,
3379 $branch_from, $r, $old_ref_id) = @_;
3380 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3382 my $ref_id = $old_ref_id;
3383 $ref_id =~ s/\@\d+-*$//;
3385 # just grow a tail if we're not unique enough :x
3386 $ref_id .= '-' while find_ref($ref_id);
3387 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3388 if ($u =~ s#^\Q$url\E(/|$)##) {
3391 $repo_id = $self->{repo_id};
3394 # It is possible to tag two different subdirectories at
3395 # the same revision. If the url for an existing ref
3396 # does not match, we must either find a ref with a
3397 # matching url or create a new ref by growing a tail.
3398 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3399 my (undef, $max_commit) = $gs->rev_map_max(1);
3400 last if (!$max_commit);
3401 my ($url) = ::cmt_metadata($max_commit);
3402 last if ($url eq $gs->metadata_url);
3405 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3410 sub call_authors_prog {
3411 my ($orig_author) = @_;
3412 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3413 my $author = `$::_authors_prog $orig_author`;
3415 die "$::_authors_prog failed with exit code $?\n"
3417 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3418 my ($name, $email) = ($1, $2);
3419 $email = undef if length $2 == 0;
3420 return [$name, $email];
3422 die "Author: $orig_author: $::_authors_prog returned "
3423 . "invalid author format: $author\n";
3429 if (!defined $author || length $author == 0) {
3430 $author = '(no author)';
3432 if (!defined $::users{$author}) {
3433 if (defined $::_authors_prog) {
3434 $::users{$author} = call_authors_prog($author);
3435 } elsif (defined $::_authors) {
3436 die "Author: $author not defined in $::_authors file\n";
3442 sub find_extra_svk_parents {
3443 my ($self, $ed, $tickets, $parents) = @_;
3444 # aha! svk:merge property changed...
3445 my @tickets = split "\n", $tickets;
3447 for my $ticket ( @tickets ) {
3448 my ($uuid, $path, $rev) = split /:/, $ticket;
3449 if ( $uuid eq $self->ra_uuid ) {
3450 my $url = $self->{url};
3451 my $repos_root = $url;
3452 my $branch_from = $path;
3453 $branch_from =~ s{^/}{};
3454 my $gs = $self->other_gs($repos_root."/".$branch_from,
3459 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3460 # wahey! we found it, but it might be
3462 push @known_parents, [ $rev, $commit ];
3466 # Ordering matters; highest-numbered commit merge tickets
3467 # first, as they may account for later merge ticket additions
3469 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3470 for my $parent ( @known_parents ) {
3471 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3472 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3474 while ( <$msg_fh> ) {
3477 command_close_pipe($msg_fh, $ctx);
3480 "Found merge parent (svk:merge ticket): $parent\n";
3481 push @$parents, $parent;
3486 sub lookup_svn_merge {
3491 my ($source, $revs) = split ":", $merge;
3494 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3496 warn "Couldn't find revmap for $url$source\n";
3499 my @ranges = split ",", $revs;
3500 my ($tip, $tip_commit);
3501 my @merged_commit_ranges;
3503 for my $range ( @ranges ) {
3504 my ($bottom, $top) = split "-", $range;
3506 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3507 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3509 unless ($top_commit and $bottom_commit) {
3510 warn "W:unknown path/rev in svn:mergeinfo "
3511 ."dirprop: $source:$range\n";
3515 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3516 push @merged_commit_ranges,
3517 "$bottom_commit^..$top_commit";
3519 push @merged_commit_ranges, "$top_commit";
3522 if ( !defined $tip or $top > $tip ) {
3524 $tip_commit = $top_commit;
3527 return ($tip_commit, @merged_commit_ranges);
3531 my ($msg_fh, $ctx) = command_output_pipe(
3535 while ( <$msg_fh> ) {
3539 command_close_pipe($msg_fh, $ctx);
3543 sub check_cherry_pick {
3546 my $parents = shift;
3548 my %commits = map { $_ => 1 }
3549 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3550 for my $range ( @ranges ) {
3551 delete @commits{_rev_list($range, "--")};
3553 for my $commit (keys %commits) {
3554 if (has_no_changes($commit)) {
3555 delete $commits{$commit};
3558 return (keys %commits);
3561 sub has_no_changes {
3564 my @revs = split / /, command_oneline(
3565 qw(rev-list --parents -1 -m), $commit);
3567 # Commits with no parents, e.g. the start of a partial branch,
3568 # have changes by definition.
3569 return 1 if (@revs < 2);
3571 # Commits with multiple parents, e.g a merge, have no changes
3573 return 0 if (@revs > 2);
3575 return (command_oneline("rev-parse", "$commit^{tree}") eq
3576 command_oneline("rev-parse", "$commit~1^{tree}"));
3579 # The GIT_DIR environment variable is not always set until after the command
3580 # line arguments are processed, so we can't memoize in a BEGIN block.
3584 sub memoize_svn_mergeinfo_functions {
3585 return if $memoized;
3588 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3589 mkpath([$cache_path]) unless -d $cache_path;
3591 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3592 "$cache_path/lookup_svn_merge.db", 'nstore';
3593 memoize 'lookup_svn_merge',
3594 SCALAR_CACHE => 'FAULT',
3595 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3598 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3599 "$cache_path/check_cherry_pick.db", 'nstore';
3600 memoize 'check_cherry_pick',
3601 SCALAR_CACHE => 'FAULT',
3602 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3605 tie my %has_no_changes_cache => 'Memoize::Storable',
3606 "$cache_path/has_no_changes.db", 'nstore';
3607 memoize 'has_no_changes',
3608 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3609 LIST_CACHE => 'FAULT',
3613 sub unmemoize_svn_mergeinfo_functions {
3614 return if not $memoized;
3617 Memoize::unmemoize 'lookup_svn_merge';
3618 Memoize::unmemoize 'check_cherry_pick';
3619 Memoize::unmemoize 'has_no_changes';
3622 Memoize::memoize 'Git::SVN::repos_root';
3626 # Force cache writeout explicitly instead of waiting for
3627 # global destruction to avoid segfault in Storable:
3628 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3629 unmemoize_svn_mergeinfo_functions();
3632 sub parents_exclude {
3633 my $parents = shift;
3635 return unless @commits;
3640 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3641 $excluded = command_oneline(@cmd);
3645 for my $commit ( @commits ) {
3646 if ( $commit eq $excluded ) {
3647 push @excluded, $commit;
3655 die "saw commit '$excluded' in rev-list output, "
3656 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3661 while ($excluded and @commits);
3667 # note: this function should only be called if the various dirprops
3668 # have actually changed
3669 sub find_extra_svn_parents {
3670 my ($self, $ed, $mergeinfo, $parents) = @_;
3671 # aha! svk:merge property changed...
3673 memoize_svn_mergeinfo_functions();
3675 # We first search for merged tips which are not in our
3676 # history. Then, we figure out which git revisions are in
3677 # that tip, but not this revision. If all of those revisions
3678 # are now marked as merge, we can add the tip as a parent.
3679 my @merges = split "\n", $mergeinfo;
3681 my $url = $self->{url};
3682 my $uuid = $self->ra_uuid;
3684 for my $merge ( @merges ) {
3685 my ($tip_commit, @ranges) =
3686 lookup_svn_merge( $uuid, $url, $merge );
3687 unless (!$tip_commit or
3688 grep { $_ eq $tip_commit } @$parents ) {
3689 push @merge_tips, $tip_commit;
3690 $ranges{$tip_commit} = \@ranges;
3692 push @merge_tips, undef;
3696 my %excluded = map { $_ => 1 }
3697 parents_exclude($parents, grep { defined } @merge_tips);
3699 # check merge tips for new parents
3701 for my $merge_tip ( @merge_tips ) {
3702 my $spec = shift @merges;
3703 next unless $merge_tip and $excluded{$merge_tip};
3705 my $ranges = $ranges{$merge_tip};
3707 # check out 'new' tips
3710 $merge_base = command_oneline(
3712 @$parents, $merge_tip,
3716 die "An error occurred during merge-base"
3717 unless $@->isa("Git::Error::Command");
3719 warn "W: Cannot find common ancestor between ".
3720 "@$parents and $merge_tip. Ignoring merge info.\n";
3724 # double check that there are no missing non-merge commits
3725 my (@incomplete) = check_cherry_pick(
3726 $merge_base, $merge_tip,
3731 if ( @incomplete ) {
3732 warn "W:svn cherry-pick ignored ($spec) - missing "
3733 .@incomplete." commit(s) (eg $incomplete[0])\n";
3736 "Found merge parent (svn:mergeinfo prop): ",
3738 push @new_parents, $merge_tip;
3742 # cater for merges which merge commits from multiple branches
3743 if ( @new_parents > 1 ) {
3744 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3745 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3747 next unless $new_parents[$i];
3748 next unless $new_parents[$j];
3749 my $revs = command_oneline(
3751 "$new_parents[$i]..$new_parents[$j]",
3754 undef($new_parents[$j]);
3759 push @$parents, grep { defined } @new_parents;
3762 sub make_log_entry {
3763 my ($self, $rev, $parents, $ed) = @_;
3764 my $untracked = $self->get_untracked($ed);
3766 my @parents = @$parents;
3767 my $ps = $ed->{path_strip} || "";
3768 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3769 my $props = $ed->{dir_prop}{$path};
3770 if ( $props->{"svk:merge"} ) {
3771 $self->find_extra_svk_parents
3772 ($ed, $props->{"svk:merge"}, \@parents);
3774 if ( $props->{"svn:mergeinfo"} ) {
3775 $self->find_extra_svn_parents
3777 $props->{"svn:mergeinfo"},
3782 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3783 print $un "r$rev\n" or croak $!;
3784 print $un $_, "\n" foreach @$untracked;
3785 my %log_entry = ( parents => \@parents, revision => $rev,
3789 my $logged = delete $self->{logged_rev_props};
3790 if (!$logged || $self->{-want_revprops}) {
3791 my $rp = $self->ra->rev_proplist($rev);
3792 foreach (sort keys %$rp) {
3794 if (/^svn:(author|date|log)$/) {
3795 $log_entry{$1} = $v;
3796 } elsif ($_ eq 'svm:headrev') {
3799 print $un " rev_prop: ", uri_encode($_), ' ',
3800 uri_encode($v), "\n";
3804 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3806 close $un or croak $!;
3808 $log_entry{date} = parse_svn_date($log_entry{date});
3809 $log_entry{log} .= "\n";
3810 my $author = $log_entry{author} = check_author($log_entry{author});
3811 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3814 my ($commit_name, $commit_email) = ($name, $email);
3815 if ($_use_log_author) {
3817 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3819 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3822 if (!defined $name_field) {
3823 if (!defined $email) {
3826 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3827 ($name, $email) = ($1, $2);
3828 } elsif ($name_field =~ /(.*)@/) {
3829 ($name, $email) = ($1, $name_field);
3831 ($name, $email) = ($name_field, $name_field);
3834 if (defined $headrev && $self->use_svm_props) {
3835 if ($self->rewrite_root) {
3836 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3839 if ($self->rewrite_uuid) {
3840 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3843 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3844 # we don't want "SVM: initializing mirror for junk" ...
3845 return undef if $r == 0;
3846 my $svm = $self->svm;
3847 if ($uuid ne $svm->{uuid}) {
3848 die "UUID mismatch on SVM path:\n",
3849 "expected: $svm->{uuid}\n",
3852 my $full_url = $self->full_url;
3853 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3854 die "Failed to replace '$svm->{replace}' with ",
3855 "'$svm->{source}' in $full_url\n";
3856 # throw away username for storing in records
3857 remove_username($full_url);
3858 $log_entry{metadata} = "$full_url\@$r $uuid";
3859 $log_entry{svm_revision} = $r;
3860 $email ||= "$author\@$uuid";
3861 $commit_email ||= "$author\@$uuid";
3862 } elsif ($self->use_svnsync_props) {
3863 my $full_url = $self->svnsync->{url};
3864 $full_url .= "/$self->{path}" if length $self->{path};
3865 remove_username($full_url);
3866 my $uuid = $self->svnsync->{uuid};
3867 $log_entry{metadata} = "$full_url\@$rev $uuid";
3868 $email ||= "$author\@$uuid";
3869 $commit_email ||= "$author\@$uuid";
3871 my $url = $self->metadata_url;
3872 remove_username($url);
3873 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3874 $log_entry{metadata} = "$url\@$rev " . $uuid;
3875 $email ||= "$author\@" . $uuid;
3876 $commit_email ||= "$author\@" . $uuid;
3878 $log_entry{name} = $name;
3879 $log_entry{email} = $email;
3880 $log_entry{commit_name} = $commit_name;
3881 $log_entry{commit_email} = $commit_email;
3886 my ($self, $min_rev, $max_rev, @parents) = @_;
3887 my ($last_rev, $last_commit) = $self->last_rev_commit;
3888 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3889 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3893 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3894 $self->{inject_parents} = { $rev => $tree };
3895 $self->fetch(undef, undef);
3899 my ($self, $tree) = (shift, shift);
3900 my $log_entry = ::get_commit_entry($tree);
3901 unless ($self->{last_rev}) {
3902 ::fatal("Must have an existing revision to commit");
3904 my %ed_opts = ( r => $self->{last_rev},
3905 log => $log_entry->{log},
3907 tree_a => $self->{last_commit},
3910 $self->set_tree_cb($log_entry, $tree, @_) },
3911 svn_path => $self->{path} );
3912 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3913 print "No changes\nr$self->{last_rev} = $tree\n";
3917 sub rebuild_from_rev_db {
3918 my ($self, $path) = @_;
3920 open my $fh, '<', $path or croak "open: $!";
3921 binmode $fh or croak "binmode: $!";
3923 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3926 next if $_ eq ('0' x 40);
3927 $self->rev_map_set($r, $_);
3930 close $fh or croak "close: $!";
3931 unlink $path or croak "unlink: $!";
3936 my $map_path = $self->map_path;
3937 my $partial = (-e $map_path && ! -z $map_path);
3938 return unless ::verify_ref($self->refname.'^0');
3939 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3940 my $rev_db = $self->rev_db_path;
3941 $self->rebuild_from_rev_db($rev_db);
3942 if ($self->use_svm_props) {
3943 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3944 $self->rebuild_from_rev_db($svm_rev_db);
3946 $self->unlink_rev_db_symlink;
3949 print "Rebuilding $map_path ...\n" if (!$partial);
3950 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3953 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
3954 ($head ? "$head.." : "") . $self->refname,
3956 my $metadata_url = $self->metadata_url;
3957 remove_username($metadata_url);
3958 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3961 if ( m{^commit ($::sha1)$} ) {
3965 next unless s{^\s*(git-svn-id:)}{$1};
3966 my ($url, $rev, $uuid) = ::extract_metadata($_);
3967 remove_username($url);
3969 # ignore merges (from set-tree)
3970 next if (!defined $rev || !$uuid);
3972 # if we merged or otherwise started elsewhere, this is
3973 # how we break out of it
3974 if (($uuid ne $svn_uuid) ||
3975 ($metadata_url && $url && ($url ne $metadata_url))) {
3978 if ($partial && $head) {
3979 print "Partial-rebuilding $map_path ...\n";
3980 print "Currently at $base_rev = $head\n";
3984 $self->rev_map_set($rev, $c);
3985 print "r$rev = $c\n";
3987 command_close_pipe($log, $ctx);
3988 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3989 my $rev_db_path = $self->rev_db_path;
3990 if (-f $self->rev_db_path) {
3991 unlink $self->rev_db_path or croak "unlink: $!";
3993 $self->unlink_rev_db_symlink;
3997 # Tie::File seems to be prone to offset errors if revisions get sparse,
3998 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3999 # one of my favorite modules is out :< Next up would be one of the DBM
4000 # modules, but I'm not sure which is most portable...
4002 # This is the replacement for the rev_db format, which was too big
4003 # and inefficient for large repositories with a lot of sparse history
4006 # The format is this:
4007 # - 24 bytes for every record,
4008 # * 4 bytes for the integer representing an SVN revision number
4009 # * 20 bytes representing the sha1 of a git commit
4010 # - No empty padding records like the old format
4011 # (except the last record, which can be overwritten)
4012 # - new records are written append-only since SVN revision numbers
4013 # increase monotonically
4014 # - lookups on SVN revision number are done via a binary search
4015 # - Piping the file to xxd -c24 is a good way of dumping it for
4016 # viewing or editing (piped back through xxd -r), should the need
4018 # - The last record can be padding revision with an all-zero sha1
4019 # This is used to optimize fetch performance when using multiple
4020 # "fetch" directives in .git/config
4022 # These files are disposable unless noMetadata or useSvmProps is set
4025 my ($fh, $rev, $commit) = @_;
4027 binmode $fh or croak "binmode: $!";
4028 my $size = (stat($fh))[7];
4029 ($size % 24) == 0 or croak "inconsistent size: $size";
4033 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4034 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4035 $read == 24 or croak "read only $read bytes (!= 24)";
4036 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4037 if ($last_commit eq ('0' x40)) {
4039 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4040 $read = sysread($fh, $buf, 24) or
4043 croak "read only $read bytes (!= 24)";
4044 ($last_rev, $last_commit) =
4045 unpack(rev_map_fmt, $buf);
4046 if ($last_commit eq ('0' x40)) {
4047 croak "inconsistent .rev_map\n";
4050 if ($last_rev >= $rev) {
4051 croak "last_rev is higher!: $last_rev >= $rev";
4056 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4057 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4061 sub _rev_map_reset {
4062 my ($fh, $rev, $commit) = @_;
4063 my $c = _rev_map_get($fh, $rev);
4064 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4065 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4066 truncate $fh, $offset or croak "truncate: $!";
4072 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4073 mkpath([$dir]) unless -d $dir;
4074 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4075 close $fh or die "Couldn't close (create) $path: $!\n";
4080 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4081 defined $commit or die "missing arg3\n";
4082 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4083 my $db = $self->map_path($uuid);
4084 my $db_lock = "$db.lock";
4088 $sigmask = POSIX::SigSet->new();
4089 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
4090 SIGALRM, SIGUSR1, SIGUSR2);
4091 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4092 croak "Can't block signals: $!";
4096 $LOCKFILES{$db_lock} = 1;
4098 # both of these options make our .rev_db file very, very important
4099 # and we can't afford to lose it because rebuild() won't work
4100 if ($self->use_svm_props || $self->no_metadata) {
4102 copy($db, $db_lock) or die "rev_map_set(@_): ",
4104 "$db => $db_lock ($!)\n";
4106 rename $db, $db_lock or die "rev_map_set(@_): ",
4107 "Failed to rename: ",
4108 "$db => $db_lock ($!)\n";
4111 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4112 or croak "Couldn't open $db_lock: $!\n";
4113 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4114 _rev_map_set($fh, $rev, $commit);
4116 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4117 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4119 close $fh or croak $!;
4123 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4124 command_noisy('update-ref', '-m', "r$rev$note",
4125 $self->refname, $commit);
4127 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4128 "$db_lock => $db ($!)\n";
4129 delete $LOCKFILES{$db_lock};
4131 sigprocmask(SIG_SETMASK, $sigmask) or
4132 croak "Can't restore signal mask: $!";
4136 # If want_commit, this will return an array of (rev, commit) where
4137 # commit _must_ be a valid commit in the archive.
4138 # Otherwise, it'll return the max revision (whether or not the
4139 # commit is valid or just a 0x40 placeholder).
4141 my ($self, $want_commit) = @_;
4143 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4144 $want_commit ? ($r, $c) : $r;
4147 sub rev_map_max_norebuild {
4148 my ($self, $want_commit) = @_;
4149 my $map_path = $self->map_path;
4150 stat $map_path or return $want_commit ? (0, undef) : 0;
4151 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4152 binmode $fh or croak "binmode: $!";
4153 my $size = (stat($fh))[7];
4154 ($size % 24) == 0 or croak "inconsistent size: $size";
4157 close $fh or croak "close: $!";
4158 return $want_commit ? (0, undef) : 0;
4161 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4162 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4163 my ($r, $c) = unpack(rev_map_fmt, $buf);
4164 if ($want_commit && $c eq ('0' x40)) {
4166 return $want_commit ? (0, undef) : 0;
4168 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4169 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4170 ($r, $c) = unpack(rev_map_fmt, $buf);
4171 if ($c eq ('0'x40)) {
4172 croak "Penultimate record is all-zeroes in $map_path";
4175 close $fh or croak "close: $!";
4176 $want_commit ? ($r, $c) : $r;
4180 my ($self, $rev, $uuid) = @_;
4181 my $map_path = $self->map_path($uuid);
4182 return undef unless -e $map_path;
4184 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4185 my $c = _rev_map_get($fh, $rev);
4186 close($fh) or croak "close: $!";
4191 my ($fh, $rev) = @_;
4193 binmode $fh or croak "binmode: $!";
4194 my $size = (stat($fh))[7];
4195 ($size % 24) == 0 or croak "inconsistent size: $size";
4201 my ($l, $u) = (0, $size - 24);
4205 my $i = int(($l/24 + $u/24) / 2) * 24;
4206 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4207 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4208 my ($r, $c) = unpack(rev_map_fmt, $buf);
4212 } elsif ($r > $rev) {
4214 } else { # $r == $rev
4215 return $c eq ('0' x 40) ? undef : $c;
4221 # Finds the first svn revision that exists on (if $eq_ok is true) or
4222 # before $rev for the current branch. It will not search any lower
4223 # than $min_rev. Returns the git commit hash and svn revision number
4224 # if found, else (undef, undef).
4225 sub find_rev_before {
4226 my ($self, $rev, $eq_ok, $min_rev) = @_;
4227 --$rev unless $eq_ok;
4229 my $max_rev = $self->rev_map_max;
4230 $rev = $max_rev if ($rev > $max_rev);
4231 while ($rev >= $min_rev) {
4232 if (my $c = $self->rev_map_get($rev)) {
4237 return (undef, undef);
4240 # Finds the first svn revision that exists on (if $eq_ok is true) or
4241 # after $rev for the current branch. It will not search any higher
4242 # than $max_rev. Returns the git commit hash and svn revision number
4243 # if found, else (undef, undef).
4244 sub find_rev_after {
4245 my ($self, $rev, $eq_ok, $max_rev) = @_;
4246 ++$rev unless $eq_ok;
4247 $max_rev ||= $self->rev_map_max;
4248 while ($rev <= $max_rev) {
4249 if (my $c = $self->rev_map_get($rev)) {
4254 return (undef, undef);
4258 my ($class, $repo_id, $ref_id, $path) = @_;
4259 unless (defined $repo_id && length $repo_id) {
4260 $repo_id = $Git::SVN::default_repo_id;
4262 unless (defined $ref_id && length $ref_id) {
4263 $_prefix = '' unless defined($_prefix);
4265 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4268 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4270 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4271 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4272 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4273 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4274 if (-d $old_dir && ! -d $dir) {
4279 $_[3] = $path = '' unless (defined $path);
4282 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4283 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4284 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4287 # for read-only access of old .rev_db formats
4288 sub unlink_rev_db_symlink {
4290 my $link = $self->rev_db_path;
4291 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4293 unlink $link or croak "unlink: $link failed!";
4298 my ($self, $uuid) = @_;
4299 my $db_path = $self->map_path($uuid);
4300 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4301 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4305 # the new replacement for .rev_db
4307 my ($self, $uuid) = @_;
4308 $uuid ||= $self->ra_uuid;
4309 "$self->{map_root}.$uuid";
4314 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4320 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4324 sub remove_username {
4325 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4328 package Git::SVN::Prompt;
4332 use vars qw/$_no_auth_cache $_username/;
4335 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4336 $may_save = undef if $_no_auth_cache;
4337 $default_username = $_username if defined $_username;
4338 if (defined $default_username && length $default_username) {
4339 if (defined $realm && length $realm) {
4340 print STDERR "Authentication realm: $realm\n";
4343 $cred->username($default_username);
4345 username($cred, $realm, $may_save, $pool);
4347 $cred->password(_read_password("Password for '" .
4348 $cred->username . "': ", $realm));
4349 $cred->may_save($may_save);
4350 $SVN::_Core::SVN_NO_ERROR;
4353 sub ssl_server_trust {
4354 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4355 $may_save = undef if $_no_auth_cache;
4356 print STDERR "Error validating server certificate for '$realm':\n";
4359 # All variables SVN::Auth::SSL::* are used only once,
4360 # so we're shutting up Perl warnings about this.
4361 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4362 print STDERR " - The certificate is not issued ",
4363 "by a trusted authority. Use the\n",
4364 " fingerprint to validate ",
4365 "the certificate manually!\n";
4367 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4368 print STDERR " - The certificate hostname ",
4369 "does not match.\n";
4371 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4372 print STDERR " - The certificate is not yet valid.\n";
4374 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4375 print STDERR " - The certificate has expired.\n";
4377 if ($failures & $SVN::Auth::SSL::OTHER) {
4378 print STDERR " - The certificate has ",
4379 "an unknown error.\n";
4381 } # no warnings 'once'
4383 "Certificate information:\n".
4384 " - Hostname: %s\n".
4385 " - Valid: from %s until %s\n".
4387 " - Fingerprint: %s\n",
4388 map $cert_info->$_, qw(hostname valid_from valid_until
4389 issuer_dname fingerprint);
4392 print STDERR $may_save ?
4393 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4394 "(R)eject or accept (t)emporarily? ";
4396 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4397 if ($choice =~ /^t$/i) {
4398 $cred->may_save(undef);
4399 } elsif ($choice =~ /^r$/i) {
4401 } elsif ($may_save && $choice =~ /^p$/i) {
4402 $cred->may_save($may_save);
4406 $cred->accepted_failures($failures);
4407 $SVN::_Core::SVN_NO_ERROR;
4410 sub ssl_client_cert {
4411 my ($cred, $realm, $may_save, $pool) = @_;
4412 $may_save = undef if $_no_auth_cache;
4413 print STDERR "Client certificate filename: ";
4415 chomp(my $filename = <STDIN>);
4416 $cred->cert_file($filename);
4417 $cred->may_save($may_save);
4418 $SVN::_Core::SVN_NO_ERROR;
4421 sub ssl_client_cert_pw {
4422 my ($cred, $realm, $may_save, $pool) = @_;
4423 $may_save = undef if $_no_auth_cache;
4424 $cred->password(_read_password("Password: ", $realm));
4425 $cred->may_save($may_save);
4426 $SVN::_Core::SVN_NO_ERROR;
4430 my ($cred, $realm, $may_save, $pool) = @_;
4431 $may_save = undef if $_no_auth_cache;
4432 if (defined $realm && length $realm) {
4433 print STDERR "Authentication realm: $realm\n";
4436 if (defined $_username) {
4437 $username = $_username;
4439 print STDERR "Username: ";
4441 chomp($username = <STDIN>);
4443 $cred->username($username);
4444 $cred->may_save($may_save);
4445 $SVN::_Core::SVN_NO_ERROR;
4448 sub _read_password {
4449 my ($prompt, $realm) = @_;
4451 if (exists $ENV{GIT_ASKPASS}) {
4452 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4454 $password =~ s/[\012\015]//; # \n\r
4457 print STDERR $prompt;
4459 require Term::ReadKey;
4460 Term::ReadKey::ReadMode('noecho');
4461 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4462 last if $key =~ /[\012\015]/; # \n\r
4465 Term::ReadKey::ReadMode('restore');
4472 package SVN::Git::Fetcher;
4473 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4474 @deleted_gpath %added_placeholder $repo_id/;
4478 use File::Basename qw/dirname/;
4481 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4483 my ($class, $git_svn, $switch_path) = @_;
4484 my $self = SVN::Delta::Editor->new;
4485 bless $self, $class;
4486 if (exists $git_svn->{last_commit}) {
4487 $self->{c} = $git_svn->{last_commit};
4488 $self->{empty_symlinks} =
4489 _mark_empty_symlinks($git_svn, $switch_path);
4492 # some options are read globally, but can be overridden locally
4493 # per [svn-remote "..."] section. Command-line options will *NOT*
4494 # override options set in an [svn-remote "..."] section
4495 $repo_id = $git_svn->{repo_id};
4496 my $k = "svn-remote.$repo_id.ignore-paths";
4497 my $v = eval { command_oneline('config', '--get', $k) };
4498 $self->{ignore_regex} = $v;
4500 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4501 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4502 if ($v && $v eq 'true') {
4503 $_preserve_empty_dirs = 1;
4504 $k = "svn-remote.$repo_id.placeholder-filename";
4505 $v = eval { command_oneline('config', '--get', $k) };
4506 $_placeholder_filename = $v;
4509 # Load the list of placeholder files added during previous invocations.
4510 $k = "svn-remote.$repo_id.added-placeholder";
4511 $v = eval { command_oneline('config', '--get-all', $k) };
4512 if ($_preserve_empty_dirs && $v) {
4513 # command() prints errors to stderr, so we only call it if
4514 # command_oneline() succeeded.
4515 my @v = command('config', '--get-all', $k);
4516 $added_placeholder{ dirname($_) } = $_ foreach @v;
4519 $self->{empty} = {};
4520 $self->{dir_prop} = {};
4521 $self->{file_prop} = {};
4522 $self->{absent_dir} = {};
4523 $self->{absent_file} = {};
4524 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4525 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4529 # this uses the Ra object, so it must be called before do_{switch,update},
4530 # not inside them (when the Git::SVN::Fetcher object is passed) to
4531 # do_{switch,update}
4532 sub _mark_empty_symlinks {
4533 my ($git_svn, $switch_path) = @_;
4534 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4535 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4538 my ($rev, $cmt) = $git_svn->last_rev_commit;
4539 return {} unless ($rev && $cmt);
4541 # allow the warning to be printed for each revision we fetch to
4542 # ensure the user sees it. The user can also disable the workaround
4543 # on the repository even while git svn is running and the next
4544 # revision fetched will skip this expensive function.
4545 my $printed_warning;
4546 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4547 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4549 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4550 $pfx .= '/' if length($pfx);
4553 s/\A100644 blob $empty_blob\t//o or next;
4554 unless ($printed_warning) {
4555 print STDERR "Scanning for empty symlinks, ",
4556 "this may take a while if you have ",
4557 "many empty files\n",
4558 "You may disable this with `",
4559 "git config svn.brokenSymlinkWorkaround ",
4561 "This may be done in a different ",
4562 "terminal without restarting ",
4564 $printed_warning = 1;
4567 my (undef, $props) =
4568 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4569 if ($props->{'svn:special'}) {
4573 command_close_pipe($ls, $ctx);
4577 # returns true if a given path is inside a ".git" directory
4579 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4582 # return value: 0 -- don't ignore, 1 -- ignore
4583 sub is_path_ignored {
4584 my ($self, $path) = @_;
4585 return 1 if in_dot_git($path);
4586 return 1 if defined($self->{ignore_regex}) &&
4587 $path =~ m!$self->{ignore_regex}!;
4588 return 0 unless defined($_ignore_regex);
4589 return 1 if $path =~ m!$_ignore_regex!o;
4593 sub set_path_strip {
4594 my ($self, $path) = @_;
4595 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4602 sub open_directory {
4603 my ($self, $path, $pb, $rev) = @_;
4608 my ($self, $path) = @_;
4609 if (my $enc = $self->{pathnameencoding}) {
4611 Encode::from_to($path, 'UTF-8', $enc);
4613 if ($self->{path_strip}) {
4614 $path =~ s!$self->{path_strip}!! or
4615 die "Failed to strip path '$path' ($self->{path_strip})\n";
4621 my ($self, $path, $rev, $pb) = @_;
4622 return undef if $self->is_path_ignored($path);
4624 my $gpath = $self->git_path($path);
4625 return undef if ($gpath eq '');
4627 # remove entire directories.
4628 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4629 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4631 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4637 my $rmpath = "$gpath/$_";
4638 $self->{gii}->remove($rmpath);
4639 print "\tD\t$rmpath\n" unless $::_q;
4641 print "\tD\t$gpath/\n" unless $::_q;
4642 command_close_pipe($ls, $ctx);
4644 $self->{gii}->remove($gpath);
4645 print "\tD\t$gpath\n" unless $::_q;
4647 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4648 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4649 $self->{empty}->{$path} = 0;
4654 my ($self, $path, $pb, $rev) = @_;
4657 goto out if $self->is_path_ignored($path);
4659 my $gpath = $self->git_path($path);
4660 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4661 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4662 unless (defined $mode && defined $blob) {
4663 die "$path was not found in commit $self->{c} (r$rev)\n";
4665 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4669 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4670 pool => SVN::Pool->new, action => 'M' };
4674 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4677 if (!$self->is_path_ignored($path)) {
4678 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4679 delete $self->{empty}->{$dir};
4682 if ($added_placeholder{$dir}) {
4683 # Remove our placeholder file, if we created one.
4684 delete_entry($self, $added_placeholder{$dir})
4685 unless $path eq $added_placeholder{$dir};
4686 delete $added_placeholder{$dir}
4690 { path => $path, mode_a => $mode, mode_b => $mode,
4691 pool => SVN::Pool->new, action => 'A' };
4695 my ($self, $path, $cp_path, $cp_rev) = @_;
4696 goto out if $self->is_path_ignored($path);
4697 my $gpath = $self->git_path($path);
4699 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4705 $self->{gii}->remove($_);
4706 print "\tD\t$_\n" unless $::_q;
4707 push @deleted_gpath, $gpath;
4709 command_close_pipe($ls, $ctx);
4710 $self->{empty}->{$path} = 0;
4712 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4713 delete $self->{empty}->{$dir};
4714 $self->{empty}->{$path} = 1;
4716 if ($added_placeholder{$dir}) {
4717 # Remove our placeholder file, if we created one.
4718 delete_entry($self, $added_placeholder{$dir});
4719 delete $added_placeholder{$dir}
4726 sub change_dir_prop {
4727 my ($self, $db, $prop, $value) = @_;
4728 return undef if $self->is_path_ignored($db->{path});
4729 $self->{dir_prop}->{$db->{path}} ||= {};
4730 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4734 sub absent_directory {
4735 my ($self, $path, $pb) = @_;
4736 return undef if $self->is_path_ignored($path);
4737 $self->{absent_dir}->{$pb->{path}} ||= [];
4738 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4743 my ($self, $path, $pb) = @_;
4744 return undef if $self->is_path_ignored($path);
4745 $self->{absent_file}->{$pb->{path}} ||= [];
4746 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4750 sub change_file_prop {
4751 my ($self, $fb, $prop, $value) = @_;
4752 return undef if $self->is_path_ignored($fb->{path});
4753 if ($prop eq 'svn:executable') {
4754 if ($fb->{mode_b} != 120000) {
4755 $fb->{mode_b} = defined $value ? 100755 : 100644;
4757 } elsif ($prop eq 'svn:special') {
4758 $fb->{mode_b} = defined $value ? 120000 : 100644;
4760 $self->{file_prop}->{$fb->{path}} ||= {};
4761 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4766 sub apply_textdelta {
4767 my ($self, $fb, $exp) = @_;
4768 return undef if $self->is_path_ignored($fb->{path});
4769 my $fh = $::_repository->temp_acquire('svn_delta');
4770 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4771 # (but $base does not,) so dup() it for reading in close_file
4772 open my $dup, '<&', $fh or croak $!;
4773 my $base = $::_repository->temp_acquire('git_blob');
4776 my ($base_is_link, $size);
4778 if ($fb->{mode_a} eq '120000' &&
4779 ! $self->{empty_symlinks}->{$fb->{path}}) {
4780 print $base 'link ' or die "print $!\n";
4784 $size = $::_repository->cat_blob($fb->{blob}, $base);
4785 die "Failed to read object $fb->{blob}" if ($size < 0);
4788 seek $base, 0, 0 or croak $!;
4789 my $got = ::md5sum($base);
4791 my $err = "Checksum mismatch: ".
4792 "$fb->{path} $fb->{blob}\n" .
4793 "expected: $exp\n" .
4795 if ($base_is_link) {
4797 "Retrying... (possibly ",
4798 "a bad symlink from SVN)\n";
4799 $::_repository->temp_reset($base);
4807 seek $base, 0, 0 or croak $!;
4809 $fb->{base} = $base;
4810 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4814 my ($self, $fb, $exp) = @_;
4815 return undef if $self->is_path_ignored($fb->{path});
4818 my $path = $self->git_path($fb->{path});
4819 if (my $fh = $fb->{fh}) {
4821 seek($fh, 0, 0) or croak $!;
4822 my $got = ::md5sum($fh);
4824 die "Checksum mismatch: $path\n",
4825 "expected: $exp\n got: $got\n";
4828 if ($fb->{mode_b} == 120000) {
4829 sysseek($fh, 0, 0) or croak $!;
4830 my $rd = sysread($fh, my $buf, 5);
4833 croak "sysread: $!\n";
4834 } elsif ($rd == 0) {
4835 warn "$path has mode 120000",
4836 " but it points to nothing\n",
4837 "converting to an empty file with mode",
4839 $fb->{mode_b} = '100644';
4840 } elsif ($buf ne 'link ') {
4841 warn "$path has mode 120000",
4842 " but is not a link\n";
4844 my $tmp_fh = $::_repository->temp_acquire(
4847 while ($res = sysread($fh, my $str, 1024)) {
4848 my $out = syswrite($tmp_fh, $str, $res);
4849 defined($out) && $out == $res
4851 Git::temp_path($tmp_fh),
4854 defined $res or croak $!;
4856 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4857 Git::temp_release($tmp_fh, 1);
4861 $hash = $::_repository->hash_and_insert_object(
4862 Git::temp_path($fh));
4863 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4865 Git::temp_release($fb->{base}, 1);
4866 Git::temp_release($fh, 1);
4868 $hash = $fb->{blob} or die "no blob information\n";
4871 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4872 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4878 $self->{nr} = $self->{gii}->{nr};
4879 delete $self->{gii};
4880 $self->SUPER::abort_edit(@_);
4886 if ($_preserve_empty_dirs) {
4889 # Any entry flagged as empty that also has an associated
4890 # dir_prop represents a newly created empty directory.
4891 foreach my $i (keys %{$self->{empty}}) {
4892 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4895 # Search for directories that have become empty due subsequent
4897 push @empty_dirs, $self->find_empty_directories();
4899 # Finally, add a placeholder file to each empty directory.
4900 $self->add_placeholder_file($_) foreach (@empty_dirs);
4902 $self->stash_placeholder_list();
4905 $self->{git_commit_ok} = 1;
4906 $self->{nr} = $self->{gii}->{nr};
4907 delete $self->{gii};
4908 $self->SUPER::close_edit(@_);
4911 sub find_empty_directories {
4914 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4916 foreach my $dir (sort keys %dirs) {
4917 next if $dir eq ".";
4919 # If there have been any additions to this directory, there is
4920 # no reason to check if it is empty.
4922 foreach my $t (qw/dir_prop file_prop/) {
4923 foreach my $path (keys %{ $self->{$t} }) {
4924 if (exists $self->{$t}->{dirname($path)}) {
4929 last if $skip_added;
4931 next if $skip_added;
4933 # Use `git ls-tree` to get the filenames of this directory
4934 # that existed prior to this particular commit.
4935 my $ls = command('ls-tree', '-z', '--name-only',
4936 $self->{c}, "$dir/");
4937 my %files = map { $_ => 1 } split(/\0/, $ls);
4939 # Remove the filenames that were deleted during this commit.
4940 delete $files{$_} foreach (@deleted_gpath);
4942 # Report the directory if there are no filenames left.
4943 push @empty_dirs, $dir unless (scalar %files);
4948 sub add_placeholder_file {
4949 my ($self, $dir) = @_;
4950 my $path = "$dir/$_placeholder_filename";
4951 my $gpath = $self->git_path($path);
4953 my $fh = $::_repository->temp_acquire($gpath);
4954 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4955 Git::temp_release($fh, 1);
4956 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4958 # The directory should no longer be considered empty.
4959 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4961 # Keep track of any placeholder files we create.
4962 $added_placeholder{$dir} = $path;
4965 sub stash_placeholder_list {
4967 my $k = "svn-remote.$repo_id.added-placeholder";
4968 my $v = eval { command_oneline('config', '--get-all', $k) };
4969 command_noisy('config', '--unset-all', $k) if $v;
4970 foreach (values %added_placeholder) {
4971 command_noisy('config', '--add', $k, $_);
4975 package SVN::Git::Editor;
4976 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4983 my ($class, $opts) = @_;
4984 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4985 die "$_ required!\n" unless (defined $opts->{$_});
4988 my $pool = SVN::Pool->new;
4989 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4990 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4993 # $opts->{ra} functions should not be used after this:
4994 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4995 $opts->{editor_cb}, $pool);
4996 my $self = SVN::Delta::Editor->new(@ce, $pool);
4997 bless $self, $class;
4998 foreach (qw/svn_path r tree_a tree_b/) {
4999 $self->{$_} = $opts->{$_};
5001 $self->{url} = $opts->{ra}->{url};
5002 $self->{mods} = $mods;
5003 $self->{types} = $types;
5004 $self->{pool} = $pool;
5005 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
5007 $self->{path_prefix} = length $self->{svn_path} ?
5008 "$self->{svn_path}/" : '';
5009 $self->{config} = $opts->{config};
5010 $self->{mergeinfo} = $opts->{mergeinfo};
5015 my ($tree_a, $tree_b) = @_;
5016 my @diff_tree = qw(diff-tree -z -r);
5017 if ($_cp_similarity) {
5018 push @diff_tree, "-C$_cp_similarity";
5020 push @diff_tree, '-C';
5022 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
5023 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
5024 push @diff_tree, $tree_a, $tree_b;
5025 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
5029 while (<$diff_fh>) {
5030 chomp $_; # this gets rid of the trailing "\0"
5031 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
5032 ($::sha1)\s($::sha1)\s
5033 ([MTCRAD])\d*$/xo) {
5034 push @mods, { mode_a => $1, mode_b => $2,
5035 sha1_a => $3, sha1_b => $4,
5037 if ($5 =~ /^(?:C|R)$/) {
5042 } elsif ($state eq 'file_a') {
5043 my $x = $mods[$#mods] or croak "Empty array\n";
5044 if ($x->{chg} !~ /^(?:C|R)$/) {
5045 croak "Error parsing $_, $x->{chg}\n";
5049 } elsif ($state eq 'file_b') {
5050 my $x = $mods[$#mods] or croak "Empty array\n";
5051 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
5052 croak "Error parsing $_, $x->{chg}\n";
5054 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
5055 croak "Error parsing $_, $x->{chg}\n";
5060 croak "Error parsing $_\n";
5063 command_close_pipe($diff_fh, $ctx);
5067 sub check_diff_paths {
5068 my ($ra, $pfx, $rev, $mods) = @_;
5070 $pfx .= '/' if length $pfx;
5072 sub type_diff_paths {
5073 my ($ra, $types, $path, $rev) = @_;
5074 my @p = split m#/+#, $path;
5076 unless (defined $types->{$c}) {
5077 $types->{$c} = $ra->check_path($c, $rev);
5080 $c .= '/' . shift @p;
5081 next if defined $types->{$c};
5082 $types->{$c} = $ra->check_path($c, $rev);
5086 foreach my $m (@$mods) {
5087 foreach my $f (qw/file_a file_b/) {
5088 next unless defined $m->{$f};
5089 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
5090 if (length $pfx.$dir && ! defined $types{$dir}) {
5091 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
5099 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
5103 my ($self, $path) = @_;
5104 if (my $enc = $self->{pathnameencoding}) {
5106 Encode::from_to($path, $enc, 'UTF-8');
5108 $self->{path_prefix}.(defined $path ? $path : '');
5112 my ($self, $path) = @_;
5113 if ($self->{url} =~ m#^https?://#) {
5114 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
5116 $self->{url} . '/' . $self->repo_path($path);
5121 my $rm = $self->{rm};
5122 delete $rm->{''}; # we never delete the url we're tracking
5125 foreach (keys %$rm) {
5126 my @d = split m#/#, $_;
5130 $c .= '/' . shift @d;
5134 delete $rm->{$self->{svn_path}};
5135 delete $rm->{''}; # we never delete the url we're tracking
5138 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5143 my @dn = split m#/#, $_;
5145 delete $rm->{join '/', @dn};
5152 command_close_pipe($fh, $ctx);
5154 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5155 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5156 $self->close_directory($bat->{$d}, $p);
5157 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5158 print "\tD+\t$d/\n" unless $::_q;
5159 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5164 sub open_or_add_dir {
5165 my ($self, $full_path, $baton, $deletions) = @_;
5166 my $t = $self->{types}->{$full_path};
5168 die "$full_path not known in r$self->{r} or we have a bug!\n";
5172 # SVN::Node::none and SVN::Node::file are used only once,
5173 # so we're shutting up Perl's warnings about them.
5174 if ($t == $SVN::Node::none || defined($deletions->{$full_path})) {
5175 return $self->add_directory($full_path, $baton,
5176 undef, -1, $self->{pool});
5177 } elsif ($t == $SVN::Node::dir) {
5178 return $self->open_directory($full_path, $baton,
5179 $self->{r}, $self->{pool});
5180 } # no warnings 'once'
5181 print STDERR "$full_path already exists in repository at ",
5182 "r$self->{r} and it is not a directory (",
5183 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5184 } # no warnings 'once'
5189 my ($self, $path, $deletions) = @_;
5190 my $bat = $self->{bat};
5191 my $repo_path = $self->repo_path($path);
5192 return $bat->{''} unless (length $repo_path);
5194 my @p = split m#/+#, $repo_path;
5196 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''}, $deletions);
5199 $c .= '/' . shift @p;
5200 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0}, $deletions);
5205 # Subroutine to convert a globbing pattern to a regular expression.
5206 # From perl cookbook.
5208 my $globstr = shift;
5209 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5210 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5211 return '^' . $globstr . '$';
5214 sub check_autoprop {
5215 my ($self, $pattern, $properties, $file, $fbat) = @_;
5216 # Convert the globbing pattern to a regular expression.
5217 my $regex = glob2pat($pattern);
5218 # Check if the pattern matches the file name.
5219 if($file =~ m/($regex)/) {
5220 # Parse the list of properties to set.
5221 my @props = split(/;/, $properties);
5222 foreach my $prop (@props) {
5223 # Parse 'name=value' syntax and set the property.
5224 if ($prop =~ /([^=]+)=(.*)/) {
5225 my ($n,$v) = ($1,$2);
5229 $self->change_file_prop($fbat, $n, $v);
5235 sub apply_autoprops {
5236 my ($self, $file, $fbat) = @_;
5237 my $conf_t = ${$self->{config}}{'config'};
5239 # Check [miscellany]/enable-auto-props in svn configuration.
5240 if (SVN::_Core::svn_config_get_bool(
5242 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5243 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5245 # Auto-props are enabled. Enumerate them to look for matches.
5246 my $callback = sub {
5247 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5249 SVN::_Core::svn_config_enumerate(
5251 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5257 my ($self, $m, $deletions) = @_;
5258 my ($dir, $file) = split_path($m->{file_b});
5259 my $pbat = $self->ensure_path($dir, $deletions);
5260 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5262 print "\tA\t$m->{file_b}\n" unless $::_q;
5263 $self->apply_autoprops($file, $fbat);
5264 $self->chg_file($fbat, $m);
5265 $self->close_file($fbat,undef,$self->{pool});
5269 my ($self, $m, $deletions) = @_;
5270 my ($dir, $file) = split_path($m->{file_b});
5271 my $pbat = $self->ensure_path($dir, $deletions);
5272 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5273 $self->url_path($m->{file_a}), $self->{r});
5274 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5275 $self->chg_file($fbat, $m);
5276 $self->close_file($fbat,undef,$self->{pool});
5280 my ($self, $path, $pbat) = @_;
5281 my $rpath = $self->repo_path($path);
5282 my ($dir, $file) = split_path($rpath);
5283 $self->{rm}->{$dir} = 1;
5284 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5288 my ($self, $m, $deletions) = @_;
5289 my ($dir, $file) = split_path($m->{file_b});
5290 my $pbat = $self->ensure_path($dir, $deletions);
5291 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5292 $self->url_path($m->{file_a}), $self->{r});
5293 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5294 $self->apply_autoprops($file, $fbat);
5295 $self->chg_file($fbat, $m);
5296 $self->close_file($fbat,undef,$self->{pool});
5298 ($dir, $file) = split_path($m->{file_a});
5299 $pbat = $self->ensure_path($dir, $deletions);
5300 $self->delete_entry($m->{file_a}, $pbat);
5304 my ($self, $m, $deletions) = @_;
5305 my ($dir, $file) = split_path($m->{file_b});
5306 my $pbat = $self->ensure_path($dir, $deletions);
5307 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5308 $pbat,$self->{r},$self->{pool});
5309 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5310 $self->chg_file($fbat, $m);
5311 $self->close_file($fbat,undef,$self->{pool});
5314 sub T { shift->M(@_) }
5316 sub change_file_prop {
5317 my ($self, $fbat, $pname, $pval) = @_;
5318 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5321 sub change_dir_prop {
5322 my ($self, $pbat, $pname, $pval) = @_;
5323 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5326 sub _chg_file_get_blob ($$$$) {
5327 my ($self, $fbat, $m, $which) = @_;
5328 my $fh = $::_repository->temp_acquire("git_blob_$which");
5329 if ($m->{"mode_$which"} =~ /^120/) {
5330 print $fh 'link ' or croak $!;
5331 $self->change_file_prop($fbat,'svn:special','*');
5332 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5333 $self->change_file_prop($fbat,'svn:special',undef);
5335 my $blob = $m->{"sha1_$which"};
5336 return ($fh,) if ($blob =~ /^0{40}$/);
5337 my $size = $::_repository->cat_blob($blob, $fh);
5338 croak "Failed to read object $blob" if ($size < 0);
5339 $fh->flush == 0 or croak $!;
5340 seek $fh, 0, 0 or croak $!;
5342 my $exp = ::md5sum($fh);
5343 seek $fh, 0, 0 or croak $!;
5348 my ($self, $fbat, $m) = @_;
5349 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5350 $self->change_file_prop($fbat,'svn:executable','*');
5351 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5352 $self->change_file_prop($fbat,'svn:executable',undef);
5354 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5355 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5356 my $pool = SVN::Pool->new;
5357 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5359 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5360 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5362 die "Unexpected result from send_txstream: $res\n",
5363 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5366 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5367 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5368 if ($got ne $exp_b);
5370 Git::temp_release($fh_b, 1);
5371 Git::temp_release($fh_a, 1);
5376 my ($self, $m, $deletions) = @_;
5377 my ($dir, $file) = split_path($m->{file_b});
5378 my $pbat = $self->ensure_path($dir, $deletions);
5379 print "\tD\t$m->{file_b}\n" unless $::_q;
5380 $self->delete_entry($m->{file_b}, $pbat);
5385 my ($p,$bat) = ($self->{pool}, $self->{bat});
5386 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5388 $self->close_directory($bat->{$_}, $p);
5390 $self->close_directory($bat->{''}, $p);
5391 $self->SUPER::close_edit($p);
5397 $self->SUPER::abort_edit($self->{pool});
5402 $self->SUPER::DESTROY(@_);
5403 $self->{pool}->clear;
5406 # this drives the editor
5409 my $mods = $self->{mods};
5410 my %o = ( D => 0, C => 1, R => 2, A => 3, M => 4, T => 5 );
5413 foreach my $m (@$mods) {
5414 if ($m->{chg} eq "D") {
5415 $deletions{$m->{file_b}} = 1;
5419 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5421 if (defined $o{$f}) {
5422 $self->$f($m, \%deletions);
5424 fatal("Invalid change type: $f");
5428 if (defined($self->{mergeinfo})) {
5429 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5430 $self->{mergeinfo});
5432 $self->rmdirs if $_rmdir;
5433 if (@$mods == 0 && !defined($self->{mergeinfo})) {
5438 return scalar @$mods;
5441 package Git::SVN::Ra;
5442 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
5445 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5448 # enforce temporary pool usage for some simple functions
5450 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5452 my $SUPER = "SUPER::$f";
5455 my $pool = SVN::Pool->new;
5456 my @ret = $self->$SUPER(@_,$pool);
5458 wantarray ? @ret : $ret[0];
5463 sub _auth_providers () {
5465 SVN::Client::get_simple_provider(),
5466 SVN::Client::get_ssl_server_trust_file_provider(),
5467 SVN::Client::get_simple_prompt_provider(
5468 \&Git::SVN::Prompt::simple, 2),
5469 SVN::Client::get_ssl_client_cert_file_provider(),
5470 SVN::Client::get_ssl_client_cert_prompt_provider(
5471 \&Git::SVN::Prompt::ssl_client_cert, 2),
5472 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5473 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5474 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5475 SVN::Client::get_username_provider(),
5476 SVN::Client::get_ssl_server_trust_prompt_provider(
5477 \&Git::SVN::Prompt::ssl_server_trust),
5478 SVN::Client::get_username_prompt_provider(
5479 \&Git::SVN::Prompt::username, 2)
5482 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
5484 if (::compare_svn_version('1.6.12') > 0) {
5485 my $config = SVN::Core::config_get_config($config_dir);
5487 # config_get_config returns all config files from
5488 # ~/.subversion, auth_get_platform_specific_client_providers
5489 # just wants the config "file".
5490 @a = ($config->{'config'}, undef);
5491 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
5492 # Insert the return value from
5493 # auth_get_platform_specific_providers
5499 sub escape_uri_only {
5502 foreach (split m{/}, $uri) {
5503 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5511 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5512 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5513 $url = "$scheme://$domain$uri";
5519 my ($class, $url) = @_;
5521 return $RA if ($RA && $RA->{url} eq $url);
5525 SVN::_Core::svn_config_ensure($config_dir, undef);
5526 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5527 my $config = SVN::Core::config_get_config($config_dir);
5529 my $dont_store_passwords = 1;
5530 my $conf_t = ${$config}{'config'};
5533 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5534 # produces warnings that variables are used only once.
5535 # I had not found the better way to shut them up, so
5536 # the warnings of type 'once' are disabled in this block.
5537 if (SVN::_Core::svn_config_get_bool($conf_t,
5538 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5539 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5541 SVN::_Core::svn_auth_set_parameter($baton,
5542 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5543 bless (\$dont_store_passwords, "_p_void"));
5545 if (SVN::_Core::svn_config_get_bool($conf_t,
5546 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5547 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5549 $Git::SVN::Prompt::_no_auth_cache = 1;
5551 } # no warnings 'once'
5552 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5554 pool => SVN::Pool->new,
5555 auth_provider_callbacks => $callbacks);
5556 $self->{url} = $url;
5557 $self->{svn_path} = $url;
5558 $self->{repos_root} = $self->get_repos_root;
5559 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5560 $self->{cache} = { check_path => { r => 0, data => {} },
5561 get_dir => { r => 0, data => {} } };
5562 $RA = bless $self, $class;
5566 my ($self, $path, $r) = @_;
5567 my $cache = $self->{cache}->{check_path};
5568 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5569 return $cache->{data}->{$path};
5571 my $pool = SVN::Pool->new;
5572 my $t = $self->SUPER::check_path($path, $r, $pool);
5574 if ($r != $cache->{r}) {
5575 %{$cache->{data}} = ();
5578 $cache->{data}->{$path} = $t;
5582 my ($self, $dir, $r) = @_;
5583 my $cache = $self->{cache}->{get_dir};
5584 if ($r == $cache->{r}) {
5585 if (my $x = $cache->{data}->{$dir}) {
5586 return wantarray ? @$x : $x->[0];
5589 my $pool = SVN::Pool->new;
5590 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5591 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5593 if ($r != $cache->{r}) {
5594 %{$cache->{data}} = ();
5597 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5598 wantarray ? (\%dirents, $r, $props) : \%dirents;
5602 # do not call the real DESTROY since we store ourselves in $RA
5605 # get_log(paths, start, end, limit,
5606 # discover_changed_paths, strict_node_history, receiver)
5608 my ($self, @args) = @_;
5609 my $pool = SVN::Pool->new;
5611 # svn_log_changed_path_t objects passed to get_log are likely to be
5612 # overwritten even if only the refs are copied to an external variable,
5613 # so we should dup the structures in their entirety. Using an
5614 # externally passed pool (instead of our temporary and quickly cleared
5615 # pool in Git::SVN::Ra) does not help matters at all...
5616 my $receiver = pop @args;
5617 my $prefix = "/".$self->{svn_path};
5618 $prefix =~ s#/+($)##;
5619 my $prefix_regex = qr#^\Q$prefix\E#;
5621 my ($paths) = $_[0];
5622 return &$receiver(@_) unless $paths;
5624 foreach my $p (keys %$paths) {
5625 my $i = $paths->{$p};
5626 # Make path relative to our url, not repos_root
5627 $p =~ s/$prefix_regex//;
5628 my %s = map { $_ => $i->$_; }
5629 qw/copyfrom_path copyfrom_rev action/;
5630 if ($s{'copyfrom_path'}) {
5631 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5639 # the limit parameter was not supported in SVN 1.1.x, so we
5640 # drop it. Therefore, the receiver callback passed to it
5641 # is made aware of this limitation by being wrapped if
5642 # the limit passed to is being wrapped.
5643 if (::compare_svn_version('1.2.0') <= 0) {
5644 my $limit = splice(@args, 3, 1);
5646 my $receiver = pop @args;
5647 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5650 my $ret = $self->SUPER::get_log(@args, $pool);
5656 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5657 my $ctx = SVN::Client->new(auth => _auth_providers);
5658 my $out = IO::File->new_tmpfile;
5660 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5661 # $ctx->diff(), so we'll create a default one
5662 my $pool = SVN::Pool->new_default_sub;
5664 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5665 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5667 my $ret = (($out->stat)[7] == 0);
5668 close $out or croak $!;
5673 sub get_commit_editor {
5674 my ($self, $log, $cb, $pool) = @_;
5676 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef, 0) : ();
5677 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5681 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5682 my $new = ($rev_a == $rev_b);
5683 my $path = $gs->{path};
5685 if ($new && -e $gs->{index}) {
5686 unlink $gs->{index} or die
5687 "Couldn't unlink index: $gs->{index}: $!\n";
5689 my $pool = SVN::Pool->new;
5690 $editor->set_path_strip($path);
5691 my (@pc) = split m#/#, $path;
5692 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5694 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
5696 # Since we can't rely on svn_ra_reparent being available, we'll
5697 # just have to do some magic with set_path to make it so
5698 # we only want a partial path.
5700 my $final = join('/', @pc);
5702 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5703 $sp .= '/' if length $sp;
5706 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5708 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5710 $reporter->finish_report($pool);
5712 $editor->{git_commit_ok};
5715 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5716 # svn_ra_reparent didn't work before 1.4)
5718 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5719 my $path = $gs->{path};
5720 my $pool = SVN::Pool->new;
5722 my $full_url = $self->{url};
5723 my $old_url = $full_url;
5724 $full_url .= '/' . $path if length $path;
5725 my ($ra, $reparented);
5727 if ($old_url =~ m#^svn(\+ssh)?://# ||
5728 ($full_url =~ m#^https?://# &&
5729 escape_url($full_url) ne $full_url)) {
5733 $ra = Git::SVN::Ra->new($full_url);
5735 } elsif ($old_url ne $full_url) {
5736 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5737 $self->{url} = $full_url;
5742 $url_b = escape_url($url_b);
5743 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5744 my @lock = (::compare_svn_version('1.2.0') >= 0) ? (undef) : ();
5745 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5746 $reporter->finish_report($pool);
5749 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5750 $self->{url} = $old_url;
5754 $editor->{git_commit_ok};
5757 sub longest_common_path {
5758 my ($gsv, $globs) = @_;
5760 my $common_max = scalar @$gsv;
5762 foreach my $gs (@$gsv) {
5763 my @tmp = split m#/#, $gs->{path};
5766 $p .= length($p) ? "/$_" : $_;
5772 $common_max += scalar @$globs;
5773 foreach my $glob (@$globs) {
5774 my @tmp = split m#/#, $glob->{path}->{left};
5777 $p .= length($p) ? "/$_" : $_;
5783 my $longest_path = '';
5784 foreach (sort {length $b <=> length $a} keys %common) {
5785 if ($common{$_} == $common_max) {
5793 sub gs_fetch_loop_common {
5794 my ($self, $base, $head, $gsv, $globs) = @_;
5795 return if ($base > $head);
5796 my $inc = $_log_window_size;
5797 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5798 my $longest_path = longest_common_path($gsv, $globs);
5799 my $ra_url = $self->{url};
5800 my $find_trailing_edge;
5804 my $err_handler = $SVN::Error::handler;
5805 $SVN::Error::handler = sub {
5807 skip_unknown_revs($err);
5810 my ($paths, $r, $author, $date, $log) = @_;
5812 { author => $author, date => $date, log => $log } ];
5814 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5815 sub { $revs{$_[1]} = _cb(@_) });
5817 print "Checked through r$max\r";
5819 $find_trailing_edge = 1;
5821 if ($err and $find_trailing_edge) {
5822 print STDERR "Path '$longest_path' ",
5823 "was probably deleted:\n",
5824 $err->expanded_message,
5825 "\nWill attempt to follow ",
5826 "revisions r$min .. r$max ",
5827 "committed before the deletion\n";
5829 while (--$hi >= $min) {
5831 $self->get_log([$longest_path], $min, $hi,
5834 $revs{$_[1]} = _cb(@_) });
5836 print STDERR "r$min .. r$ok OK\n";
5840 $find_trailing_edge = 0;
5842 $SVN::Error::handler = $err_handler;
5844 my %exists = map { $_->{path} => $_ } @$gsv;
5845 foreach my $r (sort {$a <=> $b} keys %revs) {
5846 my ($paths, $logged) = @{$revs{$r}};
5848 foreach my $gs ($self->match_globs(\%exists, $paths,
5850 if ($gs->rev_map_max >= $r) {
5853 next unless $gs->match_paths($paths, $r);
5854 $gs->{logged_rev_props} = $logged;
5855 if (my $last_commit = $gs->last_commit) {
5856 $gs->assert_index_clean($last_commit);
5858 my $log_entry = $gs->do_fetch($paths, $r);
5860 $gs->do_git_commit($log_entry);
5862 $INDEX_FILES{$gs->{index}} = 1;
5864 foreach my $g (@$globs) {
5865 my $k = "svn-remote.$g->{remote}." .
5867 Git::SVN::tmp_config($k, $r);
5873 $self = Git::SVN::Ra->new($ra_url);
5874 $ra_invalid = undef;
5877 # pre-fill the .rev_db since it'll eventually get filled in
5878 # with '0' x40 if something new gets committed
5879 foreach my $gs (@$gsv) {
5880 next if $gs->rev_map_max >= $max;
5881 next if defined $gs->rev_map_get($max);
5882 $gs->rev_map_set($max, 0 x40);
5884 foreach my $g (@$globs) {
5885 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5886 Git::SVN::tmp_config($k, $max);
5888 last if $max >= $head;
5891 $max = $head if ($max > $head);
5896 sub get_dir_globbed {
5897 my ($self, $left, $depth, $r) = @_;
5899 my @x = eval { $self->get_dir($left, $r) };
5900 return unless scalar @x == 3;
5901 my $dirents = $x[0];
5903 foreach my $de (keys %$dirents) {
5904 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5906 my @args = ("$left/$de", $depth - 1, $r);
5907 foreach my $dir ($self->get_dir_globbed(@args)) {
5908 push @finalents, "$de/$dir";
5911 push @finalents, $de;
5917 # return value: 0 -- don't ignore, 1 -- ignore
5918 sub is_ref_ignored {
5920 my $refname = $g->{ref}->full_path($p);
5921 return 1 if defined($g->{ignore_refs_regex}) &&
5922 $refname =~ m!$g->{ignore_refs_regex}!;
5923 return 0 unless defined($_ignore_refs_regex);
5924 return 1 if $refname =~ m!$_ignore_refs_regex!o;
5929 my ($self, $exists, $paths, $globs, $r) = @_;
5932 my ($self, $exists, $g, $r) = @_;
5934 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5935 $g->{path}->{depth},
5938 foreach my $de (@dirs) {
5939 my $p = $g->{path}->full_path($de);
5940 next if $exists->{$p};
5941 next if (length $g->{path}->{right} &&
5942 ($self->check_path($p, $r) !=
5944 next unless $p =~ /$g->{path}->{regex}/;
5945 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5946 $g->{ref}->full_path($de), 1);
5949 foreach my $g (@$globs) {
5950 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5951 if ($path->{action} =~ /^[AR]$/) {
5952 get_dir_check($self, $exists, $g, $r);
5955 foreach (keys %$paths) {
5956 if (/$g->{path}->{left_regex}/ &&
5957 !/$g->{path}->{regex}/) {
5958 next if $paths->{$_}->{action} !~ /^[AR]$/;
5959 get_dir_check($self, $exists, $g, $r);
5961 next unless /$g->{path}->{regex}/;
5963 my $pathname = $g->{path}->full_path($p);
5964 next if is_ref_ignored($g, $p);
5965 next if $exists->{$pathname};
5966 next if ($self->check_path($pathname, $r) !=
5968 $exists->{$pathname} = Git::SVN->init(
5969 $self->{url}, $pathname, undef,
5970 $g->{ref}->full_path($p), 1);
5973 foreach (split m#/#, $g->{path}->{left}) {
5975 next unless ($paths->{$c} &&
5976 ($paths->{$c}->{action} =~ /^[AR]$/));
5977 get_dir_check($self, $exists, $g, $r);
5985 return $self->{url} if ($self->{url} eq $self->{repos_root});
5986 my $url = $self->{repos_root};
5987 my @components = split(m!/!, $self->{svn_path});
5990 $url .= "/$c" if length $c;
5992 my $ra = (ref $self)->new($url);
5993 my $latest = $ra->get_latest_revnum;
5994 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5996 } while ($@ && ($c = shift @components));
6002 unless (defined $can_do_switch) {
6003 my $pool = SVN::Pool->new;
6005 $self->do_switch(1, '', 0, $self->{url},
6006 SVN::Delta::Editor->new, $pool);
6011 $rep->abort_report($pool);
6019 sub skip_unknown_revs {
6021 my $errno = $err->apr_err();
6022 # Maybe the branch we're tracking didn't
6023 # exist when the repo started, so it's
6024 # not an error if it doesn't, just continue
6026 # Wonderfully consistent library, eh?
6027 # 160013 - svn:// and file://
6028 # 175002 - http(s)://
6029 # 175007 - http(s):// (this repo required authorization, too...)
6030 # More codes may be discovered later...
6031 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
6032 my $err_key = $err->expanded_message;
6033 # revision numbers change every time, filter them out
6034 $err_key =~ s/\d+/\0/g;
6035 $err_key = "$errno\0$err_key";
6036 unless ($ignored_err{$err_key}) {
6037 warn "W: Ignoring error from SVN, path probably ",
6038 "does not exist: ($errno): ",
6039 $err->expanded_message,"\n";
6040 warn "W: Do not be alarmed at the above message ",
6041 "git-svn is just searching aggressively for ",
6043 "This may take a while on large repositories\n";
6044 $ignored_err{$err_key} = 1;
6048 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
6051 package Git::SVN::Log;
6054 use POSIX qw/strftime/;
6055 use constant commit_log_separator => ('-' x 72) . "\n";
6056 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
6057 %rusers $show_commit $incremental/;
6062 return 1 if defined $c->{r};
6064 # big commit message got truncated by the 16k pretty buffer in rev-list
6065 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
6066 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
6068 my @log = command(qw/cat-file commit/, $c->{c});
6070 # shift off the headers
6071 shift @log while ($log[0] ne '');
6074 # TODO: make $c->{l} not have a trailing newline in the future
6075 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
6077 (undef, $c->{r}, undef) = ::extract_metadata(
6078 (grep(/^git-svn-id: /, @log))[-1]);
6080 return defined $c->{r};
6084 return $color || Git->repository->get_colorbool('color.diff');
6087 sub git_svn_log_cmd {
6088 my ($r_min, $r_max, @args) = @_;
6090 my (@files, @log_opts);
6091 foreach my $x (@args) {
6092 if ($x eq '--' || @files) {
6095 if (::verify_ref("$x^0")) {
6103 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
6104 $gs ||= Git::SVN->_new;
6105 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
6107 push @cmd, '-r' unless $non_recursive;
6108 push @cmd, qw/--raw --name-status/ if $verbose;
6109 push @cmd, '--color' if log_use_color();
6110 push @cmd, @log_opts;
6111 if (defined $r_max && $r_max == $r_min) {
6112 push @cmd, '--max-count=1';
6113 if (my $c = $gs->rev_map_get($r_max)) {
6116 } elsif (defined $r_max) {
6117 if ($r_max < $r_min) {
6118 ($r_min, $r_max) = ($r_max, $r_min);
6120 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
6121 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
6122 # If there are no commits in the range, both $c_max and $c_min
6123 # will be undefined. If there is at least 1 commit in the
6124 # range, both will be defined.
6125 return () if !defined $c_min || !defined $c_max;
6126 if ($c_min eq $c_max) {
6127 push @cmd, '--max-count=1', $c_min;
6129 push @cmd, '--boundary', "$c_min..$c_max";
6132 return (@cmd, @files);
6135 # adapted from pager.c
6138 $ENV{GIT_PAGER_IN_USE} = 'false';
6142 chomp($pager = command_oneline(qw(var GIT_PAGER)));
6143 if ($pager eq 'cat') {
6146 $ENV{GIT_PAGER_IN_USE} = defined($pager);
6150 return unless defined $pager;
6151 pipe my ($rfd, $wfd) or return;
6152 defined(my $pid = fork) or ::fatal "Can't fork: $!";
6154 open STDOUT, '>&', $wfd or
6155 ::fatal "Can't redirect to stdout: $!";
6158 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6159 $ENV{LESS} ||= 'FRSX';
6160 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6163 sub format_svn_date {
6164 my $t = shift || time;
6165 my $gmoff = Git::SVN::get_tz($t);
6166 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6169 sub parse_git_date {
6171 # Date::Parse isn't in the standard Perl distro :(
6172 if ($tz =~ s/^\+//) {
6173 $t += tz_to_s_offset($tz);
6174 } elsif ($tz =~ s/^\-//) {
6175 $t -= tz_to_s_offset($tz);
6180 sub set_local_timezone {
6188 sub tz_to_s_offset {
6191 return ($1 * 60) + ($tz * 3600);
6194 sub get_author_info {
6195 my ($dest, $author, $t, $tz) = @_;
6196 $author =~ s/(?:^\s*|\s*$)//g;
6197 $dest->{a_raw} = $author;
6200 $au = $rusers{$author} || undef;
6203 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6208 $dest->{t_utc} = parse_git_date($t, $tz);
6211 sub process_commit {
6212 my ($c, $r_min, $r_max, $defer) = @_;
6213 if (defined $r_min && defined $r_max) {
6214 if ($r_min == $c->{r} && $r_min == $r_max) {
6218 return 1 if $r_min == $r_max;
6219 if ($r_min < $r_max) {
6220 # we need to reverse the print order
6221 return 0 if (defined $limit && --$limit < 0);
6225 if ($r_min != $r_max) {
6226 return 1 if ($r_min < $c->{r});
6227 return 1 if ($r_max > $c->{r});
6230 return 0 if (defined $limit && --$limit < 0);
6239 if (my $l = $c->{l}) {
6240 while ($l->[0] =~ /^\s*$/) { shift @$l }
6243 $l_fmt ||= 'A' . length($c->{r});
6244 print 'r',pack($l_fmt, $c->{r}),' | ';
6245 print "$c->{c} | " if $show_commit;
6248 show_commit_normal($c);
6252 sub show_commit_changed_paths {
6254 return unless $c->{changed};
6255 print "Changed paths:\n", @{$c->{changed}};
6258 sub show_commit_normal {
6260 print commit_log_separator, "r$c->{r} | ";
6261 print "$c->{c} | " if $show_commit;
6262 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6265 if (my $l = $c->{l}) {
6266 while ($l->[$#$l] eq "\n" && $#$l > 0
6267 && $l->[($#$l - 1)] eq "\n") {
6270 $nr_line = scalar @$l;
6272 print "1 line\n\n\n";
6274 if ($nr_line == 1) {
6275 $nr_line = '1 line';
6277 $nr_line .= ' lines';
6279 print $nr_line, "\n";
6280 show_commit_changed_paths($c);
6282 print $_ foreach @$l;
6286 show_commit_changed_paths($c);
6290 foreach my $x (qw/raw stat diff/) {
6293 print $_ foreach @{$c->{$x}}
6300 my ($r_min, $r_max);
6301 my $r_last = -1; # prevent dupes
6302 set_local_timezone();
6303 if (defined $::_revision) {
6304 if ($::_revision =~ /^(\d+):(\d+)$/) {
6305 ($r_min, $r_max) = ($1, $2);
6306 } elsif ($::_revision =~ /^\d+$/) {
6307 $r_min = $r_max = $::_revision;
6309 ::fatal "-r$::_revision is not supported, use ",
6310 "standard 'git log' arguments instead";
6315 @args = git_svn_log_cmd($r_min, $r_max, @args);
6317 print commit_log_separator unless $incremental || $oneline;
6320 my $log = command_output_pipe(@args);
6322 my (@k, $c, $d, $stat);
6323 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6325 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6327 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6329 process_commit($c, $r_min, $r_max, \@k) or
6334 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6335 get_author_info($c, $1, $2, $3);
6336 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6338 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6339 push @{$c->{raw}}, $_;
6340 } elsif (/^${esc_color}[ACRMDT]\t/) {
6341 # we could add $SVN->{svn_path} here, but that requires
6342 # remote access at the moment (repo_path_split)...
6343 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6344 push @{$c->{changed}}, $_;
6345 } elsif (/^${esc_color}diff /o) {
6347 push @{$c->{diff}}, $_;
6349 push @{$c->{diff}}, $_;
6350 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6351 $esc_color*[\+\-]*$esc_color$/x) {
6353 push @{$c->{stat}}, $_;
6354 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6355 push @{$c->{stat}}, $_;
6357 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6358 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6359 } elsif (s/^${esc_color} //o) {
6360 push @{$c->{l}}, $_;
6363 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6365 process_commit($c, $r_min, $r_max, \@k);
6368 ($r_min, $r_max) = ($r_max, $r_min);
6369 process_commit($_, $r_min, $r_max) foreach reverse @k;
6373 print commit_log_separator unless $incremental || $oneline;
6382 my ($fh, $ctx, $rev);
6385 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6386 while (my $line = <$fh>) {
6387 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6388 # Uncommitted edits show up as a rev ID of
6389 # all zeros, which we can't look up with
6392 (undef, $rev, undef) =
6394 $rev = '0' if (!$rev);
6398 $rev = sprintf('%-10s', $rev);
6399 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6404 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6409 my %dsha; #distinct sha keys
6411 while (my $line = <$fh>) {
6412 push @buffer, $line;
6413 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6418 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6420 foreach my $line (@buffer) {
6421 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6423 $rev = '0' if (!$rev)
6425 elsif ($line =~ /^author (.*)/) {
6426 $authors{$rev} = $1;
6427 $authors{$rev} =~ s/\s/_/g;
6429 elsif ($line =~ /^\t(.*)$/) {
6430 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6434 command_close_pipe($fh, $ctx);
6437 package Git::SVN::Migration;
6438 # these version numbers do NOT correspond to actual version numbers
6439 # of git nor git-svn. They are just relative.
6441 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6443 # v1 layout: .git/$id/info/url, refs/remotes/$id
6445 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6447 # v3 layout: .git/svn/$id, refs/remotes/$id
6448 # - info/url may remain for backwards compatibility
6449 # - this is what we migrate up to this layout automatically,
6450 # - this will be used by git svn init on single branches
6451 # v3.1 layout (auto migrated):
6452 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6453 # for backwards compatibility
6455 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6456 # - this is only created for newly multi-init-ed
6457 # repositories. Similar in spirit to the
6458 # --use-separate-remotes option in git-clone (now default)
6459 # - we do not automatically migrate to this (following
6460 # the example set by core git)
6462 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6463 # - newer, more-efficient format that uses 24-bytes per record
6464 # with no filler space.
6465 # - use xxd -c24 < .rev_map.$UUID to view and debug
6466 # - This is a one-way migration, repositories updated to the
6467 # new format will not be able to use old git-svn without
6468 # rebuilding the .rev_db. Rebuilding the rev_db is not
6469 # possible if noMetadata or useSvmProps are set; but should
6470 # be no problem for users that use the (sensible) defaults.
6474 use File::Path qw/mkpath/;
6475 use File::Basename qw/dirname basename/;
6476 use vars qw/$_minimize/;
6478 sub migrate_from_v0 {
6479 my $git_dir = $ENV{GIT_DIR};
6480 return undef unless -d $git_dir;
6481 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6485 my ($id, $orig_ref) = ($_, $_);
6486 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6487 next unless -f "$git_dir/$id/info/url";
6488 my $new_ref = "refs/remotes/$id";
6489 if (::verify_ref("$new_ref^0")) {
6490 print STDERR "W: $orig_ref is probably an old ",
6491 "branch used by an ancient version of ",
6493 "However, $new_ref also exists.\n",
6494 "We will not be able ",
6495 "to use this branch until this ",
6496 "ambiguity is resolved.\n";
6499 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6500 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6501 command_noisy('update-ref', $new_ref, $orig_ref);
6502 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6505 command_close_pipe($fh, $ctx);
6506 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6510 sub migrate_from_v1 {
6511 my $git_dir = $ENV{GIT_DIR};
6513 return $migrated unless -d $git_dir;
6514 my $svn_dir = "$git_dir/svn";
6516 # just in case somebody used 'svn' as their $id at some point...
6517 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6519 print STDERR "Migrating from a git-svn v1 layout...\n";
6521 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6522 "$svn_dir\n\t(required for this version ",
6523 "($::VERSION) of git-svn) does not exist.\n";
6524 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6527 next unless $x =~ s#^refs/remotes/##;
6529 next unless -f "$git_dir/$x/info/url";
6530 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6532 my $dn = dirname("$git_dir/svn/$x");
6533 mkpath([$dn]) unless -d $dn;
6534 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6535 mkpath(["$git_dir/svn/svn"]);
6536 print STDERR " - $git_dir/$x/info => ",
6537 "$git_dir/svn/$x/info\n";
6538 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6540 # don't worry too much about these, they probably
6541 # don't exist with repos this old (save for index,
6542 # and we can easily regenerate that)
6543 foreach my $f (qw/unhandled.log index .rev_db/) {
6544 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6547 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6548 rename "$git_dir/$x", "$git_dir/svn/$x" or
6553 command_close_pipe($fh, $ctx);
6554 print STDERR "Done migrating from a git-svn v1 layout\n";
6559 my ($l_map, $pfx, $path) = @_;
6561 foreach (<$path/*>) {
6562 if (-r "$_/info/url") {
6563 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6564 my $ref_id = $pfx . basename $_;
6565 my $url = ::file_to_s("$_/info/url");
6566 $l_map->{$ref_id} = $url;
6573 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6574 read_old_urls($l_map, $x, $_);
6578 sub migrate_from_v2 {
6579 my @cfg = command(qw/config -l/);
6580 return if grep /^svn-remote\..+\.url=/, @cfg;
6582 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6585 foreach my $ref_id (sort keys %l_map) {
6586 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6588 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6595 sub minimize_connections {
6596 my $r = Git::SVN::read_all_remotes();
6598 my $root_repos = {};
6599 foreach my $repo_id (keys %$r) {
6600 my $url = $r->{$repo_id}->{url} or next;
6601 my $fetch = $r->{$repo_id}->{fetch} or next;
6602 my $ra = Git::SVN::Ra->new($url);
6604 # skip existing cases where we already connect to the root
6605 if (($ra->{url} eq $ra->{repos_root}) ||
6606 ($ra->{repos_root} eq $repo_id)) {
6607 $root_repos->{$ra->{url}} = $repo_id;
6611 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6612 my $root_path = $ra->{url};
6613 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6614 foreach my $path (keys %$fetch) {
6615 my $ref_id = $fetch->{$path};
6616 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6618 # make sure we can read when connecting to
6619 # a higher level of a repository
6620 my ($last_rev, undef) = $gs->last_rev_commit;
6621 if (!defined $last_rev) {
6623 $root_ra->get_latest_revnum;
6627 my $new = $root_path;
6628 $new .= length $path ? "/$path" : '';
6630 $root_ra->get_log([$new], $last_rev, $last_rev,
6634 $new_urls->{$ra->{repos_root}}->{$new} =
6635 { ref_id => $ref_id,
6636 old_repo_id => $repo_id,
6637 old_path => $path };
6642 foreach my $url (keys %$new_urls) {
6643 # see if we can re-use an existing [svn-remote "repo_id"]
6644 # instead of creating a(n ugly) new section:
6645 my $repo_id = $root_repos->{$url} || $url;
6647 my $fetch = $new_urls->{$url};
6648 foreach my $path (keys %$fetch) {
6649 my $x = $fetch->{$path};
6650 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6651 my $pfx = "svn-remote.$x->{old_repo_id}";
6653 my $old_fetch = quotemeta("$x->{old_path}:".
6655 command_noisy(qw/config --unset/,
6656 "$pfx.fetch", '^'. $old_fetch . '$');
6657 delete $r->{$x->{old_repo_id}}->
6658 {fetch}->{$x->{old_path}};
6659 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6660 command_noisy(qw/config --unset/,
6662 push @emptied, $x->{old_repo_id}
6667 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6669 The following [svn-remote] sections in your config file ($file) are empty
6670 and can be safely removed:
6672 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6676 sub migration_check {
6680 minimize_connections() if $_minimize;
6683 package Git::IndexInfo;
6686 use Git qw/command_input_pipe command_close_pipe/;
6690 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6691 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6695 my ($self, $path) = @_;
6696 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6697 return ++$self->{nr};
6703 my ($self, $mode, $hash, $path) = @_;
6704 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6705 return ++$self->{nr};
6712 command_close_pipe($self->{gui}, $self->{ctx});
6715 package Git::SVN::GlobSpec;
6720 my ($class, $glob, $pattern_ok) = @_;
6722 $re =~ s!/+$!!g; # no need for trailing slashes
6723 my (@left, @right, @patterns);
6725 my $die_msg = "Only one set of wildcard directories " .
6726 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6727 for my $part (split(m|/|, $glob)) {
6728 if ($part =~ /\*/ && $part ne "*") {
6729 die "Invalid pattern in '$glob': $part\n";
6730 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6731 $part !~ /^\{[^{}]+\}/) {
6732 die "Invalid pattern in '$glob': $part\n";
6735 die $die_msg if $state eq "right";
6737 push(@patterns, "[^/]*");
6738 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6739 die $die_msg if $state eq "right";
6741 my $p = quotemeta($1);
6743 push(@patterns, "(?:$p)");
6745 if ($state eq "left") {
6748 push(@right, $part);
6753 my $depth = @patterns;
6755 die "One '*' is needed in glob: '$glob'\n";
6757 my $left = join('/', @left);
6758 my $right = join('/', @right);
6759 $re = join('/', @patterns);
6761 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6762 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6763 bless { left => $left, right => $right, left_regex => $left_re,
6764 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6768 my ($self, $path) = @_;
6769 return (length $self->{left} ? "$self->{left}/" : '') .
6770 $path . (length $self->{right} ? "/$self->{right}" : '');
6778 $remotes = { # returned by read_all_remotes()
6780 # svn-remote.svn.url=https://svn.musicpd.org
6781 url => 'https://svn.musicpd.org',
6782 # svn-remote.svn.fetch=mpd/trunk:trunk
6784 'mpd/trunk' => 'trunk',
6786 # svn-remote.svn.tags=mpd/tags/*:tags/*
6791 regex => qr!mpd/tags/([^/]+)$!,
6797 regex => qr!tags/([^/]+)$!,
6804 $log_entry hashref as returned by libsvn_log_entry()
6806 log => 'whitespace-formatted log entry
6807 ', # trailing newline is preserved
6808 revision => '8', # integer
6809 date => '2004-02-24T17:01:44.108345Z', # commit date
6810 author => 'committer name'
6814 # this is generated by generate_diff();
6815 @mods = array of diff-index line hashes, each element represents one line
6816 of diff-index output
6818 diff-index line ($m hash)
6820 mode_a => first column of diff-index output, no leading ':',
6821 mode_b => second column of diff-index output,
6822 sha1_b => sha1sum of the final blob,
6823 chg => change type [MCRADT],
6824 file_a => original file name of a file (iff chg is 'C' or 'R')
6825 file_b => new/current file name of a file (any chg)
6829 # retval of read_url_paths{,_all}();
6831 # repository root url
6832 'https://svn.musicpd.org' => {
6833 # repository path # GIT_SVN_ID
6834 'mpd/trunk' => 'trunk',
6835 'mpd/tags/0.11.5' => 'tags/0.11.5',
6840 I don't trust the each() function on unless I created %hash myself
6841 because the internal iterator may not have started at base.