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';
45 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
48 if ($SVN::Core::VERSION lt '1.1.0') {
49 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
52 my $can_compress = eval { require Compress::Zlib; 1};
53 push @Git::SVN::Ra::ISA, 'SVN::Ra';
54 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
55 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
59 use File::Basename qw/dirname basename/;
60 use File::Path qw/mkpath/;
63 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
66 use Memoize; # core since 5.8.0, Jul 2002
69 # import functions from Git into our packages, en masse
71 foreach (qw/command command_oneline command_noisy command_output_pipe
72 command_input_pipe command_close_pipe
73 command_bidi_pipe command_close_bidi_pipe/) {
74 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
75 Git::SVN::Migration Git::SVN::Log Git::SVN),
77 *{"${package}::$_"} = \&{"Git::$_"};
80 Memoize::memoize 'Git::config';
81 Memoize::memoize 'Git::config_bool';
86 $sha1 = qr/[a-f\d]{40}/;
87 $sha1_short = qr/[a-f\d]{4,40}/;
88 my ($_stdin, $_help, $_edit,
89 $_message, $_file, $_branch_dest,
91 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
92 $_merge, $_strategy, $_dry_run, $_local,
93 $_prefix, $_no_checkout, $_url, $_verbose,
94 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
95 $Git::SVN::_follow_parent = 1;
96 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
98 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
99 'config-dir=s' => \$Git::SVN::Ra::config_dir,
100 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
101 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
102 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
103 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
104 'authors-file|A=s' => \$_authors,
105 'authors-prog=s' => \$_authors_prog,
106 'repack:i' => \$Git::SVN::_repack,
107 'noMetadata' => \$Git::SVN::_no_metadata,
108 'useSvmProps' => \$Git::SVN::_use_svm_props,
109 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
110 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
111 'no-checkout' => \$_no_checkout,
113 'repack-flags|repack-args|repack-opts=s' =>
114 \$Git::SVN::_repack_flags,
115 'use-log-author' => \$Git::SVN::_use_log_author,
116 'add-author-from' => \$Git::SVN::_add_author_from,
117 'localtime' => \$Git::SVN::_localtime,
120 my ($_trunk, @_tags, @_branches, $_stdlayout);
122 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
123 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
124 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
125 'stdlayout|s' => \$_stdlayout,
126 'minimize-url|m!' => \$Git::SVN::_minimize_url,
127 'no-metadata' => sub { $icv{noMetadata} = 1 },
128 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
129 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
130 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
131 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
133 my %cmt_opts = ( 'edit|e' => \$_edit,
134 'rmdir' => \$SVN::Git::Editor::_rmdir,
135 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
136 'l=i' => \$SVN::Git::Editor::_rename_limit,
137 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
141 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
142 { 'revision|r=s' => \$_revision,
143 'fetch-all|all' => \$_fetch_all,
144 'parent|p' => \$_fetch_parent,
146 clone => [ \&cmd_clone, "Initialize and fetch revisions",
147 { 'revision|r=s' => \$_revision,
148 'preserve-empty-dirs' =>
149 \$SVN::Git::Fetcher::_preserve_empty_dirs,
150 'placeholder-filename=s' =>
151 \$SVN::Git::Fetcher::_placeholder_filename,
152 %fc_opts, %init_opts } ],
153 init => [ \&cmd_init, "Initialize a repo for tracking" .
154 " (requires URL argument)",
156 'multi-init' => [ \&cmd_multi_init,
157 "Deprecated alias for ".
158 "'$0 init -T<trunk> -b<branches> -t<tags>'",
160 dcommit => [ \&cmd_dcommit,
161 'Commit several diffs to merge with upstream',
162 { 'merge|m|M' => \$_merge,
163 'strategy|s=s' => \$_strategy,
164 'verbose|v' => \$_verbose,
165 'dry-run|n' => \$_dry_run,
166 'fetch-all|all' => \$_fetch_all,
167 'commit-url=s' => \$_commit_url,
168 'revision|r=i' => \$_revision,
169 'no-rebase' => \$_no_rebase,
170 'mergeinfo=s' => \$_merge_info,
171 'interactive|i' => \$_interactive,
172 %cmt_opts, %fc_opts } ],
173 branch => [ \&cmd_branch,
174 'Create a branch in the SVN repository',
175 { 'message|m=s' => \$_message,
176 'destination|d=s' => \$_branch_dest,
177 'dry-run|n' => \$_dry_run,
179 'username=s' => \$Git::SVN::Prompt::_username,
180 'commit-url=s' => \$_commit_url } ],
181 tag => [ sub { $_tag = 1; cmd_branch(@_) },
182 'Create a tag in the SVN repository',
183 { 'message|m=s' => \$_message,
184 'destination|d=s' => \$_branch_dest,
185 'dry-run|n' => \$_dry_run,
186 'username=s' => \$Git::SVN::Prompt::_username,
187 'commit-url=s' => \$_commit_url } ],
188 'set-tree' => [ \&cmd_set_tree,
189 "Set an SVN repository to a git tree-ish",
190 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
191 'create-ignore' => [ \&cmd_create_ignore,
192 'Create a .gitignore per svn:ignore',
193 { 'revision|r=i' => \$_revision
195 'mkdirs' => [ \&cmd_mkdirs ,
196 "recreate empty directories after a checkout",
197 { 'revision|r=i' => \$_revision } ],
198 'propget' => [ \&cmd_propget,
199 'Print the value of a property on a file or directory',
200 { 'revision|r=i' => \$_revision } ],
201 'proplist' => [ \&cmd_proplist,
202 'List all properties of a file or directory',
203 { 'revision|r=i' => \$_revision } ],
204 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
205 { 'revision|r=i' => \$_revision
207 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
208 { 'revision|r=i' => \$_revision
210 'multi-fetch' => [ \&cmd_multi_fetch,
211 "Deprecated alias for $0 fetch --all",
212 { 'revision|r=s' => \$_revision, %fc_opts } ],
213 'migrate' => [ sub { },
214 # no-op, we automatically run this anyways,
215 'Migrate configuration/metadata/layout from
216 previous versions of git-svn',
217 { 'minimize' => \$Git::SVN::Migration::_minimize,
219 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
220 { 'limit=i' => \$Git::SVN::Log::limit,
221 'revision|r=s' => \$_revision,
222 'verbose|v' => \$Git::SVN::Log::verbose,
223 'incremental' => \$Git::SVN::Log::incremental,
224 'oneline' => \$Git::SVN::Log::oneline,
225 'show-commit' => \$Git::SVN::Log::show_commit,
226 'non-recursive' => \$Git::SVN::Log::non_recursive,
227 'authors-file|A=s' => \$_authors,
228 'color' => \$Git::SVN::Log::color,
229 'pager=s' => \$Git::SVN::Log::pager
231 'find-rev' => [ \&cmd_find_rev,
232 "Translate between SVN revision numbers and tree-ish",
234 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
235 { 'merge|m|M' => \$_merge,
236 'verbose|v' => \$_verbose,
237 'strategy|s=s' => \$_strategy,
238 'local|l' => \$_local,
239 'fetch-all|all' => \$_fetch_all,
240 'dry-run|n' => \$_dry_run,
242 'commit-diff' => [ \&cmd_commit_diff,
243 'Commit a diff between two trees',
244 { 'message|m=s' => \$_message,
245 'file|F=s' => \$_file,
246 'revision|r=s' => \$_revision,
248 'info' => [ \&cmd_info,
249 "Show info about the latest SVN revision
250 on the current branch",
251 { 'url' => \$_url, } ],
252 'blame' => [ \&Git::SVN::Log::cmd_blame,
253 "Show what revision and author last modified each line of a file",
254 { 'git-format' => \$_git_format } ],
255 'reset' => [ \&cmd_reset,
256 "Undo fetches back to the specified SVN revision",
257 { 'revision|r=s' => \$_revision,
258 'parent|p' => \$_fetch_parent } ],
260 "Compress unhandled.log files in .git/svn and remove " .
261 "index files in .git/svn",
268 my ($class, $reason) = @_;
269 return bless \$reason, shift;
273 die "Cannot use readline on FakeTerm: $$self";
278 $ENV{"GIT_SVN_NOTTY"}
279 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
280 : new Term::ReadLine 'git-svn';
283 $term = new FakeTerm "$@: going non-interactive";
287 for (my $i = 0; $i < @ARGV; $i++) {
288 if (defined $cmd{$ARGV[$i]}) {
292 } elsif ($ARGV[$i] eq 'help') {
298 # make sure we're always running at the top-level working directory
299 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
300 unless (-d $ENV{GIT_DIR}) {
301 if ($git_dir_user_set) {
302 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
303 "but it is not a directory\n";
305 my $git_dir = delete $ENV{GIT_DIR};
308 $cdup = command_oneline(qw/rev-parse --show-cdup/);
309 $git_dir = '.' unless ($cdup);
310 chomp $cdup if ($cdup);
311 $cdup = "." unless ($cdup && length $cdup);
312 } "Already at toplevel, but $git_dir not found\n";
313 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
314 unless (-d $git_dir) {
315 die "$git_dir still not found after going to ",
318 $ENV{GIT_DIR} = $git_dir;
320 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
323 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
325 read_git_config(\%opts);
326 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
327 Getopt::Long::Configure('pass_through');
329 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
330 'minimize-connections' => \$Git::SVN::Migration::_minimize,
331 'id|i=s' => \$Git::SVN::default_ref_id,
332 'svn-remote|remote|R=s' => sub {
333 $Git::SVN::no_reuse_existing = 1;
334 $Git::SVN::default_repo_id = $_[1] });
335 exit 1 if (!$rv && $cmd && $cmd ne 'log');
338 version() if $_version;
339 usage(1) unless defined $cmd;
340 load_authors() if $_authors;
341 if (defined $_authors_prog) {
342 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
345 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
346 Git::SVN::Migration::migration_check();
348 Git::SVN::init_vars();
350 Git::SVN::verify_remotes_sanity();
351 $cmd{$cmd}->[0]->(@ARGV);
354 post_fetch_checkout();
357 ####################### primary functions ######################
359 my $exit = shift || 0;
360 my $fd = $exit ? \*STDERR : \*STDOUT;
362 git-svn - bidirectional operations between a single Subversion tree and git
363 Usage: git svn <command> [options] [arguments]\n
365 print $fd "Available commands:\n" unless $cmd;
367 foreach (sort keys %cmd) {
368 next if $cmd && $cmd ne $_;
369 next if /^multi-/; # don't show deprecated commands
370 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
371 foreach (sort keys %{$cmd{$_}->[2]}) {
372 # mixed-case options are for .git/config only
373 next if /[A-Z]/ && /^[a-z]+$/i;
374 # prints out arguments as they should be passed:
375 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
376 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
378 split /\|/,$_)," $x\n";
382 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
383 arbitrary identifier if you're tracking multiple SVN branches/repositories in
384 one git repository and want to keep them separate. See git-svn(1) for more
392 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
397 my ($prompt, %arg) = @_;
398 my $valid_re = $arg{valid_re};
399 my $default = $arg{default};
403 if ( !( defined($term->IN)
404 && defined( fileno($term->IN) )
405 && defined( $term->OUT )
406 && defined( fileno($term->OUT) ) ) ){
407 return defined($default) ? $default : undef;
411 $resp = $term->readline($prompt);
412 if (!defined $resp) { # EOF
414 return defined $default ? $default : undef;
416 if ($resp eq '' and defined $default) {
419 if (!defined $valid_re or $resp =~ /$valid_re/) {
427 unless (-d $ENV{GIT_DIR}) {
428 my @init_db = ('init');
429 push @init_db, "--template=$_template" if defined $_template;
430 if (defined $_shared) {
431 if ($_shared =~ /[a-z]/) {
432 push @init_db, "--shared=$_shared";
434 push @init_db, "--shared";
437 command_noisy(@init_db);
438 $_repository = Git->repository(Repository => ".git");
441 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
442 foreach my $i (keys %icv) {
443 die "'$set' and '$i' cannot both be set\n" if $set;
444 next unless defined $icv{$i};
445 command_noisy('config', "$pfx.$i", $icv{$i});
448 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
449 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
450 if defined $$ignore_paths_regex;
451 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
452 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
453 if defined $$ignore_refs_regex;
455 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
456 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
457 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
458 command_noisy('config', "$pfx.placeholder-filename", $$fname);
463 my $repo_path = shift or return;
464 mkpath([$repo_path]) unless -d $repo_path;
465 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
466 $ENV{GIT_DIR} = '.git';
467 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
471 my ($url, $path) = @_;
472 if (!defined $path &&
473 (defined $_trunk || @_branches || @_tags ||
474 defined $_stdlayout) &&
475 $url !~ m#^[a-z\+]+://#) {
478 $path = basename($url) if !defined $path || !length $path;
479 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
480 cmd_init($url, $path);
481 command_oneline('config', 'svn.authorsfile', $authors_absolute)
483 Git::SVN::fetch_all($Git::SVN::default_repo_id);
487 if (defined $_stdlayout) {
488 $_trunk = 'trunk' if (!defined $_trunk);
489 @_tags = 'tags' if (! @_tags);
490 @_branches = 'branches' if (! @_branches);
492 if (defined $_trunk || @_branches || @_tags) {
493 return cmd_multi_init(@_);
495 my $url = shift or die "SVN repository location required ",
496 "as a command-line argument\n";
497 $url = canonicalize_url($url);
501 if ($Git::SVN::_minimize_url eq 'unset') {
502 $Git::SVN::_minimize_url = 0;
505 Git::SVN->init($url);
509 if (grep /^\d+=./, @_) {
510 die "'<rev>=<commit>' fetch arguments are ",
511 "no longer supported.\n";
515 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
517 $Git::SVN::no_reuse_existing = undef;
518 if ($_fetch_parent) {
519 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
521 die "Unable to determine upstream SVN information from ",
522 "working tree history\n";
524 # just fetch, don't checkout.
525 $_no_checkout = 'true';
526 $_fetch_all ? $gs->fetch_all : $gs->fetch;
527 } elsif ($_fetch_all) {
530 $remote ||= $Git::SVN::default_repo_id;
531 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
537 if ($_stdin || !@commits) {
538 print "Reading from stdin...\n";
541 if (/\b($sha1_short)\b/o) {
542 unshift @commits, $1;
547 foreach my $c (@commits) {
548 my @tmp = command('rev-parse',$c);
549 if (scalar @tmp == 1) {
551 } elsif (scalar @tmp > 1) {
552 push @revs, reverse(command('rev-list',@tmp));
554 fatal "Failed to rev-parse $c";
557 my $gs = Git::SVN->new;
558 my ($r_last, $cmt_last) = $gs->last_rev_commit;
560 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
561 fatal "There are new revisions that were fetched ",
562 "and need to be merged (or acknowledged) ",
563 "before committing.\nlast rev: $r_last\n",
564 " current: $gs->{last_rev}";
566 $gs->set_tree($_) foreach @revs;
567 print "Done committing ",scalar @revs," revisions to SVN\n";
571 sub split_merge_info_range {
573 if ($range =~ /(\d+)-(\d+)/) {
574 return (int($1), int($2));
576 return (int($range), int($range));
584 my @arr = split(/,/, $in);
585 for my $element (@arr) {
586 my ($start, $end) = split_merge_info_range($element);
590 my @sorted = @arr [ sort {
591 $fnums[$a] <=> $fnums[$b]
597 for my $element (@sorted) {
598 my ($start, $end) = split_merge_info_range($element);
605 if ($start <= $last+1) {
611 if ($first == $last) {
612 push @return, "$first";
614 push @return, "$first-$last";
621 if ($first == $last) {
622 push @return, "$first";
624 push @return, "$first-$last";
628 return join(',', @return);
631 sub merge_revs_into_hash {
632 my ($hash, $minfo) = @_;
633 my @lines = split(' ', $minfo);
635 for my $line (@lines) {
636 my ($branchpath, $revs) = split(/:/, $line);
638 if (exists($hash->{$branchpath})) {
639 # Merge the two revision sets
640 my $combined = "$hash->{$branchpath},$revs";
641 $hash->{$branchpath} = combine_ranges($combined);
643 # Just do range combining for consolidation
644 $hash->{$branchpath} = combine_ranges($revs);
649 sub merge_merge_info {
650 my ($mergeinfo_one, $mergeinfo_two) = @_;
651 my %result_hash = ();
653 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
654 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
657 # Sort below is for consistency's sake
658 for my $branchname (sort keys(%result_hash)) {
659 my $revlist = $result_hash{$branchname};
660 $result .= "$branchname:$revlist\n"
665 sub populate_merge_info {
666 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
669 read_commit_parents(\%parentshash, $d);
670 my @parents = @{$parentshash{$d}};
673 my $all_parents_ok = 1;
674 my $aggregate_mergeinfo = '';
675 my $rooturl = $gs->repos_root;
677 if (defined($rewritten_parent)) {
678 # Replace first parent with newly-rewritten version
680 unshift @parents, $rewritten_parent;
683 foreach my $parent (@parents) {
684 my ($branchurl, $svnrev, $paruuid) =
685 cmt_metadata($parent);
687 unless (defined($svnrev)) {
688 # Should have been caught be preflight check
689 fatal "merge commit $d has ancestor $parent, but that change "
690 ."does not have git-svn metadata!";
692 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
693 fatal "commit $parent git-svn metadata changed mid-run!";
697 my $ra = Git::SVN::Ra->new($branchurl);
698 my (undef, undef, $props) =
699 $ra->get_dir(canonicalize_path("."), $svnrev);
700 my $par_mergeinfo = $props->{'svn:mergeinfo'};
701 unless (defined $par_mergeinfo) {
704 # Merge previous mergeinfo values
705 $aggregate_mergeinfo =
706 merge_merge_info($aggregate_mergeinfo,
709 next if $parent eq $parents[0]; # Skip first parent
710 # Add new changes being placed in tree by merge
711 my @cmd = (qw/rev-list --reverse/,
713 foreach my $par (@parents) {
714 unless ($par eq $parent) {
719 my ($revlist, $ctx) = command_output_pipe(@cmd);
723 my (undef, $csvnrev, undef) =
725 unless (defined $csvnrev) {
726 # A child is missing SVN annotations...
727 # this might be OK, or might not be.
728 warn "W:child $irev is merged into revision "
729 ."$d but does not have git-svn metadata. "
730 ."This means git-svn cannot determine the "
731 ."svn revision numbers to place into the "
732 ."svn:mergeinfo property. You must ensure "
733 ."a branch is entirely committed to "
734 ."SVN before merging it in order for "
735 ."svn:mergeinfo population to function "
738 push @revsin, $csvnrev;
740 command_close_pipe($revlist, $ctx);
742 last unless $all_parents_ok;
744 # We now have a list of all SVN revnos which are
745 # merged by this particular parent. Integrate them.
746 next if $#revsin == -1;
747 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
748 $aggregate_mergeinfo =
749 merge_merge_info($aggregate_mergeinfo,
752 if ($all_parents_ok and $aggregate_mergeinfo) {
753 return $aggregate_mergeinfo;
762 command_noisy(qw/update-index --refresh/);
763 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
764 'Cannot dcommit with a dirty index. Commit your changes first, '
765 . "or stash them with `git stash'.\n";
769 if ($head ne 'HEAD') {
771 command_oneline([qw/symbolic-ref -q HEAD/])
774 $old_head =~ s{^refs/heads/}{};
776 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
778 command(['checkout', $head], STDERR => 0);
782 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
784 die "Unable to determine upstream SVN information from ",
785 "$head history.\nPerhaps the repository is empty.";
788 if (defined $_commit_url) {
791 $url = eval { command_oneline('config', '--get',
792 "svn-remote.$gs->{repo_id}.commiturl") };
794 $url = $gs->full_pushurl
798 my $last_rev = $_revision if defined $_revision;
800 print "Committing to $url ...\n";
802 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
803 if ($_no_rebase && scalar(@$linear_refs) > 1) {
804 warn "Attempting to commit more than one change while ",
805 "--no-rebase is enabled.\n",
806 "If these changes depend on each other, re-running ",
807 "without --no-rebase may be required."
810 if (defined $_interactive){
811 my $ask_default = "y";
812 foreach my $d (@$linear_refs){
813 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
817 command_close_pipe($fh, $ctx);
818 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
819 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
820 default => $ask_default);
821 die "Commit this patch reply required" unless defined $_;
830 my $expect_url = $url;
832 my $push_merge_info = eval {
833 command_oneline(qw/config --get svn.pushmergeinfo/)
835 if (not defined($push_merge_info)
836 or $push_merge_info eq "false"
837 or $push_merge_info eq "no"
838 or $push_merge_info eq "never") {
839 $push_merge_info = 0;
842 unless (defined($_merge_info) || ! $push_merge_info) {
843 # Preflight check of changes to ensure no issues with mergeinfo
844 # This includes check for uncommitted-to-SVN parents
845 # (other than the first parent, which we will handle),
846 # information from different SVN repos, and paths
847 # which are not underneath this repository root.
848 my $rooturl = $gs->repos_root;
849 foreach my $d (@$linear_refs) {
851 read_commit_parents(\%parentshash, $d);
852 my @realparents = @{$parentshash{$d}};
853 if ($#realparents > 0) {
855 shift @realparents; # Remove/ignore first parent
856 foreach my $parent (@realparents) {
857 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
858 unless (defined $paruuid) {
859 # A parent is missing SVN annotations...
860 # abort the whole operation.
861 fatal "$parent is merged into revision $d, "
862 ."but does not have git-svn metadata. "
863 ."Either dcommit the branch or use a "
864 ."local cherry-pick, FF merge, or rebase "
865 ."instead of an explicit merge commit.";
868 unless ($paruuid eq $uuid) {
869 # Parent has SVN metadata from different repository
870 fatal "merge parent $parent for change $d has "
871 ."git-svn uuid $paruuid, while current change "
875 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
876 # This branch is very strange indeed.
877 fatal "merge parent $parent for $d is on branch "
878 ."$branchurl, which is not under the "
879 ."git-svn root $rooturl!";
886 my $rewritten_parent;
887 Git::SVN::remove_username($expect_url);
888 if (defined($_merge_info)) {
889 $_merge_info =~ tr{ }{\n};
892 my $d = shift @$linear_refs or last;
893 unless (defined $last_rev) {
894 (undef, $last_rev, undef) = cmt_metadata("$d~1");
895 unless (defined $last_rev) {
896 fatal "Unable to extract revision information ",
901 print "diff-tree $d~1 $d\n";
905 unless (defined($_merge_info) || ! $push_merge_info) {
906 $_merge_info = populate_merge_info($d, $gs,
912 my %ed_opts = ( r => $last_rev,
913 log => get_commit_entry($d)->{log},
914 ra => Git::SVN::Ra->new($url),
915 config => SVN::Core::config_get_config(
916 $Git::SVN::Ra::config_dir
921 print "Committed r$_[0]\n";
924 mergeinfo => $_merge_info,
926 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
927 print "No changes\n$d~1 == $d\n";
928 } elsif ($parents->{$d} && @{$parents->{$d}}) {
929 $gs->{inject_parents_dcommit}->{$cmt_rev} =
932 $_fetch_all ? $gs->fetch_all : $gs->fetch;
933 $last_rev = $cmt_rev;
936 # we always want to rebase against the current HEAD,
937 # not any head that was passed to us
938 my @diff = command('diff-tree', $d,
942 @finish = rebase_cmd();
943 print STDERR "W: $d and ", $gs->refname,
944 " differ, using @finish:\n",
945 join("\n", @diff), "\n";
947 print "No changes between current HEAD and ",
949 "\nResetting to the latest ",
951 @finish = qw/reset --mixed/;
953 command_noisy(@finish, $gs->refname);
955 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
959 my ($url_, $rev_, $uuid_, $gs_) =
960 working_head_info('HEAD', \@refs);
961 my ($linear_refs_, $parents_) =
962 linearize_history($gs_, \@refs);
963 if (scalar(@$linear_refs) !=
964 scalar(@$linear_refs_)) {
965 fatal "# of revisions changed ",
967 join("\n", @$linear_refs),
969 join("\n", @$linear_refs_), "\n",
970 'If you are attempting to commit ',
971 "merges, try running:\n\t",
972 'git rebase --interactive',
973 '--preserve-merges ',
975 "\nBefore dcommitting";
977 if ($url_ ne $expect_url) {
978 if ($url_ eq $gs->metadata_url) {
980 "Accepting rewritten URL:",
984 "URL mismatch after rebase:",
985 " $url_ != $expect_url";
988 if ($uuid_ ne $uuid) {
989 fatal "uuid mismatch after rebase: ",
994 for ($i = 0; $i < scalar @$linear_refs; $i++) {
995 my $new = $linear_refs_->[$i] or next;
997 $parents->{$linear_refs->[$i]};
1007 my $new_head = command_oneline(qw/rev-parse HEAD/);
1008 my $new_is_symbolic = eval {
1009 command_oneline(qw/symbolic-ref -q HEAD/);
1011 if ($new_is_symbolic) {
1012 print "dcommitted the branch ", $head, "\n";
1014 print "dcommitted on a detached HEAD because you gave ",
1015 "a revision argument.\n",
1016 "The rewritten commit is: ", $new_head, "\n";
1018 command(['checkout', $old_head], STDERR => 0);
1021 unlink $gs->{index};
1025 my ($branch_name, $head) = @_;
1027 unless (defined $branch_name && length $branch_name) {
1028 die(($_tag ? "tag" : "branch") . " name required\n");
1032 my (undef, $rev, undef, $gs) = working_head_info($head);
1033 my $src = $gs->full_pushurl;
1035 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1036 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1038 if ($#{$allglobs} == 0) {
1039 $glob = $allglobs->[0];
1041 unless(defined $_branch_dest) {
1043 $_tag ? "tag" : "branch",
1044 " paths defined for Subversion repository.\n",
1045 "You must specify where you want to create the ",
1046 $_tag ? "tag" : "branch",
1047 " with the --destination argument.\n";
1049 foreach my $g (@{$allglobs}) {
1050 # SVN::Git::Editor could probably be moved to Git.pm..
1051 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1052 if ($_branch_dest =~ /$re/) {
1057 unless (defined $glob) {
1058 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1059 foreach my $g (@{$allglobs}) {
1060 $g->{path}->{left} =~ /$dest_re/ or next;
1061 if (defined $glob) {
1062 die "Ambiguous destination: ",
1063 $_branch_dest, "\nmatches both '",
1064 $glob->{path}->{left}, "' and '",
1065 $g->{path}->{left}, "'\n";
1069 unless (defined $glob) {
1071 $_tag ? "tag" : "branch",
1072 " destination $_branch_dest\n";
1076 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1078 if (defined $_commit_url) {
1079 $url = $_commit_url;
1081 $url = eval { command_oneline('config', '--get',
1082 "svn-remote.$gs->{repo_id}.commiturl") };
1084 $url = $remote->{pushurl} || $remote->{url};
1087 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1089 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1090 $src=~s/^http:/https:/;
1095 my $ctx = SVN::Client->new(
1096 auth => Git::SVN::Ra::_auth_providers(),
1098 ${ $_[0] } = defined $_message
1100 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1106 $ctx->ls($dst, 'HEAD', 0);
1107 } and die "branch ${branch_name} already exists\n";
1109 print "Copying ${src} at r${rev} to ${dst}...\n";
1110 $ctx->copy($src, $rev, $dst)
1117 my $revision_or_hash = shift or die "SVN or git revision required ",
1118 "as a command-line argument\n";
1120 if ($revision_or_hash =~ /^r\d+$/) {
1124 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1126 die "Unable to determine upstream SVN information from ",
1129 my $desired_revision = substr($revision_or_hash, 1);
1130 $result = $gs->rev_map_get($desired_revision, $uuid);
1132 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1135 print "$result\n" if $result;
1138 sub auto_create_empty_directories {
1140 my $var = eval { command_oneline('config', '--get', '--bool',
1141 "svn-remote.$gs->{repo_id}.automkdirs") };
1142 # By default, create empty directories by consulting the unhandled log,
1143 # but allow setting it to 'false' to skip it.
1144 return !($var && $var eq 'false');
1148 command_noisy(qw/update-index --refresh/);
1149 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1151 die "Unable to determine upstream SVN information from ",
1152 "working tree history\n";
1155 print "Remote Branch: " . $gs->refname . "\n";
1156 print "SVN URL: " . $url . "\n";
1159 if (command(qw/diff-index HEAD --/)) {
1160 print STDERR "Cannot rebase with uncommited changes:\n";
1161 command_noisy('status');
1165 # rebase will checkout for us, so no need to do it explicitly
1166 $_no_checkout = 'true';
1167 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1169 command_noisy(rebase_cmd(), $gs->refname);
1170 if (auto_create_empty_directories($gs)) {
1175 sub cmd_show_ignore {
1176 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1177 $gs ||= Git::SVN->new;
1178 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1179 $gs->prop_walk($gs->{path}, $r, sub {
1180 my ($gs, $path, $props) = @_;
1181 print STDOUT "\n# $path\n";
1182 my $s = $props->{'svn:ignore'} or return;
1183 $s =~ s/[\r\n]+/\n/g;
1187 print STDOUT "$s\n";
1191 sub cmd_show_externals {
1192 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1193 $gs ||= Git::SVN->new;
1194 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1195 $gs->prop_walk($gs->{path}, $r, sub {
1196 my ($gs, $path, $props) = @_;
1197 print STDOUT "\n# $path\n";
1198 my $s = $props->{'svn:externals'} or return;
1199 $s =~ s/[\r\n]+/\n/g;
1202 print STDOUT "$s\n";
1206 sub cmd_create_ignore {
1207 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1208 $gs ||= Git::SVN->new;
1209 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1210 $gs->prop_walk($gs->{path}, $r, sub {
1211 my ($gs, $path, $props) = @_;
1212 # $path is of the form /path/to/dir/
1213 $path = '.' . $path;
1214 # SVN can have attributes on empty directories,
1215 # which git won't track
1216 mkpath([$path]) unless -d $path;
1217 my $ignore = $path . '.gitignore';
1218 my $s = $props->{'svn:ignore'} or return;
1219 open(GITIGNORE, '>', $ignore)
1220 or fatal("Failed to open `$ignore' for writing: $!");
1221 $s =~ s/[\r\n]+/\n/g;
1224 # Prefix all patterns so that the ignore doesn't apply
1225 # to sub-directories.
1227 print GITIGNORE "$s\n";
1229 or fatal("Failed to close `$ignore': $!");
1230 command_noisy('add', '-f', $ignore);
1235 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1236 $gs ||= Git::SVN->new;
1237 $gs->mkemptydirs($_revision);
1240 sub canonicalize_path {
1242 my $dot_slash_added = 0;
1243 if (substr($path, 0, 1) ne "/") {
1244 $path = "./" . $path;
1245 $dot_slash_added = 1;
1247 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1248 # good reason), so let's do this manually.
1250 $path =~ s#/\.(?:/|$)#/#g;
1251 $path =~ s#/[^/]+/\.\.##g;
1253 $path =~ s#^\./## if $dot_slash_added;
1259 sub canonicalize_url {
1261 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1265 # get_svnprops(PATH)
1266 # ------------------
1267 # Helper for cmd_propget and cmd_proplist below.
1270 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1271 $gs ||= Git::SVN->new;
1273 # prefix THE PATH by the sub-directory from which the user
1275 $path = $cmd_dir_prefix . $path;
1276 fatal("No such file or directory: $path") unless -e $path;
1277 my $is_dir = -d $path ? 1 : 0;
1278 $path = $gs->{path} . '/' . $path;
1280 # canonicalize the path (otherwise libsvn will abort or fail to
1282 $path = canonicalize_path($path);
1284 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1287 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1290 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1295 # cmd_propget (PROP, PATH)
1296 # ------------------------
1297 # Print the SVN property PROP for PATH.
1299 my ($prop, $path) = @_;
1300 $path = '.' if not defined $path;
1301 usage(1) if not defined $prop;
1302 my $props = get_svnprops($path);
1303 if (not defined $props->{$prop}) {
1304 fatal("`$path' does not have a `$prop' SVN property.");
1306 print $props->{$prop} . "\n";
1309 # cmd_proplist (PATH)
1310 # -------------------
1311 # Print the list of SVN properties for PATH.
1314 $path = '.' if not defined $path;
1315 my $props = get_svnprops($path);
1316 print "Properties on '$path':\n";
1317 foreach (sort keys %{$props}) {
1322 sub cmd_multi_init {
1324 unless (defined $_trunk || @_branches || @_tags) {
1328 $_prefix = '' unless defined $_prefix;
1330 $url = canonicalize_url($url);
1334 if (defined $_trunk) {
1336 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1337 # try both old-style and new-style lookups:
1338 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1339 unless ($gs_trunk) {
1340 my ($trunk_url, $trunk_path) =
1341 complete_svn_url($url, $_trunk);
1342 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1346 return unless @_branches || @_tags;
1347 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1348 foreach my $path (@_branches) {
1349 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1351 foreach my $path (@_tags) {
1352 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1356 sub cmd_multi_fetch {
1357 $Git::SVN::no_reuse_existing = undef;
1358 my $remotes = Git::SVN::read_all_remotes();
1359 foreach my $repo_id (sort keys %$remotes) {
1360 if ($remotes->{$repo_id}->{url}) {
1361 Git::SVN::fetch_all($repo_id, $remotes);
1366 # this command is special because it requires no metadata
1367 sub cmd_commit_diff {
1368 my ($ta, $tb, $url) = @_;
1369 my $usage = "Usage: $0 commit-diff -r<revision> ".
1370 "<tree-ish> <tree-ish> [<URL>]";
1371 fatal($usage) if (!defined $ta || !defined $tb);
1373 if (!defined $url) {
1374 my $gs = eval { Git::SVN->new };
1376 fatal("Needed URL or usable git-svn --id in ",
1377 "the command-line\n", $usage);
1380 $svn_path = $gs->{path};
1382 unless (defined $_revision) {
1383 fatal("-r|--revision is a required argument\n", $usage);
1385 if (defined $_message && defined $_file) {
1386 fatal("Both --message/-m and --file/-F specified ",
1387 "for the commit message.\n",
1388 "I have no idea what you mean");
1390 if (defined $_file) {
1391 $_message = file_to_s($_file);
1393 $_message ||= get_commit_entry($tb)->{log};
1395 my $ra ||= Git::SVN::Ra->new($url);
1398 $r = $ra->get_latest_revnum;
1399 } elsif ($r !~ /^\d+$/) {
1400 die "revision argument: $r not understood by git-svn\n";
1402 my %ed_opts = ( r => $r,
1407 editor_cb => sub { print "Committed r$_[0]\n" },
1408 svn_path => $svn_path );
1409 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1410 print "No changes\n$ta == $tb\n";
1414 sub escape_uri_only {
1417 foreach (split m{/}, $uri) {
1418 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1426 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1427 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1428 $url = "$scheme://$domain$uri";
1434 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1435 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1437 die "Too many arguments specified\n";
1440 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1442 if (!$file_type && !$diff_status) {
1443 print STDERR "svn: '$path' is not under version control\n";
1447 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1449 die "Unable to determine upstream SVN information from ",
1450 "working tree history\n";
1453 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1454 $path = "." if $path eq "";
1456 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1459 print escape_url($full_url), "\n";
1463 my $result = "Path: $path\n";
1464 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1465 $result .= "URL: " . escape_url($full_url) . "\n";
1468 my $repos_root = $gs->repos_root;
1469 Git::SVN::remove_username($repos_root);
1470 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1473 $result .= "Repository Root: (offline)\n";
1476 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1477 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1478 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1480 $result .= "Node Kind: " .
1481 ($file_type eq "dir" ? "directory" : "file") . "\n";
1483 my $schedule = $diff_status eq "A"
1485 : ($diff_status eq "D" ? "delete" : "normal");
1486 $result .= "Schedule: $schedule\n";
1488 if ($diff_status eq "A") {
1489 print $result, "\n";
1493 my ($lc_author, $lc_rev, $lc_date_utc);
1494 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1495 my $log = command_output_pipe(@args);
1496 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1498 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1500 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1501 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1502 (undef, $lc_rev, undef) = ::extract_metadata($1);
1507 Git::SVN::Log::set_local_timezone();
1509 $result .= "Last Changed Author: $lc_author\n";
1510 $result .= "Last Changed Rev: $lc_rev\n";
1511 $result .= "Last Changed Date: " .
1512 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1514 if ($file_type ne "dir") {
1515 my $text_last_updated_date =
1516 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1518 "Text Last Updated: " .
1519 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1522 if ($diff_status eq "D") {
1524 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1525 if ($file_type eq "link") {
1526 my $file_name = <$fh>;
1527 $checksum = md5sum("link $file_name");
1529 $checksum = md5sum($fh);
1531 command_close_pipe($fh, $ctx);
1532 } elsif ($file_type eq "link") {
1534 command(qw(cat-file blob), "HEAD:$path");
1536 md5sum("link " . $file_name);
1538 open FILE, "<", $path or die $!;
1539 $checksum = md5sum(\*FILE);
1540 close FILE or die $!;
1542 $result .= "Checksum: " . $checksum . "\n";
1545 print $result, "\n";
1549 my $target = shift || $_revision or die "SVN revision required\n";
1550 $target = $1 if $target =~ /^r(\d+)$/;
1551 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1552 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1554 die "Unable to determine upstream SVN information from ".
1557 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1558 die "Cannot find SVN revision $target\n" unless defined($c);
1559 $gs->rev_map_set($r, $c, 'reset', $uuid);
1560 print "r$r = $c ($gs->{ref_id})\n";
1564 if (!$can_compress) {
1565 warn "Compress::Zlib could not be found; unhandled.log " .
1566 "files will not be compressed.\n";
1568 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1571 ########################### utility functions #########################
1574 my @cmd = qw/rebase/;
1575 push @cmd, '-v' if $_verbose;
1576 push @cmd, qw/--merge/ if $_merge;
1577 push @cmd, "--strategy=$_strategy" if $_strategy;
1581 sub post_fetch_checkout {
1582 return if $_no_checkout;
1583 my $gs = $Git::SVN::_head or return;
1584 return if verify_ref('refs/heads/master^0');
1586 # look for "trunk" ref if it exists
1587 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1588 my $fetch = $remote->{fetch};
1590 foreach my $p (keys %$fetch) {
1591 basename($fetch->{$p}) eq 'trunk' or next;
1592 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1597 my $valid_head = verify_ref('HEAD^0');
1598 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1599 return if ($valid_head || !verify_ref('HEAD^0'));
1601 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1602 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1603 return if -f $index;
1605 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1606 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1607 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1608 print STDERR "Checked out HEAD:\n ",
1609 $gs->full_url, " r", $gs->last_rev, "\n";
1610 if (auto_create_empty_directories($gs)) {
1611 $gs->mkemptydirs($gs->last_rev);
1615 sub complete_svn_url {
1616 my ($url, $path) = @_;
1618 if ($path !~ m#^[a-z\+]+://#) {
1619 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1620 fatal("E: '$path' is not a complete URL ",
1621 "and a separate URL is not specified");
1623 return ($url, $path);
1628 sub complete_url_ls_init {
1629 my ($ra, $repo_path, $switch, $pfx) = @_;
1630 unless ($repo_path) {
1631 print STDERR "W: $switch not specified\n";
1634 $repo_path =~ s#/+$##;
1635 if ($repo_path =~ m#^[a-z\+]+://#) {
1636 $ra = Git::SVN::Ra->new($repo_path);
1639 $repo_path =~ s#^/+##;
1641 fatal("E: '$repo_path' is not a complete URL ",
1642 "and a separate URL is not specified");
1645 my $url = $ra->{url};
1646 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1647 my $k = "svn-remote.$gs->{repo_id}.url";
1648 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1649 if ($orig_url && ($orig_url ne $gs->{url})) {
1650 die "$k already set: $orig_url\n",
1651 "wanted to set to: $gs->{url}\n";
1653 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1654 my $remote_path = "$gs->{path}/$repo_path";
1655 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1656 $remote_path =~ s#/+#/#g;
1657 $remote_path =~ s#^/##g;
1658 $remote_path .= "/*" if $remote_path !~ /\*/;
1659 my ($n) = ($switch =~ /^--(\w+)/);
1660 if (length $pfx && $pfx !~ m#/$#) {
1661 die "--prefix='$pfx' must have a trailing slash '/'\n";
1663 command_noisy('config',
1665 "svn-remote.$gs->{repo_id}.$n",
1666 "$remote_path:refs/remotes/$pfx*" .
1667 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1672 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1673 { STDERR => 0 }); };
1676 sub get_tree_from_treeish {
1678 # $treeish can be a symbolic ref, too:
1679 my $type = command_oneline(qw/cat-file -t/, $treeish);
1681 while ($type eq 'tag') {
1682 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1684 if ($type eq 'commit') {
1685 $expected = (grep /^tree /, command(qw/cat-file commit/,
1687 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1688 die "Unable to get tree from $treeish\n" unless $expected;
1689 } elsif ($type eq 'tree') {
1690 $expected = $treeish;
1692 die "$treeish is a $type, expected tree, tag or commit\n";
1697 sub get_commit_entry {
1698 my ($treeish) = shift;
1699 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1700 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1701 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1702 open my $log_fh, '>', $commit_editmsg or croak $!;
1704 my $type = command_oneline(qw/cat-file -t/, $treeish);
1705 if ($type eq 'commit' || $type eq 'tag') {
1706 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1714 $in_msg = 1 if (/^\s*$/);
1715 $author = $1 if (/^author (.*>)/);
1716 } elsif (/^git-svn-id: /) {
1717 # skip this for now, we regenerate the
1718 # correct one on re-fetch anyways
1719 # TODO: set *:merge properties or like...
1721 if (/^From:/ || /^Signed-off-by:/) {
1727 $msgbuf =~ s/\s+$//s;
1728 if ($Git::SVN::_add_author_from && defined($author)
1730 $msgbuf .= "\n\nFrom: $author";
1732 print $log_fh $msgbuf or croak $!;
1733 command_close_pipe($msg_fh, $ctx);
1735 close $log_fh or croak $!;
1737 if ($_edit || ($type eq 'tree')) {
1738 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1739 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1741 rename $commit_editmsg, $commit_msg or croak $!;
1744 # SVN requires messages to be UTF-8 when entering the repo
1746 open $log_fh, '<', $commit_msg or croak $!;
1748 chomp($log_entry{log} = <$log_fh>);
1750 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1751 my $msg = $log_entry{log};
1753 eval { $msg = Encode::decode($enc, $msg, 1) };
1755 die "Could not decode as $enc:\n", $msg,
1756 "\nPerhaps you need to set i18n.commitencoding\n";
1759 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1760 die "Could not encode as UTF-8:\n$msg\n" if $@;
1762 $log_entry{log} = $msg;
1764 close $log_fh or croak $!;
1771 my ($str, $file, $mode) = @_;
1772 open my $fd,'>',$file or croak $!;
1773 print $fd $str,"\n" or croak $!;
1774 close $fd or croak $!;
1775 chmod ($mode &~ umask, $file) if (defined $mode);
1780 open my $fd,'<',$file or croak "$!: file: $file\n";
1783 close $fd or croak $!;
1788 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1790 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1791 my $log = $cmd eq 'log';
1792 while (<$authors>) {
1794 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1795 my ($user, $name, $email) = ($1, $2, $3);
1797 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1799 $users{$user} = [$name, $email];
1802 close $authors or croak $!;
1805 # convert GetOpt::Long specs for use by git-config
1806 sub read_git_config {
1809 foreach my $o (keys %$opts) {
1810 # if we have mixedCase and a long option-only, then
1811 # it's a config-only variable that we don't need for
1813 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1814 my $v = $opts->{$o};
1815 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1817 my $arg = 'git config';
1818 $arg .= ' --int' if ($o =~ /[:=]i$/);
1819 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1820 if (ref $v eq 'ARRAY') {
1821 chomp(my @tmp = `$arg --get-all svn.$key`);
1824 chomp(my $tmp = `$arg --get svn.$key`);
1825 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1830 delete @$opts{@config_only} if @config_only;
1833 sub extract_metadata {
1834 my $id = shift or return (undef, undef, undef);
1835 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1836 \s([a-f\d\-]+)$/ix);
1837 if (!defined $rev || !$uuid || !$url) {
1838 # some of the original repositories I made had
1839 # identifiers like this:
1840 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1842 return ($url, $rev, $uuid);
1846 return extract_metadata((grep(/^git-svn-id: /,
1847 command(qw/cat-file commit/, shift)))[-1]);
1850 sub cmt_sha2rev_batch {
1852 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1855 foreach my $sha (@{$list}) {
1858 print $out $sha, "\n";
1860 while (my $line = <$in>) {
1861 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1864 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1868 } elsif ($line =~ /^(git-svn-id: )/) {
1869 my (undef, $rev, undef) =
1870 extract_metadata($line);
1874 $size -= length($line);
1875 last if ($size == 0);
1879 command_close_bidi_pipe($pid, $in, $out, $ctx);
1884 sub working_head_info {
1885 my ($head, $refs) = @_;
1886 my @args = qw/rev-list --first-parent --pretty=medium/;
1887 my ($fh, $ctx) = command_output_pipe(@args, $head);
1891 if ( m{^commit ($::sha1)$} ) {
1892 unshift @$refs, $hash if $hash and $refs;
1896 next unless s{^\s*(git-svn-id:)}{$1};
1897 my ($url, $rev, $uuid) = extract_metadata($_);
1898 if (defined $url && defined $rev) {
1899 next if $max{$url} and $max{$url} < $rev;
1900 if (my $gs = Git::SVN->find_by_url($url)) {
1901 my $c = $gs->rev_map_get($rev, $uuid);
1902 if ($c && $c eq $hash) {
1903 close $fh; # break the pipe
1904 return ($url, $rev, $uuid, $gs);
1906 $max{$url} ||= $gs->rev_map_max;
1911 command_close_pipe($fh, $ctx);
1912 (undef, undef, undef, undef);
1915 sub read_commit_parents {
1916 my ($parents, $c) = @_;
1917 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1918 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1919 @{$parents->{$c}} = split(/ /, $p);
1922 sub linearize_history {
1923 my ($gs, $refs) = @_;
1925 foreach my $c (@$refs) {
1926 read_commit_parents(\%parents, $c);
1931 my $last_svn_commit = $gs->last_commit;
1932 foreach my $c (reverse @$refs) {
1933 next if $c eq $last_svn_commit;
1936 unshift @linear_refs, $c;
1939 # we only want the first parent to diff against for linear
1940 # history, we save the rest to inject when we finalize the
1942 my $fp_a = verify_ref("$c~1");
1943 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1944 if (!$fp_a || !$fp_b) {
1946 "has no parent commit, and therefore ",
1947 "nothing to diff against.\n",
1948 "You should be working from a repository ",
1949 "originally created by git-svn\n";
1951 if ($fp_a ne $fp_b) {
1952 die "$c~1 = $fp_a, however parsing commit $c ",
1953 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1956 foreach my $p (@{$parents{$c}}) {
1960 (\@linear_refs, \%parents);
1963 sub find_file_type_and_diff_status {
1965 return ('dir', '') if $path eq '';
1968 command_oneline(qw(diff --cached --name-status --), $path) || "";
1969 my $diff_status = (split(' ', $diff_output))[0] || "";
1971 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1973 return (undef, undef) if !$diff_status && !$ls_tree;
1975 if ($diff_status eq "A") {
1976 return ("link", $diff_status) if -l $path;
1977 return ("dir", $diff_status) if -d $path;
1978 return ("file", $diff_status);
1981 my $mode = (split(' ', $ls_tree))[0] || "";
1983 return ("link", $diff_status) if $mode eq "120000";
1984 return ("dir", $diff_status) if $mode eq "040000";
1985 return ("file", $diff_status);
1991 my $md5 = Digest::MD5->new();
1992 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1993 $md5->addfile($arg) or croak $!;
1994 } elsif ($ref eq 'SCALAR') {
1995 $md5->add($$arg) or croak $!;
1997 $md5->add($arg) or croak $!;
1999 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2001 return $md5->hexdigest();
2005 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2006 my $out_filename = $_ . ".gz";
2007 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2009 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2010 die "Unable to open $out_filename: $!\n";
2013 while ($res = sysread($in_fh, my $str, 1024)) {
2014 $gz->gzwrite($str) or
2015 die "Unable to write: ".$gz->gzerror()."!\n";
2017 unlink $_ or die "unlink $File::Find::name: $!\n";
2018 } elsif (-f $_ && basename($_) eq "index") {
2019 unlink $_ or die "unlink $_: $!\n";
2026 use Fcntl qw/:DEFAULT :seek/;
2027 use constant rev_map_fmt => 'NH40';
2028 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2029 $_repack $_repack_flags $_use_svm_props $_head
2030 $_use_svnsync_props $no_reuse_existing $_minimize_url
2031 $_use_log_author $_add_author_from $_localtime/;
2033 use File::Path qw/mkpath/;
2034 use File::Copy qw/copy/;
2037 use Memoize; # core since 5.8.0, Jul 2002
2038 use Memoize::Storable;
2039 use POSIX qw(:signal_h);
2041 my ($_gc_nr, $_gc_period);
2043 # properties that we do not log:
2046 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2047 svn:special svn:executable
2048 svn:entry:committed-rev
2049 svn:entry:last-author
2051 svn:entry:committed-date/;
2053 # some options are read globally, but can be overridden locally
2054 # per [svn-remote "..."] section. Command-line options will *NOT*
2055 # override options set in an [svn-remote "..."] section
2057 for my $option (qw/follow_parent no_metadata use_svm_props
2058 use_svnsync_props/) {
2061 my $prop = "-$option";
2064 return $self->{$prop} if exists $self->{$prop};
2065 my $k = "svn-remote.$self->{repo_id}.$key";
2066 eval { command_oneline(qw/config --get/, $k) };
2068 $self->{$prop} = ${"Git::SVN::_$option"};
2070 my $v = command_oneline(qw/config --bool/,$k);
2071 $self->{$prop} = $v eq 'false' ? 0 : 1;
2073 return $self->{$prop};
2079 my (%LOCKFILES, %INDEX_FILES);
2081 unlink keys %LOCKFILES if %LOCKFILES;
2082 unlink keys %INDEX_FILES if %INDEX_FILES;
2085 sub resolve_local_globs {
2086 my ($url, $fetch, $glob_spec) = @_;
2087 return unless defined $glob_spec;
2088 my $ref = $glob_spec->{ref};
2089 my $path = $glob_spec->{path};
2090 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2091 next unless m#^$ref->{regex}$#;
2093 my $pathname = desanitize_refname($path->full_path($p));
2094 my $refname = desanitize_refname($ref->full_path($p));
2095 if (my $existing = $fetch->{$pathname}) {
2096 if ($existing ne $refname) {
2097 die "Refspec conflict:\n",
2098 "existing: $existing\n",
2099 " globbed: $refname\n";
2101 my $u = (::cmt_metadata("$refname"))[0];
2102 $u =~ s!^\Q$url\E(/|$)!! or die
2103 "$refname: '$url' not found in '$u'\n";
2104 if ($pathname ne $u) {
2105 warn "W: Refspec glob conflict ",
2106 "(ref: $refname):\n",
2107 "expected path: $pathname\n",
2109 "Continuing ahead with $u\n";
2113 $fetch->{$pathname} = $refname;
2118 sub parse_revision_argument {
2119 my ($base, $head) = @_;
2120 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2121 return ($base, $head);
2123 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2124 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2125 return ($head, $head) if ($::_revision eq 'HEAD');
2126 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2127 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2128 die "revision argument: $::_revision not understood by git-svn\n";
2132 my ($repo_id, $remotes) = @_;
2136 $repo_id = $gs->{repo_id};
2138 $remotes ||= read_all_remotes();
2139 my $remote = $remotes->{$repo_id} or
2140 die "[svn-remote \"$repo_id\"] unknown\n";
2141 my $fetch = $remote->{fetch};
2142 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2144 my $ra = Git::SVN::Ra->new($url);
2145 my $uuid = $ra->get_uuid;
2146 my $head = $ra->get_latest_revnum;
2148 # ignore errors, $head revision may not even exist anymore
2149 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2150 warn "W: $@\n" if $@;
2152 my $base = defined $fetch ? $head : 0;
2154 # read the max revs for wildcard expansion (branches/*, tags/*)
2155 foreach my $t (qw/branches tags/) {
2156 defined $remote->{$t} or next;
2157 push @globs, @{$remote->{$t}};
2159 my $max_rev = eval { tmp_config(qw/--int --get/,
2160 "svn-remote.$repo_id.${t}-maxRev") };
2161 if (defined $max_rev && ($max_rev < $base)) {
2163 } elsif (!defined $max_rev) {
2169 foreach my $p (sort keys %$fetch) {
2170 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2171 my $lr = $gs->rev_map_max;
2173 $base = $lr if ($lr < $base);
2179 ($base, $head) = parse_revision_argument($base, $head);
2180 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2183 sub read_all_remotes {
2185 my $use_svm_props = eval { command_oneline(qw/config --bool
2186 svn.useSvmProps/) };
2187 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2188 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2189 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2190 if (m!^(.+)\.fetch=$svn_refspec$!) {
2191 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2192 die("svn-remote.$remote: remote ref '$remote_ref' "
2193 . "must start with 'refs/'\n")
2194 unless $remote_ref =~ m{^refs/};
2195 $local_ref = uri_decode($local_ref);
2196 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2197 $r->{$remote}->{svm} = {} if $use_svm_props;
2198 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2199 $r->{$1}->{svm} = {};
2200 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2201 $r->{$1}->{url} = $2;
2202 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2203 $r->{$1}->{pushurl} = $2;
2204 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2205 $r->{$1}->{ignore_refs_regex} = $2;
2206 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2207 my ($remote, $t, $local_ref, $remote_ref) =
2209 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2210 . "must start with 'refs/'\n")
2211 unless $remote_ref =~ m{^refs/};
2212 $local_ref = uri_decode($local_ref);
2216 path => Git::SVN::GlobSpec->new($local_ref, 1),
2217 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2218 if (length($rs->{ref}->{right}) != 0) {
2219 die "The '*' glob character must be the last ",
2220 "character of '$remote_ref'\n";
2222 push @{ $r->{$remote}->{$t} }, $rs;
2227 if (defined $r->{$_}->{svm}) {
2230 my $section = "svn-remote.$_";
2232 source => tmp_config('--get',
2233 "$section.svm-source"),
2234 replace => tmp_config('--get',
2235 "$section.svm-replace"),
2238 $r->{$_}->{svm} = $svm;
2242 foreach my $remote (keys %$r) {
2243 foreach ( grep { defined $_ }
2244 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2245 foreach my $rs ( @$_ ) {
2246 $rs->{ignore_refs_regex} =
2247 $r->{$remote}->{ignore_refs_regex};
2256 $_gc_nr = $_gc_period = 1000;
2257 if (defined $_repack || defined $_repack_flags) {
2258 warn "Repack options are obsolete; they have no effect.\n";
2262 sub verify_remotes_sanity {
2263 return unless -d $ENV{GIT_DIR};
2265 foreach (command(qw/config -l/)) {
2266 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2268 die "Remote ref refs/remote/$1 is tracked by",
2269 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2270 "Please resolve this ambiguity in ",
2271 "your git configuration file before ",
2279 sub find_existing_remote {
2280 my ($url, $remotes) = @_;
2281 return undef if $no_reuse_existing;
2283 foreach my $repo_id (keys %$remotes) {
2284 my $u = $remotes->{$repo_id}->{url} or next;
2286 $existing = $repo_id;
2292 sub init_remote_config {
2293 my ($self, $url, $no_write) = @_;
2294 $url =~ s!/+$!!; # strip trailing slash
2295 my $r = read_all_remotes();
2296 my $existing = find_existing_remote($url, $r);
2298 unless ($no_write) {
2299 print STDERR "Using existing ",
2300 "[svn-remote \"$existing\"]\n";
2302 $self->{repo_id} = $existing;
2303 } elsif ($_minimize_url) {
2304 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2305 $existing = find_existing_remote($min_url, $r);
2307 unless ($no_write) {
2308 print STDERR "Using existing ",
2309 "[svn-remote \"$existing\"]\n";
2311 $self->{repo_id} = $existing;
2313 if ($min_url ne $url) {
2314 unless ($no_write) {
2315 print STDERR "Using higher level of URL: ",
2316 "$url => $min_url\n";
2318 my $old_path = $self->{path};
2319 $self->{path} = $url;
2320 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2321 if (length $old_path) {
2322 $self->{path} .= "/$old_path";
2329 # verify that we aren't overwriting anything:
2331 command_oneline('config', '--get',
2332 "svn-remote.$self->{repo_id}.url")
2334 if ($orig_url && ($orig_url ne $url)) {
2335 die "svn-remote.$self->{repo_id}.url already set: ",
2336 "$orig_url\nwanted to set to: $url\n";
2339 my ($xrepo_id, $xpath) = find_ref($self->refname);
2340 if (!$no_write && defined $xpath) {
2341 die "svn-remote.$xrepo_id.fetch already set to track ",
2342 "$xpath:", $self->refname, "\n";
2344 unless ($no_write) {
2345 command_noisy('config',
2346 "svn-remote.$self->{repo_id}.url", $url);
2347 $self->{path} =~ s{^/}{};
2348 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2349 command_noisy('config', '--add',
2350 "svn-remote.$self->{repo_id}.fetch",
2351 "$self->{path}:".$self->refname);
2353 $self->{url} = $url;
2356 sub find_by_url { # repos_root and, path are optional
2357 my ($class, $full_url, $repos_root, $path) = @_;
2359 return undef unless defined $full_url;
2360 remove_username($full_url);
2361 remove_username($repos_root) if defined $repos_root;
2362 my $remotes = read_all_remotes();
2363 if (defined $full_url && defined $repos_root && !defined $path) {
2365 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2367 foreach my $repo_id (keys %$remotes) {
2368 my $u = $remotes->{$repo_id}->{url} or next;
2369 remove_username($u);
2370 next if defined $repos_root && $repos_root ne $u;
2372 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2373 foreach my $t (qw/branches tags/) {
2374 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2375 resolve_local_globs($u, $fetch, $globspec);
2379 my $rwr = rewrite_root({repo_id => $repo_id});
2380 my $svm = $remotes->{$repo_id}->{svm}
2381 if defined $remotes->{$repo_id}->{svm};
2382 unless (defined $p) {
2388 remove_username($z);
2389 } elsif (defined $svm) {
2390 $z = $svm->{source};
2391 $prefix = $svm->{replace};
2392 $prefix =~ s#^\Q$u\E(?:/|$)##;
2395 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2397 foreach my $f (keys %$fetch) {
2399 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2406 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2407 my $self = _new($class, $repo_id, $ref_id, $path);
2409 $self->init_remote_config($url, $no_write);
2416 foreach (command(qw/config -l/)) {
2417 next unless m!^svn-remote\.(.+)\.fetch=
2418 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2419 my ($repo_id, $path, $ref) = ($1, $2, $3);
2420 if ($ref eq $ref_id) {
2421 $path = '' if ($path =~ m#^\./?#);
2422 return ($repo_id, $path);
2425 (undef, undef, undef);
2429 my ($class, $ref_id, $repo_id, $path) = @_;
2430 if (defined $ref_id && !defined $repo_id && !defined $path) {
2431 ($repo_id, $path) = find_ref($ref_id);
2432 if (!defined $repo_id) {
2433 die "Could not find a \"svn-remote.*.fetch\" key ",
2434 "in the repository configuration matching: ",
2438 my $self = _new($class, $repo_id, $ref_id, $path);
2439 if (!defined $self->{path} || !length $self->{path}) {
2440 my $fetch = command_oneline('config', '--get',
2441 "svn-remote.$repo_id.fetch",
2443 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2444 "\":$ref_id\$\" in config\n";
2445 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2447 $self->{path} =~ s{/+}{/}g;
2448 $self->{path} =~ s{\A/}{};
2449 $self->{path} =~ s{/\z}{};
2450 $self->{url} = command_oneline('config', '--get',
2451 "svn-remote.$repo_id.url") or
2452 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2453 $self->{pushurl} = eval { command_oneline('config', '--get',
2454 "svn-remote.$repo_id.pushurl") };
2460 my ($refname) = $_[0]->{ref_id} ;
2462 # It cannot end with a slash /, we'll throw up on this because
2463 # SVN can't have directories with a slash in their name, either:
2464 if ($refname =~ m{/$}) {
2465 die "ref: '$refname' ends with a trailing slash, this is ",
2466 "not permitted by git nor Subversion\n";
2469 # It cannot have ASCII control character space, tilde ~, caret ^,
2470 # colon :, question-mark ?, asterisk *, space, or open bracket [
2473 # Additionally, % must be escaped because it is used for escaping
2474 # and we want our escaped refname to be reversible
2475 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2477 # no slash-separated component can begin with a dot .
2479 $refname =~ s{/\.}{/%2E}g;
2481 # It cannot have two consecutive dots .. anywhere
2483 $refname =~ s{\.\.}{%2E%2E}g;
2485 # trailing dots and .lock are not allowed
2486 # .$ becomes %2E and .lock becomes %2Elock
2487 $refname =~ s{\.(?=$|lock$)}{%2E};
2489 # the sequence @{ is used to access the reflog
2491 $refname =~ s{\@\{}{%40\{}g;
2496 sub desanitize_refname {
2498 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2504 return $self->{svm}->{uuid} if $self->svm;
2506 unless ($self->{svm}) {
2507 die "SVM UUID not cached, and reading remotely failed\n";
2509 $self->{svm}->{uuid};
2514 return $self->{svm} if $self->{svm};
2516 # see if we have it in our config, first:
2518 my $section = "svn-remote.$self->{repo_id}";
2520 source => tmp_config('--get', "$section.svm-source"),
2521 uuid => tmp_config('--get', "$section.svm-uuid"),
2522 replace => tmp_config('--get', "$section.svm-replace"),
2525 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2526 $self->{svm} = $svm;
2532 my ($self, $ra) = @_;
2533 return $ra if $self->svm;
2535 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2536 "(svm:source, svm:uuid) ",
2537 "from the following URLs:\n" );
2538 sub read_svm_props {
2539 my ($self, $ra, $path, $r) = @_;
2540 my $props = ($ra->get_dir($path, $r))[2];
2541 my $src = $props->{'svm:source'};
2542 my $uuid = $props->{'svm:uuid'};
2543 return undef if (!$src || !$uuid);
2547 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2548 or die "doesn't look right - svm:uuid is '$uuid'\n";
2550 # the '!' is used to mark the repos_root!/relative/path
2551 $src =~ s{/?!/?}{/};
2552 $src =~ s{/+$}{}; # no trailing slashes please
2553 # username is of no interest
2554 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2556 my $replace = $ra->{url};
2557 $replace .= "/$path" if length $path;
2559 my $section = "svn-remote.$self->{repo_id}";
2560 tmp_config("$section.svm-source", $src);
2561 tmp_config("$section.svm-replace", $replace);
2562 tmp_config("$section.svm-uuid", $uuid);
2570 my $r = $ra->get_latest_revnum;
2571 my $path = $self->{path};
2573 while (length $path) {
2574 unless ($tried{"$self->{url}/$path"}) {
2575 return $ra if $self->read_svm_props($ra, $path, $r);
2576 $tried{"$self->{url}/$path"} = 1;
2578 $path =~ s#/?[^/]+$##;
2580 die "Path: '$path' should be ''\n" if $path ne '';
2581 return $ra if $self->read_svm_props($ra, $path, $r);
2582 $tried{"$self->{url}/$path"} = 1;
2584 if ($ra->{repos_root} eq $self->{url}) {
2585 die @err, (map { " $_\n" } keys %tried), "\n";
2588 # nope, make sure we're connected to the repository root:
2591 $path = $ra->{svn_path};
2592 $ra = Git::SVN::Ra->new($ra->{repos_root});
2593 while (length $path) {
2594 unless ($tried{"$ra->{url}/$path"}) {
2595 $ok = $self->read_svm_props($ra, $path, $r);
2597 $tried{"$ra->{url}/$path"} = 1;
2599 $path =~ s#/?[^/]+$##;
2601 die "Path: '$path' should be ''\n" if $path ne '';
2602 $ok ||= $self->read_svm_props($ra, $path, $r);
2603 $tried{"$ra->{url}/$path"} = 1;
2605 die @err, (map { " $_\n" } keys %tried), "\n";
2607 Git::SVN::Ra->new($self->{url});
2612 return $self->{svnsync} if $self->{svnsync};
2614 if ($self->no_metadata) {
2615 die "Can't have both 'noMetadata' and ",
2616 "'useSvnsyncProps' options set!\n";
2618 if ($self->rewrite_root) {
2619 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2622 if ($self->rewrite_uuid) {
2623 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2628 # see if we have it in our config, first:
2630 my $section = "svn-remote.$self->{repo_id}";
2632 my $url = tmp_config('--get', "$section.svnsync-url");
2633 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2634 die "doesn't look right - svn:sync-from-url is '$url'\n";
2636 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2637 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2638 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2640 $svnsync = { url => $url, uuid => $uuid }
2642 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2643 return $self->{svnsync} = $svnsync;
2646 my $err = "useSvnsyncProps set, but failed to read " .
2647 "svnsync property: svn:sync-from-";
2648 my $rp = $self->ra->rev_proplist(0);
2650 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2651 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2652 die "doesn't look right - svn:sync-from-url is '$url'\n";
2654 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2655 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2656 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2658 my $section = "svn-remote.$self->{repo_id}";
2659 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2660 tmp_config('--add', "$section.svnsync-url", $url);
2661 return $self->{svnsync} = { url => $url, uuid => $uuid };
2664 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2665 # remote lookup (useful for 'git svn log').
2668 unless ($self->{ra_uuid}) {
2669 my $key = "svn-remote.$self->{repo_id}.uuid";
2670 my $uuid = eval { tmp_config('--get', $key) };
2671 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2672 $self->{ra_uuid} = $uuid;
2674 die "ra_uuid called without URL\n" unless $self->{url};
2675 $self->{ra_uuid} = $self->ra->get_uuid;
2676 tmp_config('--add', $key, $self->{ra_uuid});
2682 sub _set_repos_root {
2683 my ($self, $repos_root) = @_;
2684 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2685 $repos_root ||= $self->ra->{repos_root};
2686 tmp_config($k, $repos_root);
2692 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2693 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2698 my $ra = Git::SVN::Ra->new($self->{url});
2699 $self->_set_repos_root($ra->{repos_root});
2700 if ($self->use_svm_props && !$self->{svm}) {
2701 if ($self->no_metadata) {
2702 die "Can't have both 'noMetadata' and ",
2703 "'useSvmProps' options set!\n";
2704 } elsif ($self->use_svnsync_props) {
2705 die "Can't have both 'useSvnsyncProps' and ",
2706 "'useSvmProps' options set!\n";
2708 $ra = $self->_set_svm_vars($ra);
2709 $self->{-want_revprops} = 1;
2714 # prop_walk(PATH, REV, SUB)
2715 # -------------------------
2716 # Recursively traverse PATH at revision REV and invoke SUB for each
2717 # directory that contains a SVN property. SUB will be invoked as
2718 # follows: &SUB(gs, path, props); where `gs' is this instance of
2719 # Git::SVN, `path' the path to the directory where the properties
2720 # `props' were found. The `path' will be relative to point of checkout,
2721 # that is, if url://repo/trunk is the current Git branch, and that
2722 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2723 # as `path' (note the trailing `/').
2725 my ($self, $path, $rev, $sub) = @_;
2728 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2731 # Strip the irrelevant part of the path.
2732 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2733 # Ensure the path is terminated by a `/'.
2736 # The properties contain all the internal SVN stuff nobody
2737 # (usually) cares about.
2738 my $interesting_props = 0;
2739 foreach (keys %{$props}) {
2740 # If it doesn't start with `svn:', it must be a
2741 # user-defined property.
2742 ++$interesting_props and next if $_ !~ /^svn:/;
2743 # FIXME: Fragile, if SVN adds new public properties,
2744 # this needs to be updated.
2745 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2746 |eol-style|mime-type
2747 |externals|needs-lock)$/x;
2749 &$sub($self, $p, $props) if $interesting_props;
2751 foreach (sort keys %$dirent) {
2752 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2753 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2757 sub last_rev { ($_[0]->last_rev_commit)[0] }
2758 sub last_commit { ($_[0]->last_rev_commit)[1] }
2760 # returns the newest SVN revision number and newest commit SHA1
2761 sub last_rev_commit {
2763 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2764 return ($self->{last_rev}, $self->{last_commit});
2766 my $c = ::verify_ref($self->refname.'^0');
2767 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2768 my $rev = (::cmt_metadata($c))[1];
2770 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2774 my $map_path = $self->map_path;
2775 unless (-e $map_path) {
2776 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2777 return (undef, undef);
2779 my ($rev, $commit) = $self->rev_map_max(1);
2780 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2781 return ($rev, $commit);
2784 sub get_fetch_range {
2785 my ($self, $min, $max) = @_;
2786 $max ||= $self->ra->get_latest_revnum;
2787 $min ||= $self->rev_map_max;
2793 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2794 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2795 if (! -f $config && -f $old_def_config) {
2796 rename $old_def_config, $config or
2797 die "Failed rename $old_def_config => $config: $!\n";
2799 my $old_config = $ENV{GIT_CONFIG};
2800 $ENV{GIT_CONFIG} = $config;
2803 unless (-f $config) {
2805 open my $fh, '>', $config or
2806 die "Can't open $config: $!\n";
2807 print $fh "; This file is used internally by ",
2809 "Couldn't write to $config: $!\n";
2810 print $fh "; You should not have to edit it\n" or
2811 die "Couldn't write to $config: $!\n";
2812 close $fh or die "Couldn't close $config: $!\n";
2814 command('config', @args);
2817 if (defined $old_config) {
2818 $ENV{GIT_CONFIG} = $old_config;
2820 delete $ENV{GIT_CONFIG};
2823 wantarray ? @ret : $ret[0];
2827 my ($self, $sub) = @_;
2828 my $old_index = $ENV{GIT_INDEX_FILE};
2829 $ENV{GIT_INDEX_FILE} = $self->{index};
2832 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2833 mkpath([$dir]) unless -d $dir;
2837 if (defined $old_index) {
2838 $ENV{GIT_INDEX_FILE} = $old_index;
2840 delete $ENV{GIT_INDEX_FILE};
2843 wantarray ? @ret : $ret[0];
2846 sub assert_index_clean {
2847 my ($self, $treeish) = @_;
2849 $self->tmp_index_do(sub {
2850 command_noisy('read-tree', $treeish) unless -e $self->{index};
2851 my $x = command_oneline('write-tree');
2852 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2853 /^tree ($::sha1)/mo);
2856 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2857 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2858 command_noisy('read-tree', $treeish);
2859 $x = command_oneline('write-tree');
2861 ::fatal "trees ($treeish) $y != $x\n",
2862 "Something is seriously wrong...";
2867 sub get_commit_parents {
2868 my ($self, $log_entry) = @_;
2869 my (%seen, @ret, @tmp);
2870 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2871 if (my $ip = $self->{inject_parents}) {
2872 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2876 if (my $cur = ::verify_ref($self->refname.'^0')) {
2879 if (my $ipd = $self->{inject_parents_dcommit}) {
2880 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2881 push @tmp, @$commit;
2884 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2885 while (my $p = shift @tmp) {
2895 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2896 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2897 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2900 if ($rwr !~ m#^[a-z\+]+://#) {
2901 die "$rwr is not a valid URL (key: $k)\n";
2904 $self->{-rewrite_root} = $rwr;
2909 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2910 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2911 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2914 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2915 die "$rwid is not a valid UUID (key: $k)\n";
2918 $self->{-rewrite_uuid} = $rwid;
2923 ($self->rewrite_root || $self->{url}) .
2924 (length $self->{path} ? '/' . $self->{path} : '');
2929 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2934 if ($self->{pushurl}) {
2935 return $self->{pushurl} . (length $self->{path} ? '/' .
2936 $self->{path} : '');
2938 return $self->full_url;
2942 sub set_commit_header_env {
2943 my ($log_entry) = @_;
2945 foreach my $ned (qw/NAME EMAIL DATE/) {
2946 foreach my $ac (qw/AUTHOR COMMITTER/) {
2947 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2951 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2952 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2953 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2955 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2956 ? $log_entry->{commit_name}
2957 : $log_entry->{name};
2958 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2959 ? $log_entry->{commit_email}
2960 : $log_entry->{email};
2964 sub restore_commit_header_env {
2966 foreach my $ned (qw/NAME EMAIL DATE/) {
2967 foreach my $ac (qw/AUTHOR COMMITTER/) {
2968 my $k = "GIT_${ac}_${ned}";
2969 if (defined $env->{$k}) {
2970 $ENV{$k} = $env->{$k};
2979 command_noisy('gc', '--auto');
2983 my ($self, $log_entry) = @_;
2984 my $lr = $self->last_rev;
2985 if (defined $lr && $lr >= $log_entry->{revision}) {
2986 die "Last fetched revision of ", $self->refname,
2987 " was r$lr, but we are about to fetch: ",
2988 "r$log_entry->{revision}!\n";
2990 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2991 croak "$log_entry->{revision} = $c already exists! ",
2992 "Why are we refetching it?\n";
2994 my $old_env = set_commit_header_env($log_entry);
2995 my $tree = $log_entry->{tree};
2996 if (!defined $tree) {
2997 $tree = $self->tmp_index_do(sub {
2998 command_oneline('write-tree') });
3000 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3002 my @exec = ('git', 'commit-tree', $tree);
3003 foreach ($self->get_commit_parents($log_entry)) {
3004 push @exec, '-p', $_;
3006 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3010 # we always get UTF-8 from SVN, but we may want our commits in
3011 # a different encoding.
3012 if (my $enc = Git::config('i18n.commitencoding')) {
3014 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3016 print $msg_fh $log_entry->{log} or croak $!;
3017 restore_commit_header_env($old_env);
3018 unless ($self->no_metadata) {
3019 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3022 $msg_fh->flush == 0 or croak $!;
3023 close $msg_fh or croak $!;
3024 chomp(my $commit = do { local $/; <$out_fh> });
3025 close $out_fh or croak $!;
3028 if ($commit !~ /^$::sha1$/o) {
3029 die "Failed to commit, invalid sha1: $commit\n";
3032 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3034 $self->{last_rev} = $log_entry->{revision};
3035 $self->{last_commit} = $commit;
3036 print "r$log_entry->{revision}" unless $::_q > 1;
3037 if (defined $log_entry->{svm_revision}) {
3038 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3039 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3040 0, $self->svm_uuid);
3042 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3043 if (--$_gc_nr == 0) {
3044 $_gc_nr = $_gc_period;
3051 my ($self, $paths, $r) = @_;
3052 return 1 if $self->{path} eq '';
3053 if (my $path = $paths->{"/$self->{path}"}) {
3054 return ($path->{action} eq 'D') ? 0 : 1;
3056 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3057 if (grep /$self->{path_regex}/, keys %$paths) {
3061 foreach (split m#/#, $self->{path}) {
3063 next unless ($paths->{$c} &&
3064 ($paths->{$c}->{action} =~ /^[AR]$/));
3065 if ($self->ra->check_path($self->{path}, $r) ==
3073 sub find_parent_branch {
3074 my ($self, $paths, $rev) = @_;
3075 return undef unless $self->follow_parent;
3076 unless (defined $paths) {
3077 my $err_handler = $SVN::Error::handler;
3078 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3079 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3080 sub { $paths = $_[0] });
3081 $SVN::Error::handler = $err_handler;
3083 return undef unless defined $paths;
3085 # look for a parent from another branch:
3086 my @b_path_components = split m#/#, $self->{path};
3087 my @a_path_components;
3089 while (@b_path_components) {
3090 $i = $paths->{'/'.join('/', @b_path_components)};
3091 last if $i && defined $i->{copyfrom_path};
3092 unshift(@a_path_components, pop(@b_path_components));
3094 return undef unless defined $i && defined $i->{copyfrom_path};
3095 my $branch_from = $i->{copyfrom_path};
3096 if (@a_path_components) {
3097 print STDERR "branch_from: $branch_from => ";
3098 $branch_from .= '/'.join('/', @a_path_components);
3099 print STDERR $branch_from, "\n";
3101 my $r = $i->{copyfrom_rev};
3102 my $repos_root = $self->ra->{repos_root};
3103 my $url = $self->ra->{url};
3104 my $new_url = $url . $branch_from;
3105 print STDERR "Found possible branch point: ",
3106 "$new_url => ", $self->full_url, ", $r\n"
3108 $branch_from =~ s#^/##;
3109 my $gs = $self->other_gs($new_url, $url,
3110 $branch_from, $r, $self->{ref_id});
3111 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3114 if (!defined $r0 || !defined $parent) {
3115 ($base, $head) = parse_revision_argument(0, $r);
3118 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3119 0, 1, sub { $base = $_[1] - 1 });
3122 if (defined $base && $base <= $r) {
3123 $gs->fetch($base, $r);
3125 ($r0, $parent) = $gs->find_rev_before($r, 1);
3127 if (defined $r0 && defined $parent) {
3128 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3131 if ($self->ra->can_do_switch) {
3132 $self->assert_index_clean($parent);
3133 print STDERR "Following parent with do_switch\n"
3135 # do_switch works with svn/trunk >= r22312, but that
3136 # is not included with SVN 1.4.3 (the latest version
3137 # at the moment), so we can't rely on it
3138 $self->{last_rev} = $r0;
3139 $self->{last_commit} = $parent;
3140 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3141 $gs->ra->gs_do_switch($r0, $rev, $gs,
3142 $self->full_url, $ed)
3143 or die "SVN connection failed somewhere...\n";
3144 } elsif ($self->ra->trees_match($new_url, $r0,
3145 $self->full_url, $rev)) {
3146 print STDERR "Trees match:\n",
3148 " ${\$self->full_url}\@$rev\n",
3149 "Following parent with no changes\n"
3151 $self->tmp_index_do(sub {
3152 command_noisy('read-tree', $parent);
3154 $self->{last_commit} = $parent;
3156 print STDERR "Following parent with do_update\n"
3158 $ed = SVN::Git::Fetcher->new($self);
3159 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3160 or die "SVN connection failed somewhere...\n";
3162 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3163 return $self->make_log_entry($rev, [$parent], $ed);
3169 my ($self, $paths, $rev) = @_;
3171 my ($last_rev, @parents);
3172 if (my $lc = $self->last_commit) {
3173 # we can have a branch that was deleted, then re-added
3174 # under the same name but copied from another path, in
3175 # which case we'll have multiple parents (we don't
3176 # want to break the original ref, nor lose copypath info):
3177 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3178 push @{$log_entry->{parents}}, $lc;
3181 $ed = SVN::Git::Fetcher->new($self);
3182 $last_rev = $self->{last_rev};
3187 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3190 $ed = SVN::Git::Fetcher->new($self);
3192 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3193 die "SVN connection failed somewhere...\n";
3195 $self->make_log_entry($rev, \@parents, $ed);
3199 my ($self, $r) = @_;
3202 my ($r, $empty_dirs, $line) = @_;
3203 if (defined $r && $line =~ /^r(\d+)$/) {
3204 return 0 if $1 > $r;
3205 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3206 $empty_dirs->{$1} = 1;
3207 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3208 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3209 delete @$empty_dirs{@d};
3214 my %empty_dirs = ();
3215 my $gz_file = "$self->{dir}/unhandled.log.gz";
3217 if (!$can_compress) {
3218 warn "Compress::Zlib could not be found; ",
3219 "empty directories in $gz_file will not be read\n";
3221 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3222 die "Unable to open $gz_file: $!\n";
3224 while ($gz->gzreadline($line) > 0) {
3225 scan($r, \%empty_dirs, $line) or last;
3231 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3232 binmode $fh or croak "binmode: $!";
3234 scan($r, \%empty_dirs, $_) or last;
3239 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3240 foreach my $d (sort keys %empty_dirs) {
3241 $d = uri_decode($d);
3243 next unless length($d);
3246 warn "$d exists but is not a directory\n";
3248 print "creating empty directory: $d\n";
3255 my ($self, $ed) = @_;
3257 my $h = $ed->{empty};
3258 foreach (sort keys %$h) {
3259 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3260 push @out, " $act: " . uri_encode($_);
3261 warn "W: $act: $_\n";
3263 foreach my $t (qw/dir_prop file_prop/) {
3264 $h = $ed->{$t} or next;
3265 foreach my $path (sort keys %$h) {
3266 my $ppath = $path eq '' ? '.' : $path;
3267 foreach my $prop (sort keys %{$h->{$path}}) {
3268 next if $SKIP_PROP{$prop};
3269 my $v = $h->{$path}->{$prop};
3270 my $t_ppath_prop = "$t: " .
3271 uri_encode($ppath) . ' ' .
3274 push @out, " +$t_ppath_prop " .
3277 push @out, " -$t_ppath_prop";
3282 foreach my $t (qw/absent_file absent_directory/) {
3283 $h = $ed->{$t} or next;
3284 foreach my $parent (sort keys %$h) {
3285 foreach my $path (sort @{$h->{$parent}}) {
3286 push @out, " $t: " .
3287 uri_encode("$parent/$path");
3288 warn "W: $t: $parent/$path ",
3289 "Insufficient permissions?\n";
3297 # some systmes don't handle or mishandle %z, so be creative.
3298 my $t = shift || time;
3299 my $gm = timelocal(gmtime($t));
3300 my $sign = qw( + + - )[ $t <=> $gm ];
3301 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3304 # parse_svn_date(DATE)
3305 # --------------------
3306 # Given a date (in UTC) from Subversion, return a string in the format
3307 # "<TZ Offset> <local date/time>" that Git will use.
3309 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3310 # is true we'll convert it to the local timezone instead.
3311 sub parse_svn_date {
3312 my $date = shift || return '+0000 1970-01-01 00:00:00';
3313 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3314 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3315 croak "Unable to parse date: $date\n";
3316 my $parsed_date; # Set next.
3318 if ($Git::SVN::_localtime) {
3319 # Translate the Subversion datetime to an epoch time.
3320 # Begin by switching ourselves to $date's timezone, UTC.
3321 my $old_env_TZ = $ENV{TZ};
3325 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3327 # Determine our local timezone (including DST) at the
3328 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3329 # value of TZ, if any, at the time we were run.
3330 if (defined $Git::SVN::Log::TZ) {
3331 $ENV{TZ} = $Git::SVN::Log::TZ;
3336 my $our_TZ = get_tz();
3338 # This converts $epoch_in_UTC into our local timezone.
3339 my ($sec, $min, $hour, $mday, $mon, $year,
3340 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3342 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3343 $our_TZ, $year + 1900, $mon + 1,
3344 $mday, $hour, $min, $sec);
3346 # Reset us to the timezone in effect when we entered
3348 if (defined $old_env_TZ) {
3349 $ENV{TZ} = $old_env_TZ;
3354 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3357 return $parsed_date;
3361 my ($self, $new_url, $url,
3362 $branch_from, $r, $old_ref_id) = @_;
3363 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3365 my $ref_id = $old_ref_id;
3366 $ref_id =~ s/\@\d+-*$//;
3368 # just grow a tail if we're not unique enough :x
3369 $ref_id .= '-' while find_ref($ref_id);
3370 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3371 if ($u =~ s#^\Q$url\E(/|$)##) {
3374 $repo_id = $self->{repo_id};
3377 # It is possible to tag two different subdirectories at
3378 # the same revision. If the url for an existing ref
3379 # does not match, we must either find a ref with a
3380 # matching url or create a new ref by growing a tail.
3381 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3382 my (undef, $max_commit) = $gs->rev_map_max(1);
3383 last if (!$max_commit);
3384 my ($url) = ::cmt_metadata($max_commit);
3385 last if ($url eq $gs->metadata_url);
3388 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3393 sub call_authors_prog {
3394 my ($orig_author) = @_;
3395 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3396 my $author = `$::_authors_prog $orig_author`;
3398 die "$::_authors_prog failed with exit code $?\n"
3400 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3401 my ($name, $email) = ($1, $2);
3402 $email = undef if length $2 == 0;
3403 return [$name, $email];
3405 die "Author: $orig_author: $::_authors_prog returned "
3406 . "invalid author format: $author\n";
3412 if (!defined $author || length $author == 0) {
3413 $author = '(no author)';
3415 if (!defined $::users{$author}) {
3416 if (defined $::_authors_prog) {
3417 $::users{$author} = call_authors_prog($author);
3418 } elsif (defined $::_authors) {
3419 die "Author: $author not defined in $::_authors file\n";
3425 sub find_extra_svk_parents {
3426 my ($self, $ed, $tickets, $parents) = @_;
3427 # aha! svk:merge property changed...
3428 my @tickets = split "\n", $tickets;
3430 for my $ticket ( @tickets ) {
3431 my ($uuid, $path, $rev) = split /:/, $ticket;
3432 if ( $uuid eq $self->ra_uuid ) {
3433 my $url = $self->{url};
3434 my $repos_root = $url;
3435 my $branch_from = $path;
3436 $branch_from =~ s{^/}{};
3437 my $gs = $self->other_gs($repos_root."/".$branch_from,
3442 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3443 # wahey! we found it, but it might be
3445 push @known_parents, [ $rev, $commit ];
3449 # Ordering matters; highest-numbered commit merge tickets
3450 # first, as they may account for later merge ticket additions
3452 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3453 for my $parent ( @known_parents ) {
3454 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3455 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3457 while ( <$msg_fh> ) {
3460 command_close_pipe($msg_fh, $ctx);
3463 "Found merge parent (svk:merge ticket): $parent\n";
3464 push @$parents, $parent;
3469 sub lookup_svn_merge {
3474 my ($source, $revs) = split ":", $merge;
3477 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3479 warn "Couldn't find revmap for $url$source\n";
3482 my @ranges = split ",", $revs;
3483 my ($tip, $tip_commit);
3484 my @merged_commit_ranges;
3486 for my $range ( @ranges ) {
3487 my ($bottom, $top) = split "-", $range;
3489 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3490 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3492 unless ($top_commit and $bottom_commit) {
3493 warn "W:unknown path/rev in svn:mergeinfo "
3494 ."dirprop: $source:$range\n";
3498 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3499 push @merged_commit_ranges,
3500 "$bottom_commit^..$top_commit";
3502 push @merged_commit_ranges, "$top_commit";
3505 if ( !defined $tip or $top > $tip ) {
3507 $tip_commit = $top_commit;
3510 return ($tip_commit, @merged_commit_ranges);
3514 my ($msg_fh, $ctx) = command_output_pipe(
3518 while ( <$msg_fh> ) {
3522 command_close_pipe($msg_fh, $ctx);
3526 sub check_cherry_pick {
3529 my $parents = shift;
3531 my %commits = map { $_ => 1 }
3532 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3533 for my $range ( @ranges ) {
3534 delete @commits{_rev_list($range, "--")};
3536 for my $commit (keys %commits) {
3537 if (has_no_changes($commit)) {
3538 delete $commits{$commit};
3541 return (keys %commits);
3544 sub has_no_changes {
3547 my @revs = split / /, command_oneline(
3548 qw(rev-list --parents -1 -m), $commit);
3550 # Commits with no parents, e.g. the start of a partial branch,
3551 # have changes by definition.
3552 return 1 if (@revs < 2);
3554 # Commits with multiple parents, e.g a merge, have no changes
3556 return 0 if (@revs > 2);
3558 return (command_oneline("rev-parse", "$commit^{tree}") eq
3559 command_oneline("rev-parse", "$commit~1^{tree}"));
3562 # The GIT_DIR environment variable is not always set until after the command
3563 # line arguments are processed, so we can't memoize in a BEGIN block.
3567 sub memoize_svn_mergeinfo_functions {
3568 return if $memoized;
3571 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3572 mkpath([$cache_path]) unless -d $cache_path;
3574 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3575 "$cache_path/lookup_svn_merge.db", 'nstore';
3576 memoize 'lookup_svn_merge',
3577 SCALAR_CACHE => 'FAULT',
3578 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3581 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3582 "$cache_path/check_cherry_pick.db", 'nstore';
3583 memoize 'check_cherry_pick',
3584 SCALAR_CACHE => 'FAULT',
3585 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3588 tie my %has_no_changes_cache => 'Memoize::Storable',
3589 "$cache_path/has_no_changes.db", 'nstore';
3590 memoize 'has_no_changes',
3591 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3592 LIST_CACHE => 'FAULT',
3596 sub unmemoize_svn_mergeinfo_functions {
3597 return if not $memoized;
3600 Memoize::unmemoize 'lookup_svn_merge';
3601 Memoize::unmemoize 'check_cherry_pick';
3602 Memoize::unmemoize 'has_no_changes';
3605 Memoize::memoize 'Git::SVN::repos_root';
3609 # Force cache writeout explicitly instead of waiting for
3610 # global destruction to avoid segfault in Storable:
3611 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3612 unmemoize_svn_mergeinfo_functions();
3615 sub parents_exclude {
3616 my $parents = shift;
3618 return unless @commits;
3623 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3624 $excluded = command_oneline(@cmd);
3628 for my $commit ( @commits ) {
3629 if ( $commit eq $excluded ) {
3630 push @excluded, $commit;
3638 die "saw commit '$excluded' in rev-list output, "
3639 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3644 while ($excluded and @commits);
3650 # note: this function should only be called if the various dirprops
3651 # have actually changed
3652 sub find_extra_svn_parents {
3653 my ($self, $ed, $mergeinfo, $parents) = @_;
3654 # aha! svk:merge property changed...
3656 memoize_svn_mergeinfo_functions();
3658 # We first search for merged tips which are not in our
3659 # history. Then, we figure out which git revisions are in
3660 # that tip, but not this revision. If all of those revisions
3661 # are now marked as merge, we can add the tip as a parent.
3662 my @merges = split "\n", $mergeinfo;
3664 my $url = $self->{url};
3665 my $uuid = $self->ra_uuid;
3667 for my $merge ( @merges ) {
3668 my ($tip_commit, @ranges) =
3669 lookup_svn_merge( $uuid, $url, $merge );
3670 unless (!$tip_commit or
3671 grep { $_ eq $tip_commit } @$parents ) {
3672 push @merge_tips, $tip_commit;
3673 $ranges{$tip_commit} = \@ranges;
3675 push @merge_tips, undef;
3679 my %excluded = map { $_ => 1 }
3680 parents_exclude($parents, grep { defined } @merge_tips);
3682 # check merge tips for new parents
3684 for my $merge_tip ( @merge_tips ) {
3685 my $spec = shift @merges;
3686 next unless $merge_tip and $excluded{$merge_tip};
3688 my $ranges = $ranges{$merge_tip};
3690 # check out 'new' tips
3693 $merge_base = command_oneline(
3695 @$parents, $merge_tip,
3699 die "An error occurred during merge-base"
3700 unless $@->isa("Git::Error::Command");
3702 warn "W: Cannot find common ancestor between ".
3703 "@$parents and $merge_tip. Ignoring merge info.\n";
3707 # double check that there are no missing non-merge commits
3708 my (@incomplete) = check_cherry_pick(
3709 $merge_base, $merge_tip,
3714 if ( @incomplete ) {
3715 warn "W:svn cherry-pick ignored ($spec) - missing "
3716 .@incomplete." commit(s) (eg $incomplete[0])\n";
3719 "Found merge parent (svn:mergeinfo prop): ",
3721 push @new_parents, $merge_tip;
3725 # cater for merges which merge commits from multiple branches
3726 if ( @new_parents > 1 ) {
3727 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3728 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3730 next unless $new_parents[$i];
3731 next unless $new_parents[$j];
3732 my $revs = command_oneline(
3734 "$new_parents[$i]..$new_parents[$j]",
3737 undef($new_parents[$j]);
3742 push @$parents, grep { defined } @new_parents;
3745 sub make_log_entry {
3746 my ($self, $rev, $parents, $ed) = @_;
3747 my $untracked = $self->get_untracked($ed);
3749 my @parents = @$parents;
3750 my $ps = $ed->{path_strip} || "";
3751 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3752 my $props = $ed->{dir_prop}{$path};
3753 if ( $props->{"svk:merge"} ) {
3754 $self->find_extra_svk_parents
3755 ($ed, $props->{"svk:merge"}, \@parents);
3757 if ( $props->{"svn:mergeinfo"} ) {
3758 $self->find_extra_svn_parents
3760 $props->{"svn:mergeinfo"},
3765 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3766 print $un "r$rev\n" or croak $!;
3767 print $un $_, "\n" foreach @$untracked;
3768 my %log_entry = ( parents => \@parents, revision => $rev,
3772 my $logged = delete $self->{logged_rev_props};
3773 if (!$logged || $self->{-want_revprops}) {
3774 my $rp = $self->ra->rev_proplist($rev);
3775 foreach (sort keys %$rp) {
3777 if (/^svn:(author|date|log)$/) {
3778 $log_entry{$1} = $v;
3779 } elsif ($_ eq 'svm:headrev') {
3782 print $un " rev_prop: ", uri_encode($_), ' ',
3783 uri_encode($v), "\n";
3787 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3789 close $un or croak $!;
3791 $log_entry{date} = parse_svn_date($log_entry{date});
3792 $log_entry{log} .= "\n";
3793 my $author = $log_entry{author} = check_author($log_entry{author});
3794 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3797 my ($commit_name, $commit_email) = ($name, $email);
3798 if ($_use_log_author) {
3800 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3802 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3805 if (!defined $name_field) {
3806 if (!defined $email) {
3809 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3810 ($name, $email) = ($1, $2);
3811 } elsif ($name_field =~ /(.*)@/) {
3812 ($name, $email) = ($1, $name_field);
3814 ($name, $email) = ($name_field, $name_field);
3817 if (defined $headrev && $self->use_svm_props) {
3818 if ($self->rewrite_root) {
3819 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3822 if ($self->rewrite_uuid) {
3823 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3826 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3827 # we don't want "SVM: initializing mirror for junk" ...
3828 return undef if $r == 0;
3829 my $svm = $self->svm;
3830 if ($uuid ne $svm->{uuid}) {
3831 die "UUID mismatch on SVM path:\n",
3832 "expected: $svm->{uuid}\n",
3835 my $full_url = $self->full_url;
3836 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3837 die "Failed to replace '$svm->{replace}' with ",
3838 "'$svm->{source}' in $full_url\n";
3839 # throw away username for storing in records
3840 remove_username($full_url);
3841 $log_entry{metadata} = "$full_url\@$r $uuid";
3842 $log_entry{svm_revision} = $r;
3843 $email ||= "$author\@$uuid";
3844 $commit_email ||= "$author\@$uuid";
3845 } elsif ($self->use_svnsync_props) {
3846 my $full_url = $self->svnsync->{url};
3847 $full_url .= "/$self->{path}" if length $self->{path};
3848 remove_username($full_url);
3849 my $uuid = $self->svnsync->{uuid};
3850 $log_entry{metadata} = "$full_url\@$rev $uuid";
3851 $email ||= "$author\@$uuid";
3852 $commit_email ||= "$author\@$uuid";
3854 my $url = $self->metadata_url;
3855 remove_username($url);
3856 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3857 $log_entry{metadata} = "$url\@$rev " . $uuid;
3858 $email ||= "$author\@" . $uuid;
3859 $commit_email ||= "$author\@" . $uuid;
3861 $log_entry{name} = $name;
3862 $log_entry{email} = $email;
3863 $log_entry{commit_name} = $commit_name;
3864 $log_entry{commit_email} = $commit_email;
3869 my ($self, $min_rev, $max_rev, @parents) = @_;
3870 my ($last_rev, $last_commit) = $self->last_rev_commit;
3871 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3872 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3876 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3877 $self->{inject_parents} = { $rev => $tree };
3878 $self->fetch(undef, undef);
3882 my ($self, $tree) = (shift, shift);
3883 my $log_entry = ::get_commit_entry($tree);
3884 unless ($self->{last_rev}) {
3885 ::fatal("Must have an existing revision to commit");
3887 my %ed_opts = ( r => $self->{last_rev},
3888 log => $log_entry->{log},
3890 tree_a => $self->{last_commit},
3893 $self->set_tree_cb($log_entry, $tree, @_) },
3894 svn_path => $self->{path} );
3895 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3896 print "No changes\nr$self->{last_rev} = $tree\n";
3900 sub rebuild_from_rev_db {
3901 my ($self, $path) = @_;
3903 open my $fh, '<', $path or croak "open: $!";
3904 binmode $fh or croak "binmode: $!";
3906 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3909 next if $_ eq ('0' x 40);
3910 $self->rev_map_set($r, $_);
3913 close $fh or croak "close: $!";
3914 unlink $path or croak "unlink: $!";
3919 my $map_path = $self->map_path;
3920 my $partial = (-e $map_path && ! -z $map_path);
3921 return unless ::verify_ref($self->refname.'^0');
3922 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3923 my $rev_db = $self->rev_db_path;
3924 $self->rebuild_from_rev_db($rev_db);
3925 if ($self->use_svm_props) {
3926 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3927 $self->rebuild_from_rev_db($svm_rev_db);
3929 $self->unlink_rev_db_symlink;
3932 print "Rebuilding $map_path ...\n" if (!$partial);
3933 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3936 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
3937 ($head ? "$head.." : "") . $self->refname,
3939 my $metadata_url = $self->metadata_url;
3940 remove_username($metadata_url);
3941 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3944 if ( m{^commit ($::sha1)$} ) {
3948 next unless s{^\s*(git-svn-id:)}{$1};
3949 my ($url, $rev, $uuid) = ::extract_metadata($_);
3950 remove_username($url);
3952 # ignore merges (from set-tree)
3953 next if (!defined $rev || !$uuid);
3955 # if we merged or otherwise started elsewhere, this is
3956 # how we break out of it
3957 if (($uuid ne $svn_uuid) ||
3958 ($metadata_url && $url && ($url ne $metadata_url))) {
3961 if ($partial && $head) {
3962 print "Partial-rebuilding $map_path ...\n";
3963 print "Currently at $base_rev = $head\n";
3967 $self->rev_map_set($rev, $c);
3968 print "r$rev = $c\n";
3970 command_close_pipe($log, $ctx);
3971 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3972 my $rev_db_path = $self->rev_db_path;
3973 if (-f $self->rev_db_path) {
3974 unlink $self->rev_db_path or croak "unlink: $!";
3976 $self->unlink_rev_db_symlink;
3980 # Tie::File seems to be prone to offset errors if revisions get sparse,
3981 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3982 # one of my favorite modules is out :< Next up would be one of the DBM
3983 # modules, but I'm not sure which is most portable...
3985 # This is the replacement for the rev_db format, which was too big
3986 # and inefficient for large repositories with a lot of sparse history
3989 # The format is this:
3990 # - 24 bytes for every record,
3991 # * 4 bytes for the integer representing an SVN revision number
3992 # * 20 bytes representing the sha1 of a git commit
3993 # - No empty padding records like the old format
3994 # (except the last record, which can be overwritten)
3995 # - new records are written append-only since SVN revision numbers
3996 # increase monotonically
3997 # - lookups on SVN revision number are done via a binary search
3998 # - Piping the file to xxd -c24 is a good way of dumping it for
3999 # viewing or editing (piped back through xxd -r), should the need
4001 # - The last record can be padding revision with an all-zero sha1
4002 # This is used to optimize fetch performance when using multiple
4003 # "fetch" directives in .git/config
4005 # These files are disposable unless noMetadata or useSvmProps is set
4008 my ($fh, $rev, $commit) = @_;
4010 binmode $fh or croak "binmode: $!";
4011 my $size = (stat($fh))[7];
4012 ($size % 24) == 0 or croak "inconsistent size: $size";
4016 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4017 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4018 $read == 24 or croak "read only $read bytes (!= 24)";
4019 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4020 if ($last_commit eq ('0' x40)) {
4022 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4023 $read = sysread($fh, $buf, 24) or
4026 croak "read only $read bytes (!= 24)";
4027 ($last_rev, $last_commit) =
4028 unpack(rev_map_fmt, $buf);
4029 if ($last_commit eq ('0' x40)) {
4030 croak "inconsistent .rev_map\n";
4033 if ($last_rev >= $rev) {
4034 croak "last_rev is higher!: $last_rev >= $rev";
4039 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4040 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4044 sub _rev_map_reset {
4045 my ($fh, $rev, $commit) = @_;
4046 my $c = _rev_map_get($fh, $rev);
4047 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4048 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4049 truncate $fh, $offset or croak "truncate: $!";
4055 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4056 mkpath([$dir]) unless -d $dir;
4057 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4058 close $fh or die "Couldn't close (create) $path: $!\n";
4063 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4064 defined $commit or die "missing arg3\n";
4065 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4066 my $db = $self->map_path($uuid);
4067 my $db_lock = "$db.lock";
4071 $sigmask = POSIX::SigSet->new();
4072 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
4073 SIGALRM, SIGUSR1, SIGUSR2);
4074 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4075 croak "Can't block signals: $!";
4079 $LOCKFILES{$db_lock} = 1;
4081 # both of these options make our .rev_db file very, very important
4082 # and we can't afford to lose it because rebuild() won't work
4083 if ($self->use_svm_props || $self->no_metadata) {
4085 copy($db, $db_lock) or die "rev_map_set(@_): ",
4087 "$db => $db_lock ($!)\n";
4089 rename $db, $db_lock or die "rev_map_set(@_): ",
4090 "Failed to rename: ",
4091 "$db => $db_lock ($!)\n";
4094 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4095 or croak "Couldn't open $db_lock: $!\n";
4096 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4097 _rev_map_set($fh, $rev, $commit);
4099 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4100 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4102 close $fh or croak $!;
4106 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4107 command_noisy('update-ref', '-m', "r$rev$note",
4108 $self->refname, $commit);
4110 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4111 "$db_lock => $db ($!)\n";
4112 delete $LOCKFILES{$db_lock};
4114 sigprocmask(SIG_SETMASK, $sigmask) or
4115 croak "Can't restore signal mask: $!";
4119 # If want_commit, this will return an array of (rev, commit) where
4120 # commit _must_ be a valid commit in the archive.
4121 # Otherwise, it'll return the max revision (whether or not the
4122 # commit is valid or just a 0x40 placeholder).
4124 my ($self, $want_commit) = @_;
4126 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4127 $want_commit ? ($r, $c) : $r;
4130 sub rev_map_max_norebuild {
4131 my ($self, $want_commit) = @_;
4132 my $map_path = $self->map_path;
4133 stat $map_path or return $want_commit ? (0, undef) : 0;
4134 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4135 binmode $fh or croak "binmode: $!";
4136 my $size = (stat($fh))[7];
4137 ($size % 24) == 0 or croak "inconsistent size: $size";
4140 close $fh or croak "close: $!";
4141 return $want_commit ? (0, undef) : 0;
4144 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4145 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4146 my ($r, $c) = unpack(rev_map_fmt, $buf);
4147 if ($want_commit && $c eq ('0' x40)) {
4149 return $want_commit ? (0, undef) : 0;
4151 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4152 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4153 ($r, $c) = unpack(rev_map_fmt, $buf);
4154 if ($c eq ('0'x40)) {
4155 croak "Penultimate record is all-zeroes in $map_path";
4158 close $fh or croak "close: $!";
4159 $want_commit ? ($r, $c) : $r;
4163 my ($self, $rev, $uuid) = @_;
4164 my $map_path = $self->map_path($uuid);
4165 return undef unless -e $map_path;
4167 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4168 my $c = _rev_map_get($fh, $rev);
4169 close($fh) or croak "close: $!";
4174 my ($fh, $rev) = @_;
4176 binmode $fh or croak "binmode: $!";
4177 my $size = (stat($fh))[7];
4178 ($size % 24) == 0 or croak "inconsistent size: $size";
4184 my ($l, $u) = (0, $size - 24);
4188 my $i = int(($l/24 + $u/24) / 2) * 24;
4189 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4190 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4191 my ($r, $c) = unpack(rev_map_fmt, $buf);
4195 } elsif ($r > $rev) {
4197 } else { # $r == $rev
4198 return $c eq ('0' x 40) ? undef : $c;
4204 # Finds the first svn revision that exists on (if $eq_ok is true) or
4205 # before $rev for the current branch. It will not search any lower
4206 # than $min_rev. Returns the git commit hash and svn revision number
4207 # if found, else (undef, undef).
4208 sub find_rev_before {
4209 my ($self, $rev, $eq_ok, $min_rev) = @_;
4210 --$rev unless $eq_ok;
4212 my $max_rev = $self->rev_map_max;
4213 $rev = $max_rev if ($rev > $max_rev);
4214 while ($rev >= $min_rev) {
4215 if (my $c = $self->rev_map_get($rev)) {
4220 return (undef, undef);
4223 # Finds the first svn revision that exists on (if $eq_ok is true) or
4224 # after $rev for the current branch. It will not search any higher
4225 # than $max_rev. Returns the git commit hash and svn revision number
4226 # if found, else (undef, undef).
4227 sub find_rev_after {
4228 my ($self, $rev, $eq_ok, $max_rev) = @_;
4229 ++$rev unless $eq_ok;
4230 $max_rev ||= $self->rev_map_max;
4231 while ($rev <= $max_rev) {
4232 if (my $c = $self->rev_map_get($rev)) {
4237 return (undef, undef);
4241 my ($class, $repo_id, $ref_id, $path) = @_;
4242 unless (defined $repo_id && length $repo_id) {
4243 $repo_id = $Git::SVN::default_repo_id;
4245 unless (defined $ref_id && length $ref_id) {
4246 $_prefix = '' unless defined($_prefix);
4248 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4251 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4253 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4254 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4255 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4256 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4257 if (-d $old_dir && ! -d $dir) {
4262 $_[3] = $path = '' unless (defined $path);
4265 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4266 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4267 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4270 # for read-only access of old .rev_db formats
4271 sub unlink_rev_db_symlink {
4273 my $link = $self->rev_db_path;
4274 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4276 unlink $link or croak "unlink: $link failed!";
4281 my ($self, $uuid) = @_;
4282 my $db_path = $self->map_path($uuid);
4283 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4284 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4288 # the new replacement for .rev_db
4290 my ($self, $uuid) = @_;
4291 $uuid ||= $self->ra_uuid;
4292 "$self->{map_root}.$uuid";
4297 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4303 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4307 sub remove_username {
4308 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4311 package Git::SVN::Prompt;
4315 use vars qw/$_no_auth_cache $_username/;
4318 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
4319 $may_save = undef if $_no_auth_cache;
4320 $default_username = $_username if defined $_username;
4321 if (defined $default_username && length $default_username) {
4322 if (defined $realm && length $realm) {
4323 print STDERR "Authentication realm: $realm\n";
4326 $cred->username($default_username);
4328 username($cred, $realm, $may_save, $pool);
4330 $cred->password(_read_password("Password for '" .
4331 $cred->username . "': ", $realm));
4332 $cred->may_save($may_save);
4333 $SVN::_Core::SVN_NO_ERROR;
4336 sub ssl_server_trust {
4337 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
4338 $may_save = undef if $_no_auth_cache;
4339 print STDERR "Error validating server certificate for '$realm':\n";
4342 # All variables SVN::Auth::SSL::* are used only once,
4343 # so we're shutting up Perl warnings about this.
4344 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
4345 print STDERR " - The certificate is not issued ",
4346 "by a trusted authority. Use the\n",
4347 " fingerprint to validate ",
4348 "the certificate manually!\n";
4350 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
4351 print STDERR " - The certificate hostname ",
4352 "does not match.\n";
4354 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
4355 print STDERR " - The certificate is not yet valid.\n";
4357 if ($failures & $SVN::Auth::SSL::EXPIRED) {
4358 print STDERR " - The certificate has expired.\n";
4360 if ($failures & $SVN::Auth::SSL::OTHER) {
4361 print STDERR " - The certificate has ",
4362 "an unknown error.\n";
4364 } # no warnings 'once'
4366 "Certificate information:\n".
4367 " - Hostname: %s\n".
4368 " - Valid: from %s until %s\n".
4370 " - Fingerprint: %s\n",
4371 map $cert_info->$_, qw(hostname valid_from valid_until
4372 issuer_dname fingerprint);
4375 print STDERR $may_save ?
4376 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
4377 "(R)eject or accept (t)emporarily? ";
4379 $choice = lc(substr(<STDIN> || 'R', 0, 1));
4380 if ($choice =~ /^t$/i) {
4381 $cred->may_save(undef);
4382 } elsif ($choice =~ /^r$/i) {
4384 } elsif ($may_save && $choice =~ /^p$/i) {
4385 $cred->may_save($may_save);
4389 $cred->accepted_failures($failures);
4390 $SVN::_Core::SVN_NO_ERROR;
4393 sub ssl_client_cert {
4394 my ($cred, $realm, $may_save, $pool) = @_;
4395 $may_save = undef if $_no_auth_cache;
4396 print STDERR "Client certificate filename: ";
4398 chomp(my $filename = <STDIN>);
4399 $cred->cert_file($filename);
4400 $cred->may_save($may_save);
4401 $SVN::_Core::SVN_NO_ERROR;
4404 sub ssl_client_cert_pw {
4405 my ($cred, $realm, $may_save, $pool) = @_;
4406 $may_save = undef if $_no_auth_cache;
4407 $cred->password(_read_password("Password: ", $realm));
4408 $cred->may_save($may_save);
4409 $SVN::_Core::SVN_NO_ERROR;
4413 my ($cred, $realm, $may_save, $pool) = @_;
4414 $may_save = undef if $_no_auth_cache;
4415 if (defined $realm && length $realm) {
4416 print STDERR "Authentication realm: $realm\n";
4419 if (defined $_username) {
4420 $username = $_username;
4422 print STDERR "Username: ";
4424 chomp($username = <STDIN>);
4426 $cred->username($username);
4427 $cred->may_save($may_save);
4428 $SVN::_Core::SVN_NO_ERROR;
4431 sub _read_password {
4432 my ($prompt, $realm) = @_;
4434 if (exists $ENV{GIT_ASKPASS}) {
4435 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4437 $password =~ s/[\012\015]//; # \n\r
4440 print STDERR $prompt;
4442 require Term::ReadKey;
4443 Term::ReadKey::ReadMode('noecho');
4444 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4445 last if $key =~ /[\012\015]/; # \n\r
4448 Term::ReadKey::ReadMode('restore');
4455 package SVN::Git::Fetcher;
4456 use vars qw/@ISA $_ignore_regex $_preserve_empty_dirs $_placeholder_filename
4457 @deleted_gpath %added_placeholder $repo_id/;
4461 use File::Basename qw/dirname/;
4464 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4466 my ($class, $git_svn, $switch_path) = @_;
4467 my $self = SVN::Delta::Editor->new;
4468 bless $self, $class;
4469 if (exists $git_svn->{last_commit}) {
4470 $self->{c} = $git_svn->{last_commit};
4471 $self->{empty_symlinks} =
4472 _mark_empty_symlinks($git_svn, $switch_path);
4475 # some options are read globally, but can be overridden locally
4476 # per [svn-remote "..."] section. Command-line options will *NOT*
4477 # override options set in an [svn-remote "..."] section
4478 $repo_id = $git_svn->{repo_id};
4479 my $k = "svn-remote.$repo_id.ignore-paths";
4480 my $v = eval { command_oneline('config', '--get', $k) };
4481 $self->{ignore_regex} = $v;
4483 $k = "svn-remote.$repo_id.preserve-empty-dirs";
4484 $v = eval { command_oneline('config', '--get', '--bool', $k) };
4485 if ($v && $v eq 'true') {
4486 $_preserve_empty_dirs = 1;
4487 $k = "svn-remote.$repo_id.placeholder-filename";
4488 $v = eval { command_oneline('config', '--get', $k) };
4489 $_placeholder_filename = $v;
4492 # Load the list of placeholder files added during previous invocations.
4493 $k = "svn-remote.$repo_id.added-placeholder";
4494 $v = eval { command_oneline('config', '--get-all', $k) };
4495 if ($_preserve_empty_dirs && $v) {
4496 # command() prints errors to stderr, so we only call it if
4497 # command_oneline() succeeded.
4498 my @v = command('config', '--get-all', $k);
4499 $added_placeholder{ dirname($_) } = $_ foreach @v;
4502 $self->{empty} = {};
4503 $self->{dir_prop} = {};
4504 $self->{file_prop} = {};
4505 $self->{absent_dir} = {};
4506 $self->{absent_file} = {};
4507 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4508 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4512 # this uses the Ra object, so it must be called before do_{switch,update},
4513 # not inside them (when the Git::SVN::Fetcher object is passed) to
4514 # do_{switch,update}
4515 sub _mark_empty_symlinks {
4516 my ($git_svn, $switch_path) = @_;
4517 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4518 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4521 my ($rev, $cmt) = $git_svn->last_rev_commit;
4522 return {} unless ($rev && $cmt);
4524 # allow the warning to be printed for each revision we fetch to
4525 # ensure the user sees it. The user can also disable the workaround
4526 # on the repository even while git svn is running and the next
4527 # revision fetched will skip this expensive function.
4528 my $printed_warning;
4529 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4530 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4532 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4533 $pfx .= '/' if length($pfx);
4536 s/\A100644 blob $empty_blob\t//o or next;
4537 unless ($printed_warning) {
4538 print STDERR "Scanning for empty symlinks, ",
4539 "this may take a while if you have ",
4540 "many empty files\n",
4541 "You may disable this with `",
4542 "git config svn.brokenSymlinkWorkaround ",
4544 "This may be done in a different ",
4545 "terminal without restarting ",
4547 $printed_warning = 1;
4550 my (undef, $props) =
4551 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4552 if ($props->{'svn:special'}) {
4556 command_close_pipe($ls, $ctx);
4560 # returns true if a given path is inside a ".git" directory
4562 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4565 # return value: 0 -- don't ignore, 1 -- ignore
4566 sub is_path_ignored {
4567 my ($self, $path) = @_;
4568 return 1 if in_dot_git($path);
4569 return 1 if defined($self->{ignore_regex}) &&
4570 $path =~ m!$self->{ignore_regex}!;
4571 return 0 unless defined($_ignore_regex);
4572 return 1 if $path =~ m!$_ignore_regex!o;
4576 sub set_path_strip {
4577 my ($self, $path) = @_;
4578 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4585 sub open_directory {
4586 my ($self, $path, $pb, $rev) = @_;
4591 my ($self, $path) = @_;
4592 if (my $enc = $self->{pathnameencoding}) {
4594 Encode::from_to($path, 'UTF-8', $enc);
4596 if ($self->{path_strip}) {
4597 $path =~ s!$self->{path_strip}!! or
4598 die "Failed to strip path '$path' ($self->{path_strip})\n";
4604 my ($self, $path, $rev, $pb) = @_;
4605 return undef if $self->is_path_ignored($path);
4607 my $gpath = $self->git_path($path);
4608 return undef if ($gpath eq '');
4610 # remove entire directories.
4611 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4612 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4614 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4620 my $rmpath = "$gpath/$_";
4621 $self->{gii}->remove($rmpath);
4622 print "\tD\t$rmpath\n" unless $::_q;
4624 print "\tD\t$gpath/\n" unless $::_q;
4625 command_close_pipe($ls, $ctx);
4627 $self->{gii}->remove($gpath);
4628 print "\tD\t$gpath\n" unless $::_q;
4630 # Don't add to @deleted_gpath if we're deleting a placeholder file.
4631 push @deleted_gpath, $gpath unless $added_placeholder{dirname($path)};
4632 $self->{empty}->{$path} = 0;
4637 my ($self, $path, $pb, $rev) = @_;
4640 goto out if $self->is_path_ignored($path);
4642 my $gpath = $self->git_path($path);
4643 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4644 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4645 unless (defined $mode && defined $blob) {
4646 die "$path was not found in commit $self->{c} (r$rev)\n";
4648 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4652 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4653 pool => SVN::Pool->new, action => 'M' };
4657 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4660 if (!$self->is_path_ignored($path)) {
4661 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4662 delete $self->{empty}->{$dir};
4665 if ($added_placeholder{$dir}) {
4666 # Remove our placeholder file, if we created one.
4667 delete_entry($self, $added_placeholder{$dir})
4668 unless $path eq $added_placeholder{$dir};
4669 delete $added_placeholder{$dir}
4673 { path => $path, mode_a => $mode, mode_b => $mode,
4674 pool => SVN::Pool->new, action => 'A' };
4678 my ($self, $path, $cp_path, $cp_rev) = @_;
4679 goto out if $self->is_path_ignored($path);
4680 my $gpath = $self->git_path($path);
4682 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4688 $self->{gii}->remove($_);
4689 print "\tD\t$_\n" unless $::_q;
4690 push @deleted_gpath, $gpath;
4692 command_close_pipe($ls, $ctx);
4693 $self->{empty}->{$path} = 0;
4695 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4696 delete $self->{empty}->{$dir};
4697 $self->{empty}->{$path} = 1;
4699 if ($added_placeholder{$dir}) {
4700 # Remove our placeholder file, if we created one.
4701 delete_entry($self, $added_placeholder{$dir});
4702 delete $added_placeholder{$dir}
4709 sub change_dir_prop {
4710 my ($self, $db, $prop, $value) = @_;
4711 return undef if $self->is_path_ignored($db->{path});
4712 $self->{dir_prop}->{$db->{path}} ||= {};
4713 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4717 sub absent_directory {
4718 my ($self, $path, $pb) = @_;
4719 return undef if $self->is_path_ignored($path);
4720 $self->{absent_dir}->{$pb->{path}} ||= [];
4721 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4726 my ($self, $path, $pb) = @_;
4727 return undef if $self->is_path_ignored($path);
4728 $self->{absent_file}->{$pb->{path}} ||= [];
4729 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4733 sub change_file_prop {
4734 my ($self, $fb, $prop, $value) = @_;
4735 return undef if $self->is_path_ignored($fb->{path});
4736 if ($prop eq 'svn:executable') {
4737 if ($fb->{mode_b} != 120000) {
4738 $fb->{mode_b} = defined $value ? 100755 : 100644;
4740 } elsif ($prop eq 'svn:special') {
4741 $fb->{mode_b} = defined $value ? 120000 : 100644;
4743 $self->{file_prop}->{$fb->{path}} ||= {};
4744 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4749 sub apply_textdelta {
4750 my ($self, $fb, $exp) = @_;
4751 return undef if $self->is_path_ignored($fb->{path});
4752 my $fh = $::_repository->temp_acquire('svn_delta');
4753 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4754 # (but $base does not,) so dup() it for reading in close_file
4755 open my $dup, '<&', $fh or croak $!;
4756 my $base = $::_repository->temp_acquire('git_blob');
4759 my ($base_is_link, $size);
4761 if ($fb->{mode_a} eq '120000' &&
4762 ! $self->{empty_symlinks}->{$fb->{path}}) {
4763 print $base 'link ' or die "print $!\n";
4767 $size = $::_repository->cat_blob($fb->{blob}, $base);
4768 die "Failed to read object $fb->{blob}" if ($size < 0);
4771 seek $base, 0, 0 or croak $!;
4772 my $got = ::md5sum($base);
4774 my $err = "Checksum mismatch: ".
4775 "$fb->{path} $fb->{blob}\n" .
4776 "expected: $exp\n" .
4778 if ($base_is_link) {
4780 "Retrying... (possibly ",
4781 "a bad symlink from SVN)\n";
4782 $::_repository->temp_reset($base);
4790 seek $base, 0, 0 or croak $!;
4792 $fb->{base} = $base;
4793 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4797 my ($self, $fb, $exp) = @_;
4798 return undef if $self->is_path_ignored($fb->{path});
4801 my $path = $self->git_path($fb->{path});
4802 if (my $fh = $fb->{fh}) {
4804 seek($fh, 0, 0) or croak $!;
4805 my $got = ::md5sum($fh);
4807 die "Checksum mismatch: $path\n",
4808 "expected: $exp\n got: $got\n";
4811 if ($fb->{mode_b} == 120000) {
4812 sysseek($fh, 0, 0) or croak $!;
4813 my $rd = sysread($fh, my $buf, 5);
4816 croak "sysread: $!\n";
4817 } elsif ($rd == 0) {
4818 warn "$path has mode 120000",
4819 " but it points to nothing\n",
4820 "converting to an empty file with mode",
4822 $fb->{mode_b} = '100644';
4823 } elsif ($buf ne 'link ') {
4824 warn "$path has mode 120000",
4825 " but is not a link\n";
4827 my $tmp_fh = $::_repository->temp_acquire(
4830 while ($res = sysread($fh, my $str, 1024)) {
4831 my $out = syswrite($tmp_fh, $str, $res);
4832 defined($out) && $out == $res
4834 Git::temp_path($tmp_fh),
4837 defined $res or croak $!;
4839 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4840 Git::temp_release($tmp_fh, 1);
4844 $hash = $::_repository->hash_and_insert_object(
4845 Git::temp_path($fh));
4846 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4848 Git::temp_release($fb->{base}, 1);
4849 Git::temp_release($fh, 1);
4851 $hash = $fb->{blob} or die "no blob information\n";
4854 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4855 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4861 $self->{nr} = $self->{gii}->{nr};
4862 delete $self->{gii};
4863 $self->SUPER::abort_edit(@_);
4869 if ($_preserve_empty_dirs) {
4872 # Any entry flagged as empty that also has an associated
4873 # dir_prop represents a newly created empty directory.
4874 foreach my $i (keys %{$self->{empty}}) {
4875 push @empty_dirs, $i if exists $self->{dir_prop}->{$i};
4878 # Search for directories that have become empty due subsequent
4880 push @empty_dirs, $self->find_empty_directories();
4882 # Finally, add a placeholder file to each empty directory.
4883 $self->add_placeholder_file($_) foreach (@empty_dirs);
4885 $self->stash_placeholder_list();
4888 $self->{git_commit_ok} = 1;
4889 $self->{nr} = $self->{gii}->{nr};
4890 delete $self->{gii};
4891 $self->SUPER::close_edit(@_);
4894 sub find_empty_directories {
4897 my %dirs = map { dirname($_) => 1 } @deleted_gpath;
4899 foreach my $dir (sort keys %dirs) {
4900 next if $dir eq ".";
4902 # If there have been any additions to this directory, there is
4903 # no reason to check if it is empty.
4905 foreach my $t (qw/dir_prop file_prop/) {
4906 foreach my $path (keys %{ $self->{$t} }) {
4907 if (exists $self->{$t}->{dirname($path)}) {
4912 last if $skip_added;
4914 next if $skip_added;
4916 # Use `git ls-tree` to get the filenames of this directory
4917 # that existed prior to this particular commit.
4918 my $ls = command('ls-tree', '-z', '--name-only',
4919 $self->{c}, "$dir/");
4920 my %files = map { $_ => 1 } split(/\0/, $ls);
4922 # Remove the filenames that were deleted during this commit.
4923 delete $files{$_} foreach (@deleted_gpath);
4925 # Report the directory if there are no filenames left.
4926 push @empty_dirs, $dir unless (scalar %files);
4931 sub add_placeholder_file {
4932 my ($self, $dir) = @_;
4933 my $path = "$dir/$_placeholder_filename";
4934 my $gpath = $self->git_path($path);
4936 my $fh = $::_repository->temp_acquire($gpath);
4937 my $hash = $::_repository->hash_and_insert_object(Git::temp_path($fh));
4938 Git::temp_release($fh, 1);
4939 $self->{gii}->update('100644', $hash, $gpath) or croak $!;
4941 # The directory should no longer be considered empty.
4942 delete $self->{empty}->{$dir} if exists $self->{empty}->{$dir};
4944 # Keep track of any placeholder files we create.
4945 $added_placeholder{$dir} = $path;
4948 sub stash_placeholder_list {
4950 my $k = "svn-remote.$repo_id.added-placeholder";
4951 my $v = eval { command_oneline('config', '--get-all', $k) };
4952 command_noisy('config', '--unset-all', $k) if $v;
4953 foreach (values %added_placeholder) {
4954 command_noisy('config', '--add', $k, $_);
4958 package SVN::Git::Editor;
4959 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4966 my ($class, $opts) = @_;
4967 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4968 die "$_ required!\n" unless (defined $opts->{$_});
4971 my $pool = SVN::Pool->new;
4972 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4973 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4976 # $opts->{ra} functions should not be used after this:
4977 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4978 $opts->{editor_cb}, $pool);
4979 my $self = SVN::Delta::Editor->new(@ce, $pool);
4980 bless $self, $class;
4981 foreach (qw/svn_path r tree_a tree_b/) {
4982 $self->{$_} = $opts->{$_};
4984 $self->{url} = $opts->{ra}->{url};
4985 $self->{mods} = $mods;
4986 $self->{types} = $types;
4987 $self->{pool} = $pool;
4988 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4990 $self->{path_prefix} = length $self->{svn_path} ?
4991 "$self->{svn_path}/" : '';
4992 $self->{config} = $opts->{config};
4993 $self->{mergeinfo} = $opts->{mergeinfo};
4998 my ($tree_a, $tree_b) = @_;
4999 my @diff_tree = qw(diff-tree -z -r);
5000 if ($_cp_similarity) {
5001 push @diff_tree, "-C$_cp_similarity";
5003 push @diff_tree, '-C';
5005 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
5006 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
5007 push @diff_tree, $tree_a, $tree_b;
5008 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
5012 while (<$diff_fh>) {
5013 chomp $_; # this gets rid of the trailing "\0"
5014 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
5015 ($::sha1)\s($::sha1)\s
5016 ([MTCRAD])\d*$/xo) {
5017 push @mods, { mode_a => $1, mode_b => $2,
5018 sha1_a => $3, sha1_b => $4,
5020 if ($5 =~ /^(?:C|R)$/) {
5025 } elsif ($state eq 'file_a') {
5026 my $x = $mods[$#mods] or croak "Empty array\n";
5027 if ($x->{chg} !~ /^(?:C|R)$/) {
5028 croak "Error parsing $_, $x->{chg}\n";
5032 } elsif ($state eq 'file_b') {
5033 my $x = $mods[$#mods] or croak "Empty array\n";
5034 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
5035 croak "Error parsing $_, $x->{chg}\n";
5037 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
5038 croak "Error parsing $_, $x->{chg}\n";
5043 croak "Error parsing $_\n";
5046 command_close_pipe($diff_fh, $ctx);
5050 sub check_diff_paths {
5051 my ($ra, $pfx, $rev, $mods) = @_;
5053 $pfx .= '/' if length $pfx;
5055 sub type_diff_paths {
5056 my ($ra, $types, $path, $rev) = @_;
5057 my @p = split m#/+#, $path;
5059 unless (defined $types->{$c}) {
5060 $types->{$c} = $ra->check_path($c, $rev);
5063 $c .= '/' . shift @p;
5064 next if defined $types->{$c};
5065 $types->{$c} = $ra->check_path($c, $rev);
5069 foreach my $m (@$mods) {
5070 foreach my $f (qw/file_a file_b/) {
5071 next unless defined $m->{$f};
5072 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
5073 if (length $pfx.$dir && ! defined $types{$dir}) {
5074 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
5082 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
5086 my ($self, $path) = @_;
5087 if (my $enc = $self->{pathnameencoding}) {
5089 Encode::from_to($path, $enc, 'UTF-8');
5091 $self->{path_prefix}.(defined $path ? $path : '');
5095 my ($self, $path) = @_;
5096 if ($self->{url} =~ m#^https?://#) {
5097 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
5099 $self->{url} . '/' . $self->repo_path($path);
5104 my $rm = $self->{rm};
5105 delete $rm->{''}; # we never delete the url we're tracking
5108 foreach (keys %$rm) {
5109 my @d = split m#/#, $_;
5113 $c .= '/' . shift @d;
5117 delete $rm->{$self->{svn_path}};
5118 delete $rm->{''}; # we never delete the url we're tracking
5121 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
5126 my @dn = split m#/#, $_;
5128 delete $rm->{join '/', @dn};
5135 command_close_pipe($fh, $ctx);
5137 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
5138 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
5139 $self->close_directory($bat->{$d}, $p);
5140 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
5141 print "\tD+\t$d/\n" unless $::_q;
5142 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
5147 sub open_or_add_dir {
5148 my ($self, $full_path, $baton, $deletions) = @_;
5149 my $t = $self->{types}->{$full_path};
5151 die "$full_path not known in r$self->{r} or we have a bug!\n";
5155 # SVN::Node::none and SVN::Node::file are used only once,
5156 # so we're shutting up Perl's warnings about them.
5157 if ($t == $SVN::Node::none || defined($deletions->{$full_path})) {
5158 return $self->add_directory($full_path, $baton,
5159 undef, -1, $self->{pool});
5160 } elsif ($t == $SVN::Node::dir) {
5161 return $self->open_directory($full_path, $baton,
5162 $self->{r}, $self->{pool});
5163 } # no warnings 'once'
5164 print STDERR "$full_path already exists in repository at ",
5165 "r$self->{r} and it is not a directory (",
5166 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
5167 } # no warnings 'once'
5172 my ($self, $path, $deletions) = @_;
5173 my $bat = $self->{bat};
5174 my $repo_path = $self->repo_path($path);
5175 return $bat->{''} unless (length $repo_path);
5177 my @p = split m#/+#, $repo_path;
5179 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''}, $deletions);
5182 $c .= '/' . shift @p;
5183 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0}, $deletions);
5188 # Subroutine to convert a globbing pattern to a regular expression.
5189 # From perl cookbook.
5191 my $globstr = shift;
5192 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
5193 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
5194 return '^' . $globstr . '$';
5197 sub check_autoprop {
5198 my ($self, $pattern, $properties, $file, $fbat) = @_;
5199 # Convert the globbing pattern to a regular expression.
5200 my $regex = glob2pat($pattern);
5201 # Check if the pattern matches the file name.
5202 if($file =~ m/($regex)/) {
5203 # Parse the list of properties to set.
5204 my @props = split(/;/, $properties);
5205 foreach my $prop (@props) {
5206 # Parse 'name=value' syntax and set the property.
5207 if ($prop =~ /([^=]+)=(.*)/) {
5208 my ($n,$v) = ($1,$2);
5212 $self->change_file_prop($fbat, $n, $v);
5218 sub apply_autoprops {
5219 my ($self, $file, $fbat) = @_;
5220 my $conf_t = ${$self->{config}}{'config'};
5222 # Check [miscellany]/enable-auto-props in svn configuration.
5223 if (SVN::_Core::svn_config_get_bool(
5225 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
5226 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
5228 # Auto-props are enabled. Enumerate them to look for matches.
5229 my $callback = sub {
5230 $self->check_autoprop($_[0], $_[1], $file, $fbat);
5232 SVN::_Core::svn_config_enumerate(
5234 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
5240 my ($self, $m, $deletions) = @_;
5241 my ($dir, $file) = split_path($m->{file_b});
5242 my $pbat = $self->ensure_path($dir, $deletions);
5243 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5245 print "\tA\t$m->{file_b}\n" unless $::_q;
5246 $self->apply_autoprops($file, $fbat);
5247 $self->chg_file($fbat, $m);
5248 $self->close_file($fbat,undef,$self->{pool});
5252 my ($self, $m, $deletions) = @_;
5253 my ($dir, $file) = split_path($m->{file_b});
5254 my $pbat = $self->ensure_path($dir, $deletions);
5255 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5256 $self->url_path($m->{file_a}), $self->{r});
5257 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5258 $self->chg_file($fbat, $m);
5259 $self->close_file($fbat,undef,$self->{pool});
5263 my ($self, $path, $pbat) = @_;
5264 my $rpath = $self->repo_path($path);
5265 my ($dir, $file) = split_path($rpath);
5266 $self->{rm}->{$dir} = 1;
5267 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
5271 my ($self, $m, $deletions) = @_;
5272 my ($dir, $file) = split_path($m->{file_b});
5273 my $pbat = $self->ensure_path($dir, $deletions);
5274 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
5275 $self->url_path($m->{file_a}), $self->{r});
5276 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
5277 $self->apply_autoprops($file, $fbat);
5278 $self->chg_file($fbat, $m);
5279 $self->close_file($fbat,undef,$self->{pool});
5281 ($dir, $file) = split_path($m->{file_a});
5282 $pbat = $self->ensure_path($dir, $deletions);
5283 $self->delete_entry($m->{file_a}, $pbat);
5287 my ($self, $m, $deletions) = @_;
5288 my ($dir, $file) = split_path($m->{file_b});
5289 my $pbat = $self->ensure_path($dir, $deletions);
5290 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
5291 $pbat,$self->{r},$self->{pool});
5292 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
5293 $self->chg_file($fbat, $m);
5294 $self->close_file($fbat,undef,$self->{pool});
5297 sub T { shift->M(@_) }
5299 sub change_file_prop {
5300 my ($self, $fbat, $pname, $pval) = @_;
5301 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
5304 sub change_dir_prop {
5305 my ($self, $pbat, $pname, $pval) = @_;
5306 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
5309 sub _chg_file_get_blob ($$$$) {
5310 my ($self, $fbat, $m, $which) = @_;
5311 my $fh = $::_repository->temp_acquire("git_blob_$which");
5312 if ($m->{"mode_$which"} =~ /^120/) {
5313 print $fh 'link ' or croak $!;
5314 $self->change_file_prop($fbat,'svn:special','*');
5315 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
5316 $self->change_file_prop($fbat,'svn:special',undef);
5318 my $blob = $m->{"sha1_$which"};
5319 return ($fh,) if ($blob =~ /^0{40}$/);
5320 my $size = $::_repository->cat_blob($blob, $fh);
5321 croak "Failed to read object $blob" if ($size < 0);
5322 $fh->flush == 0 or croak $!;
5323 seek $fh, 0, 0 or croak $!;
5325 my $exp = ::md5sum($fh);
5326 seek $fh, 0, 0 or croak $!;
5331 my ($self, $fbat, $m) = @_;
5332 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
5333 $self->change_file_prop($fbat,'svn:executable','*');
5334 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
5335 $self->change_file_prop($fbat,'svn:executable',undef);
5337 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
5338 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
5339 my $pool = SVN::Pool->new;
5340 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
5342 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
5343 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
5345 die "Unexpected result from send_txstream: $res\n",
5346 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
5349 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
5350 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
5351 if ($got ne $exp_b);
5353 Git::temp_release($fh_b, 1);
5354 Git::temp_release($fh_a, 1);
5359 my ($self, $m, $deletions) = @_;
5360 my ($dir, $file) = split_path($m->{file_b});
5361 my $pbat = $self->ensure_path($dir, $deletions);
5362 print "\tD\t$m->{file_b}\n" unless $::_q;
5363 $self->delete_entry($m->{file_b}, $pbat);
5368 my ($p,$bat) = ($self->{pool}, $self->{bat});
5369 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
5371 $self->close_directory($bat->{$_}, $p);
5373 $self->close_directory($bat->{''}, $p);
5374 $self->SUPER::close_edit($p);
5380 $self->SUPER::abort_edit($self->{pool});
5385 $self->SUPER::DESTROY(@_);
5386 $self->{pool}->clear;
5389 # this drives the editor
5392 my $mods = $self->{mods};
5393 my %o = ( D => 0, C => 1, R => 2, A => 3, M => 4, T => 5 );
5396 foreach my $m (@$mods) {
5397 if ($m->{chg} eq "D") {
5398 $deletions{$m->{file_b}} = 1;
5402 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
5404 if (defined $o{$f}) {
5405 $self->$f($m, \%deletions);
5407 fatal("Invalid change type: $f");
5411 if (defined($self->{mergeinfo})) {
5412 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
5413 $self->{mergeinfo});
5415 $self->rmdirs if $_rmdir;
5416 if (@$mods == 0 && !defined($self->{mergeinfo})) {
5421 return scalar @$mods;
5424 package Git::SVN::Ra;
5425 use vars qw/@ISA $config_dir $_ignore_refs_regex $_log_window_size/;
5428 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
5431 # enforce temporary pool usage for some simple functions
5433 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
5435 my $SUPER = "SUPER::$f";
5438 my $pool = SVN::Pool->new;
5439 my @ret = $self->$SUPER(@_,$pool);
5441 wantarray ? @ret : $ret[0];
5446 sub _auth_providers () {
5448 SVN::Client::get_simple_provider(),
5449 SVN::Client::get_ssl_server_trust_file_provider(),
5450 SVN::Client::get_simple_prompt_provider(
5451 \&Git::SVN::Prompt::simple, 2),
5452 SVN::Client::get_ssl_client_cert_file_provider(),
5453 SVN::Client::get_ssl_client_cert_prompt_provider(
5454 \&Git::SVN::Prompt::ssl_client_cert, 2),
5455 SVN::Client::get_ssl_client_cert_pw_file_provider(),
5456 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
5457 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
5458 SVN::Client::get_username_provider(),
5459 SVN::Client::get_ssl_server_trust_prompt_provider(
5460 \&Git::SVN::Prompt::ssl_server_trust),
5461 SVN::Client::get_username_prompt_provider(
5462 \&Git::SVN::Prompt::username, 2)
5465 # earlier 1.6.x versions would segfault, and <= 1.5.x didn't have
5467 if ($SVN::Core::VERSION gt '1.6.12') {
5468 my $config = SVN::Core::config_get_config($config_dir);
5470 # config_get_config returns all config files from
5471 # ~/.subversion, auth_get_platform_specific_client_providers
5472 # just wants the config "file".
5473 @a = ($config->{'config'}, undef);
5474 $p = SVN::Core::auth_get_platform_specific_client_providers(@a);
5475 # Insert the return value from
5476 # auth_get_platform_specific_providers
5482 sub escape_uri_only {
5485 foreach (split m{/}, $uri) {
5486 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
5494 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
5495 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
5496 $url = "$scheme://$domain$uri";
5502 my ($class, $url) = @_;
5504 return $RA if ($RA && $RA->{url} eq $url);
5508 SVN::_Core::svn_config_ensure($config_dir, undef);
5509 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
5510 my $config = SVN::Core::config_get_config($config_dir);
5512 my $dont_store_passwords = 1;
5513 my $conf_t = ${$config}{'config'};
5516 # The usage of $SVN::_Core::SVN_CONFIG_* variables
5517 # produces warnings that variables are used only once.
5518 # I had not found the better way to shut them up, so
5519 # the warnings of type 'once' are disabled in this block.
5520 if (SVN::_Core::svn_config_get_bool($conf_t,
5521 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5522 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
5524 SVN::_Core::svn_auth_set_parameter($baton,
5525 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
5526 bless (\$dont_store_passwords, "_p_void"));
5528 if (SVN::_Core::svn_config_get_bool($conf_t,
5529 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
5530 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
5532 $Git::SVN::Prompt::_no_auth_cache = 1;
5534 } # no warnings 'once'
5535 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
5537 pool => SVN::Pool->new,
5538 auth_provider_callbacks => $callbacks);
5539 $self->{url} = $url;
5540 $self->{svn_path} = $url;
5541 $self->{repos_root} = $self->get_repos_root;
5542 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5543 $self->{cache} = { check_path => { r => 0, data => {} },
5544 get_dir => { r => 0, data => {} } };
5545 $RA = bless $self, $class;
5549 my ($self, $path, $r) = @_;
5550 my $cache = $self->{cache}->{check_path};
5551 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5552 return $cache->{data}->{$path};
5554 my $pool = SVN::Pool->new;
5555 my $t = $self->SUPER::check_path($path, $r, $pool);
5557 if ($r != $cache->{r}) {
5558 %{$cache->{data}} = ();
5561 $cache->{data}->{$path} = $t;
5565 my ($self, $dir, $r) = @_;
5566 my $cache = $self->{cache}->{get_dir};
5567 if ($r == $cache->{r}) {
5568 if (my $x = $cache->{data}->{$dir}) {
5569 return wantarray ? @$x : $x->[0];
5572 my $pool = SVN::Pool->new;
5573 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5574 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5576 if ($r != $cache->{r}) {
5577 %{$cache->{data}} = ();
5580 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5581 wantarray ? (\%dirents, $r, $props) : \%dirents;
5585 # do not call the real DESTROY since we store ourselves in $RA
5588 # get_log(paths, start, end, limit,
5589 # discover_changed_paths, strict_node_history, receiver)
5591 my ($self, @args) = @_;
5592 my $pool = SVN::Pool->new;
5594 # svn_log_changed_path_t objects passed to get_log are likely to be
5595 # overwritten even if only the refs are copied to an external variable,
5596 # so we should dup the structures in their entirety. Using an
5597 # externally passed pool (instead of our temporary and quickly cleared
5598 # pool in Git::SVN::Ra) does not help matters at all...
5599 my $receiver = pop @args;
5600 my $prefix = "/".$self->{svn_path};
5601 $prefix =~ s#/+($)##;
5602 my $prefix_regex = qr#^\Q$prefix\E#;
5604 my ($paths) = $_[0];
5605 return &$receiver(@_) unless $paths;
5607 foreach my $p (keys %$paths) {
5608 my $i = $paths->{$p};
5609 # Make path relative to our url, not repos_root
5610 $p =~ s/$prefix_regex//;
5611 my %s = map { $_ => $i->$_; }
5612 qw/copyfrom_path copyfrom_rev action/;
5613 if ($s{'copyfrom_path'}) {
5614 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5622 # the limit parameter was not supported in SVN 1.1.x, so we
5623 # drop it. Therefore, the receiver callback passed to it
5624 # is made aware of this limitation by being wrapped if
5625 # the limit passed to is being wrapped.
5626 if ($SVN::Core::VERSION le '1.2.0') {
5627 my $limit = splice(@args, 3, 1);
5629 my $receiver = pop @args;
5630 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5633 my $ret = $self->SUPER::get_log(@args, $pool);
5639 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5640 my $ctx = SVN::Client->new(auth => _auth_providers);
5641 my $out = IO::File->new_tmpfile;
5643 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5644 # $ctx->diff(), so we'll create a default one
5645 my $pool = SVN::Pool->new_default_sub;
5647 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5648 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5650 my $ret = (($out->stat)[7] == 0);
5651 close $out or croak $!;
5656 sub get_commit_editor {
5657 my ($self, $log, $cb, $pool) = @_;
5658 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5659 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5663 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5664 my $new = ($rev_a == $rev_b);
5665 my $path = $gs->{path};
5667 if ($new && -e $gs->{index}) {
5668 unlink $gs->{index} or die
5669 "Couldn't unlink index: $gs->{index}: $!\n";
5671 my $pool = SVN::Pool->new;
5672 $editor->set_path_strip($path);
5673 my (@pc) = split m#/#, $path;
5674 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5676 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5678 # Since we can't rely on svn_ra_reparent being available, we'll
5679 # just have to do some magic with set_path to make it so
5680 # we only want a partial path.
5682 my $final = join('/', @pc);
5684 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5685 $sp .= '/' if length $sp;
5688 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5690 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5692 $reporter->finish_report($pool);
5694 $editor->{git_commit_ok};
5697 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5698 # svn_ra_reparent didn't work before 1.4)
5700 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5701 my $path = $gs->{path};
5702 my $pool = SVN::Pool->new;
5704 my $full_url = $self->{url};
5705 my $old_url = $full_url;
5706 $full_url .= '/' . $path if length $path;
5707 my ($ra, $reparented);
5709 if ($old_url =~ m#^svn(\+ssh)?://# ||
5710 ($full_url =~ m#^https?://# &&
5711 escape_url($full_url) ne $full_url)) {
5715 $ra = Git::SVN::Ra->new($full_url);
5717 } elsif ($old_url ne $full_url) {
5718 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5719 $self->{url} = $full_url;
5724 $url_b = escape_url($url_b);
5725 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5726 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5727 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5728 $reporter->finish_report($pool);
5731 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5732 $self->{url} = $old_url;
5736 $editor->{git_commit_ok};
5739 sub longest_common_path {
5740 my ($gsv, $globs) = @_;
5742 my $common_max = scalar @$gsv;
5744 foreach my $gs (@$gsv) {
5745 my @tmp = split m#/#, $gs->{path};
5748 $p .= length($p) ? "/$_" : $_;
5754 $common_max += scalar @$globs;
5755 foreach my $glob (@$globs) {
5756 my @tmp = split m#/#, $glob->{path}->{left};
5759 $p .= length($p) ? "/$_" : $_;
5765 my $longest_path = '';
5766 foreach (sort {length $b <=> length $a} keys %common) {
5767 if ($common{$_} == $common_max) {
5775 sub gs_fetch_loop_common {
5776 my ($self, $base, $head, $gsv, $globs) = @_;
5777 return if ($base > $head);
5778 my $inc = $_log_window_size;
5779 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5780 my $longest_path = longest_common_path($gsv, $globs);
5781 my $ra_url = $self->{url};
5782 my $find_trailing_edge;
5786 my $err_handler = $SVN::Error::handler;
5787 $SVN::Error::handler = sub {
5789 skip_unknown_revs($err);
5792 my ($paths, $r, $author, $date, $log) = @_;
5794 { author => $author, date => $date, log => $log } ];
5796 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5797 sub { $revs{$_[1]} = _cb(@_) });
5799 print "Checked through r$max\r";
5801 $find_trailing_edge = 1;
5803 if ($err and $find_trailing_edge) {
5804 print STDERR "Path '$longest_path' ",
5805 "was probably deleted:\n",
5806 $err->expanded_message,
5807 "\nWill attempt to follow ",
5808 "revisions r$min .. r$max ",
5809 "committed before the deletion\n";
5811 while (--$hi >= $min) {
5813 $self->get_log([$longest_path], $min, $hi,
5816 $revs{$_[1]} = _cb(@_) });
5818 print STDERR "r$min .. r$ok OK\n";
5822 $find_trailing_edge = 0;
5824 $SVN::Error::handler = $err_handler;
5826 my %exists = map { $_->{path} => $_ } @$gsv;
5827 foreach my $r (sort {$a <=> $b} keys %revs) {
5828 my ($paths, $logged) = @{$revs{$r}};
5830 foreach my $gs ($self->match_globs(\%exists, $paths,
5832 if ($gs->rev_map_max >= $r) {
5835 next unless $gs->match_paths($paths, $r);
5836 $gs->{logged_rev_props} = $logged;
5837 if (my $last_commit = $gs->last_commit) {
5838 $gs->assert_index_clean($last_commit);
5840 my $log_entry = $gs->do_fetch($paths, $r);
5842 $gs->do_git_commit($log_entry);
5844 $INDEX_FILES{$gs->{index}} = 1;
5846 foreach my $g (@$globs) {
5847 my $k = "svn-remote.$g->{remote}." .
5849 Git::SVN::tmp_config($k, $r);
5855 $self = Git::SVN::Ra->new($ra_url);
5856 $ra_invalid = undef;
5859 # pre-fill the .rev_db since it'll eventually get filled in
5860 # with '0' x40 if something new gets committed
5861 foreach my $gs (@$gsv) {
5862 next if $gs->rev_map_max >= $max;
5863 next if defined $gs->rev_map_get($max);
5864 $gs->rev_map_set($max, 0 x40);
5866 foreach my $g (@$globs) {
5867 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5868 Git::SVN::tmp_config($k, $max);
5870 last if $max >= $head;
5873 $max = $head if ($max > $head);
5878 sub get_dir_globbed {
5879 my ($self, $left, $depth, $r) = @_;
5881 my @x = eval { $self->get_dir($left, $r) };
5882 return unless scalar @x == 3;
5883 my $dirents = $x[0];
5885 foreach my $de (keys %$dirents) {
5886 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5888 my @args = ("$left/$de", $depth - 1, $r);
5889 foreach my $dir ($self->get_dir_globbed(@args)) {
5890 push @finalents, "$de/$dir";
5893 push @finalents, $de;
5899 # return value: 0 -- don't ignore, 1 -- ignore
5900 sub is_ref_ignored {
5902 my $refname = $g->{ref}->full_path($p);
5903 return 1 if defined($g->{ignore_refs_regex}) &&
5904 $refname =~ m!$g->{ignore_refs_regex}!;
5905 return 0 unless defined($_ignore_refs_regex);
5906 return 1 if $refname =~ m!$_ignore_refs_regex!o;
5911 my ($self, $exists, $paths, $globs, $r) = @_;
5914 my ($self, $exists, $g, $r) = @_;
5916 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5917 $g->{path}->{depth},
5920 foreach my $de (@dirs) {
5921 my $p = $g->{path}->full_path($de);
5922 next if $exists->{$p};
5923 next if (length $g->{path}->{right} &&
5924 ($self->check_path($p, $r) !=
5926 next unless $p =~ /$g->{path}->{regex}/;
5927 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5928 $g->{ref}->full_path($de), 1);
5931 foreach my $g (@$globs) {
5932 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5933 if ($path->{action} =~ /^[AR]$/) {
5934 get_dir_check($self, $exists, $g, $r);
5937 foreach (keys %$paths) {
5938 if (/$g->{path}->{left_regex}/ &&
5939 !/$g->{path}->{regex}/) {
5940 next if $paths->{$_}->{action} !~ /^[AR]$/;
5941 get_dir_check($self, $exists, $g, $r);
5943 next unless /$g->{path}->{regex}/;
5945 my $pathname = $g->{path}->full_path($p);
5946 next if is_ref_ignored($g, $p);
5947 next if $exists->{$pathname};
5948 next if ($self->check_path($pathname, $r) !=
5950 $exists->{$pathname} = Git::SVN->init(
5951 $self->{url}, $pathname, undef,
5952 $g->{ref}->full_path($p), 1);
5955 foreach (split m#/#, $g->{path}->{left}) {
5957 next unless ($paths->{$c} &&
5958 ($paths->{$c}->{action} =~ /^[AR]$/));
5959 get_dir_check($self, $exists, $g, $r);
5967 return $self->{url} if ($self->{url} eq $self->{repos_root});
5968 my $url = $self->{repos_root};
5969 my @components = split(m!/!, $self->{svn_path});
5972 $url .= "/$c" if length $c;
5974 my $ra = (ref $self)->new($url);
5975 my $latest = $ra->get_latest_revnum;
5976 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5978 } while ($@ && ($c = shift @components));
5984 unless (defined $can_do_switch) {
5985 my $pool = SVN::Pool->new;
5987 $self->do_switch(1, '', 0, $self->{url},
5988 SVN::Delta::Editor->new, $pool);
5993 $rep->abort_report($pool);
6001 sub skip_unknown_revs {
6003 my $errno = $err->apr_err();
6004 # Maybe the branch we're tracking didn't
6005 # exist when the repo started, so it's
6006 # not an error if it doesn't, just continue
6008 # Wonderfully consistent library, eh?
6009 # 160013 - svn:// and file://
6010 # 175002 - http(s)://
6011 # 175007 - http(s):// (this repo required authorization, too...)
6012 # More codes may be discovered later...
6013 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
6014 my $err_key = $err->expanded_message;
6015 # revision numbers change every time, filter them out
6016 $err_key =~ s/\d+/\0/g;
6017 $err_key = "$errno\0$err_key";
6018 unless ($ignored_err{$err_key}) {
6019 warn "W: Ignoring error from SVN, path probably ",
6020 "does not exist: ($errno): ",
6021 $err->expanded_message,"\n";
6022 warn "W: Do not be alarmed at the above message ",
6023 "git-svn is just searching aggressively for ",
6025 "This may take a while on large repositories\n";
6026 $ignored_err{$err_key} = 1;
6030 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
6033 package Git::SVN::Log;
6036 use POSIX qw/strftime/;
6037 use constant commit_log_separator => ('-' x 72) . "\n";
6038 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
6039 %rusers $show_commit $incremental/;
6044 return 1 if defined $c->{r};
6046 # big commit message got truncated by the 16k pretty buffer in rev-list
6047 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
6048 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
6050 my @log = command(qw/cat-file commit/, $c->{c});
6052 # shift off the headers
6053 shift @log while ($log[0] ne '');
6056 # TODO: make $c->{l} not have a trailing newline in the future
6057 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
6059 (undef, $c->{r}, undef) = ::extract_metadata(
6060 (grep(/^git-svn-id: /, @log))[-1]);
6062 return defined $c->{r};
6066 return $color || Git->repository->get_colorbool('color.diff');
6069 sub git_svn_log_cmd {
6070 my ($r_min, $r_max, @args) = @_;
6072 my (@files, @log_opts);
6073 foreach my $x (@args) {
6074 if ($x eq '--' || @files) {
6077 if (::verify_ref("$x^0")) {
6085 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
6086 $gs ||= Git::SVN->_new;
6087 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
6089 push @cmd, '-r' unless $non_recursive;
6090 push @cmd, qw/--raw --name-status/ if $verbose;
6091 push @cmd, '--color' if log_use_color();
6092 push @cmd, @log_opts;
6093 if (defined $r_max && $r_max == $r_min) {
6094 push @cmd, '--max-count=1';
6095 if (my $c = $gs->rev_map_get($r_max)) {
6098 } elsif (defined $r_max) {
6099 if ($r_max < $r_min) {
6100 ($r_min, $r_max) = ($r_max, $r_min);
6102 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
6103 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
6104 # If there are no commits in the range, both $c_max and $c_min
6105 # will be undefined. If there is at least 1 commit in the
6106 # range, both will be defined.
6107 return () if !defined $c_min || !defined $c_max;
6108 if ($c_min eq $c_max) {
6109 push @cmd, '--max-count=1', $c_min;
6111 push @cmd, '--boundary', "$c_min..$c_max";
6114 return (@cmd, @files);
6117 # adapted from pager.c
6120 $ENV{GIT_PAGER_IN_USE} = 'false';
6124 chomp($pager = command_oneline(qw(var GIT_PAGER)));
6125 if ($pager eq 'cat') {
6128 $ENV{GIT_PAGER_IN_USE} = defined($pager);
6132 return unless defined $pager;
6133 pipe my ($rfd, $wfd) or return;
6134 defined(my $pid = fork) or ::fatal "Can't fork: $!";
6136 open STDOUT, '>&', $wfd or
6137 ::fatal "Can't redirect to stdout: $!";
6140 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
6141 $ENV{LESS} ||= 'FRSX';
6142 exec $pager or ::fatal "Can't run pager: $! ($pager)";
6145 sub format_svn_date {
6146 my $t = shift || time;
6147 my $gmoff = Git::SVN::get_tz($t);
6148 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
6151 sub parse_git_date {
6153 # Date::Parse isn't in the standard Perl distro :(
6154 if ($tz =~ s/^\+//) {
6155 $t += tz_to_s_offset($tz);
6156 } elsif ($tz =~ s/^\-//) {
6157 $t -= tz_to_s_offset($tz);
6162 sub set_local_timezone {
6170 sub tz_to_s_offset {
6173 return ($1 * 60) + ($tz * 3600);
6176 sub get_author_info {
6177 my ($dest, $author, $t, $tz) = @_;
6178 $author =~ s/(?:^\s*|\s*$)//g;
6179 $dest->{a_raw} = $author;
6182 $au = $rusers{$author} || undef;
6185 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
6190 $dest->{t_utc} = parse_git_date($t, $tz);
6193 sub process_commit {
6194 my ($c, $r_min, $r_max, $defer) = @_;
6195 if (defined $r_min && defined $r_max) {
6196 if ($r_min == $c->{r} && $r_min == $r_max) {
6200 return 1 if $r_min == $r_max;
6201 if ($r_min < $r_max) {
6202 # we need to reverse the print order
6203 return 0 if (defined $limit && --$limit < 0);
6207 if ($r_min != $r_max) {
6208 return 1 if ($r_min < $c->{r});
6209 return 1 if ($r_max > $c->{r});
6212 return 0 if (defined $limit && --$limit < 0);
6221 if (my $l = $c->{l}) {
6222 while ($l->[0] =~ /^\s*$/) { shift @$l }
6225 $l_fmt ||= 'A' . length($c->{r});
6226 print 'r',pack($l_fmt, $c->{r}),' | ';
6227 print "$c->{c} | " if $show_commit;
6230 show_commit_normal($c);
6234 sub show_commit_changed_paths {
6236 return unless $c->{changed};
6237 print "Changed paths:\n", @{$c->{changed}};
6240 sub show_commit_normal {
6242 print commit_log_separator, "r$c->{r} | ";
6243 print "$c->{c} | " if $show_commit;
6244 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
6247 if (my $l = $c->{l}) {
6248 while ($l->[$#$l] eq "\n" && $#$l > 0
6249 && $l->[($#$l - 1)] eq "\n") {
6252 $nr_line = scalar @$l;
6254 print "1 line\n\n\n";
6256 if ($nr_line == 1) {
6257 $nr_line = '1 line';
6259 $nr_line .= ' lines';
6261 print $nr_line, "\n";
6262 show_commit_changed_paths($c);
6264 print $_ foreach @$l;
6268 show_commit_changed_paths($c);
6272 foreach my $x (qw/raw stat diff/) {
6275 print $_ foreach @{$c->{$x}}
6282 my ($r_min, $r_max);
6283 my $r_last = -1; # prevent dupes
6284 set_local_timezone();
6285 if (defined $::_revision) {
6286 if ($::_revision =~ /^(\d+):(\d+)$/) {
6287 ($r_min, $r_max) = ($1, $2);
6288 } elsif ($::_revision =~ /^\d+$/) {
6289 $r_min = $r_max = $::_revision;
6291 ::fatal "-r$::_revision is not supported, use ",
6292 "standard 'git log' arguments instead";
6297 @args = git_svn_log_cmd($r_min, $r_max, @args);
6299 print commit_log_separator unless $incremental || $oneline;
6302 my $log = command_output_pipe(@args);
6304 my (@k, $c, $d, $stat);
6305 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
6307 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
6309 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
6311 process_commit($c, $r_min, $r_max, \@k) or
6316 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
6317 get_author_info($c, $1, $2, $3);
6318 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
6320 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
6321 push @{$c->{raw}}, $_;
6322 } elsif (/^${esc_color}[ACRMDT]\t/) {
6323 # we could add $SVN->{svn_path} here, but that requires
6324 # remote access at the moment (repo_path_split)...
6325 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
6326 push @{$c->{changed}}, $_;
6327 } elsif (/^${esc_color}diff /o) {
6329 push @{$c->{diff}}, $_;
6331 push @{$c->{diff}}, $_;
6332 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
6333 $esc_color*[\+\-]*$esc_color$/x) {
6335 push @{$c->{stat}}, $_;
6336 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
6337 push @{$c->{stat}}, $_;
6339 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
6340 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
6341 } elsif (s/^${esc_color} //o) {
6342 push @{$c->{l}}, $_;
6345 if ($c && defined $c->{r} && $c->{r} != $r_last) {
6347 process_commit($c, $r_min, $r_max, \@k);
6350 ($r_min, $r_max) = ($r_max, $r_min);
6351 process_commit($_, $r_min, $r_max) foreach reverse @k;
6355 print commit_log_separator unless $incremental || $oneline;
6364 my ($fh, $ctx, $rev);
6367 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
6368 while (my $line = <$fh>) {
6369 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
6370 # Uncommitted edits show up as a rev ID of
6371 # all zeros, which we can't look up with
6374 (undef, $rev, undef) =
6376 $rev = '0' if (!$rev);
6380 $rev = sprintf('%-10s', $rev);
6381 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
6386 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
6391 my %dsha; #distinct sha keys
6393 while (my $line = <$fh>) {
6394 push @buffer, $line;
6395 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6400 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
6402 foreach my $line (@buffer) {
6403 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6405 $rev = '0' if (!$rev)
6407 elsif ($line =~ /^author (.*)/) {
6408 $authors{$rev} = $1;
6409 $authors{$rev} =~ s/\s/_/g;
6411 elsif ($line =~ /^\t(.*)$/) {
6412 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
6416 command_close_pipe($fh, $ctx);
6419 package Git::SVN::Migration;
6420 # these version numbers do NOT correspond to actual version numbers
6421 # of git nor git-svn. They are just relative.
6423 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
6425 # v1 layout: .git/$id/info/url, refs/remotes/$id
6427 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
6429 # v3 layout: .git/svn/$id, refs/remotes/$id
6430 # - info/url may remain for backwards compatibility
6431 # - this is what we migrate up to this layout automatically,
6432 # - this will be used by git svn init on single branches
6433 # v3.1 layout (auto migrated):
6434 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
6435 # for backwards compatibility
6437 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
6438 # - this is only created for newly multi-init-ed
6439 # repositories. Similar in spirit to the
6440 # --use-separate-remotes option in git-clone (now default)
6441 # - we do not automatically migrate to this (following
6442 # the example set by core git)
6444 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
6445 # - newer, more-efficient format that uses 24-bytes per record
6446 # with no filler space.
6447 # - use xxd -c24 < .rev_map.$UUID to view and debug
6448 # - This is a one-way migration, repositories updated to the
6449 # new format will not be able to use old git-svn without
6450 # rebuilding the .rev_db. Rebuilding the rev_db is not
6451 # possible if noMetadata or useSvmProps are set; but should
6452 # be no problem for users that use the (sensible) defaults.
6456 use File::Path qw/mkpath/;
6457 use File::Basename qw/dirname basename/;
6458 use vars qw/$_minimize/;
6460 sub migrate_from_v0 {
6461 my $git_dir = $ENV{GIT_DIR};
6462 return undef unless -d $git_dir;
6463 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6467 my ($id, $orig_ref) = ($_, $_);
6468 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
6469 next unless -f "$git_dir/$id/info/url";
6470 my $new_ref = "refs/remotes/$id";
6471 if (::verify_ref("$new_ref^0")) {
6472 print STDERR "W: $orig_ref is probably an old ",
6473 "branch used by an ancient version of ",
6475 "However, $new_ref also exists.\n",
6476 "We will not be able ",
6477 "to use this branch until this ",
6478 "ambiguity is resolved.\n";
6481 print STDERR "Migrating from v0 layout...\n" if !$migrated;
6482 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
6483 command_noisy('update-ref', $new_ref, $orig_ref);
6484 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
6487 command_close_pipe($fh, $ctx);
6488 print STDERR "Done migrating from v0 layout...\n" if $migrated;
6492 sub migrate_from_v1 {
6493 my $git_dir = $ENV{GIT_DIR};
6495 return $migrated unless -d $git_dir;
6496 my $svn_dir = "$git_dir/svn";
6498 # just in case somebody used 'svn' as their $id at some point...
6499 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
6501 print STDERR "Migrating from a git-svn v1 layout...\n";
6503 print STDERR "Data from a previous version of git-svn exists, but\n\t",
6504 "$svn_dir\n\t(required for this version ",
6505 "($::VERSION) of git-svn) does not exist.\n";
6506 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
6509 next unless $x =~ s#^refs/remotes/##;
6511 next unless -f "$git_dir/$x/info/url";
6512 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
6514 my $dn = dirname("$git_dir/svn/$x");
6515 mkpath([$dn]) unless -d $dn;
6516 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
6517 mkpath(["$git_dir/svn/svn"]);
6518 print STDERR " - $git_dir/$x/info => ",
6519 "$git_dir/svn/$x/info\n";
6520 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
6522 # don't worry too much about these, they probably
6523 # don't exist with repos this old (save for index,
6524 # and we can easily regenerate that)
6525 foreach my $f (qw/unhandled.log index .rev_db/) {
6526 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
6529 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
6530 rename "$git_dir/$x", "$git_dir/svn/$x" or
6535 command_close_pipe($fh, $ctx);
6536 print STDERR "Done migrating from a git-svn v1 layout\n";
6541 my ($l_map, $pfx, $path) = @_;
6543 foreach (<$path/*>) {
6544 if (-r "$_/info/url") {
6545 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
6546 my $ref_id = $pfx . basename $_;
6547 my $url = ::file_to_s("$_/info/url");
6548 $l_map->{$ref_id} = $url;
6555 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6556 read_old_urls($l_map, $x, $_);
6560 sub migrate_from_v2 {
6561 my @cfg = command(qw/config -l/);
6562 return if grep /^svn-remote\..+\.url=/, @cfg;
6564 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6567 foreach my $ref_id (sort keys %l_map) {
6568 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6570 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6577 sub minimize_connections {
6578 my $r = Git::SVN::read_all_remotes();
6580 my $root_repos = {};
6581 foreach my $repo_id (keys %$r) {
6582 my $url = $r->{$repo_id}->{url} or next;
6583 my $fetch = $r->{$repo_id}->{fetch} or next;
6584 my $ra = Git::SVN::Ra->new($url);
6586 # skip existing cases where we already connect to the root
6587 if (($ra->{url} eq $ra->{repos_root}) ||
6588 ($ra->{repos_root} eq $repo_id)) {
6589 $root_repos->{$ra->{url}} = $repo_id;
6593 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6594 my $root_path = $ra->{url};
6595 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6596 foreach my $path (keys %$fetch) {
6597 my $ref_id = $fetch->{$path};
6598 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6600 # make sure we can read when connecting to
6601 # a higher level of a repository
6602 my ($last_rev, undef) = $gs->last_rev_commit;
6603 if (!defined $last_rev) {
6605 $root_ra->get_latest_revnum;
6609 my $new = $root_path;
6610 $new .= length $path ? "/$path" : '';
6612 $root_ra->get_log([$new], $last_rev, $last_rev,
6616 $new_urls->{$ra->{repos_root}}->{$new} =
6617 { ref_id => $ref_id,
6618 old_repo_id => $repo_id,
6619 old_path => $path };
6624 foreach my $url (keys %$new_urls) {
6625 # see if we can re-use an existing [svn-remote "repo_id"]
6626 # instead of creating a(n ugly) new section:
6627 my $repo_id = $root_repos->{$url} || $url;
6629 my $fetch = $new_urls->{$url};
6630 foreach my $path (keys %$fetch) {
6631 my $x = $fetch->{$path};
6632 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6633 my $pfx = "svn-remote.$x->{old_repo_id}";
6635 my $old_fetch = quotemeta("$x->{old_path}:".
6637 command_noisy(qw/config --unset/,
6638 "$pfx.fetch", '^'. $old_fetch . '$');
6639 delete $r->{$x->{old_repo_id}}->
6640 {fetch}->{$x->{old_path}};
6641 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6642 command_noisy(qw/config --unset/,
6644 push @emptied, $x->{old_repo_id}
6649 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6651 The following [svn-remote] sections in your config file ($file) are empty
6652 and can be safely removed:
6654 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6658 sub migration_check {
6662 minimize_connections() if $_minimize;
6665 package Git::IndexInfo;
6668 use Git qw/command_input_pipe command_close_pipe/;
6672 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6673 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6677 my ($self, $path) = @_;
6678 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6679 return ++$self->{nr};
6685 my ($self, $mode, $hash, $path) = @_;
6686 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6687 return ++$self->{nr};
6694 command_close_pipe($self->{gui}, $self->{ctx});
6697 package Git::SVN::GlobSpec;
6702 my ($class, $glob, $pattern_ok) = @_;
6704 $re =~ s!/+$!!g; # no need for trailing slashes
6705 my (@left, @right, @patterns);
6707 my $die_msg = "Only one set of wildcard directories " .
6708 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6709 for my $part (split(m|/|, $glob)) {
6710 if ($part =~ /\*/ && $part ne "*") {
6711 die "Invalid pattern in '$glob': $part\n";
6712 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6713 $part !~ /^\{[^{}]+\}/) {
6714 die "Invalid pattern in '$glob': $part\n";
6717 die $die_msg if $state eq "right";
6719 push(@patterns, "[^/]*");
6720 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6721 die $die_msg if $state eq "right";
6723 my $p = quotemeta($1);
6725 push(@patterns, "(?:$p)");
6727 if ($state eq "left") {
6730 push(@right, $part);
6735 my $depth = @patterns;
6737 die "One '*' is needed in glob: '$glob'\n";
6739 my $left = join('/', @left);
6740 my $right = join('/', @right);
6741 $re = join('/', @patterns);
6743 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6744 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6745 bless { left => $left, right => $right, left_regex => $left_re,
6746 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6750 my ($self, $path) = @_;
6751 return (length $self->{left} ? "$self->{left}/" : '') .
6752 $path . (length $self->{right} ? "/$self->{right}" : '');
6760 $remotes = { # returned by read_all_remotes()
6762 # svn-remote.svn.url=https://svn.musicpd.org
6763 url => 'https://svn.musicpd.org',
6764 # svn-remote.svn.fetch=mpd/trunk:trunk
6766 'mpd/trunk' => 'trunk',
6768 # svn-remote.svn.tags=mpd/tags/*:tags/*
6773 regex => qr!mpd/tags/([^/]+)$!,
6779 regex => qr!tags/([^/]+)$!,
6786 $log_entry hashref as returned by libsvn_log_entry()
6788 log => 'whitespace-formatted log entry
6789 ', # trailing newline is preserved
6790 revision => '8', # integer
6791 date => '2004-02-24T17:01:44.108345Z', # commit date
6792 author => 'committer name'
6796 # this is generated by generate_diff();
6797 @mods = array of diff-index line hashes, each element represents one line
6798 of diff-index output
6800 diff-index line ($m hash)
6802 mode_a => first column of diff-index output, no leading ':',
6803 mode_b => second column of diff-index output,
6804 sha1_b => sha1sum of the final blob,
6805 chg => change type [MCRADT],
6806 file_a => original file name of a file (iff chg is 'C' or 'R')
6807 file_b => new/current file name of a file (any chg)
6811 # retval of read_url_paths{,_all}();
6813 # repository root url
6814 'https://svn.musicpd.org' => {
6815 # repository path # GIT_SVN_ID
6816 'mpd/trunk' => 'trunk',
6817 'mpd/tags/0.11.5' => 'tags/0.11.5',
6822 I don't trust the each() function on unless I created %hash myself
6823 because the internal iterator may not have started at base.