2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
7 use vars qw/ $AUTHOR $VERSION
8 $sha1 $sha1_short $_revision $_repository
9 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
29 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
34 $Git::SVN::Log::TZ = $ENV{TZ};
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
41 # repository decides to close the connection which we expect to be kept alive.
42 $SIG{PIPE} = 'IGNORE';
44 # Given a dot separated version number, "subtract" it from
45 # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
46 # is at least at the version the caller asked for.
47 sub compare_svn_version {
48 my (@ours) = split(/\./, $SVN::Core::VERSION);
49 my (@theirs) = split(/\./, $_[0]);
52 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
53 $diff = $ours[$i] - $theirs[$i];
54 return $diff if ($diff);
56 return 1 if ($i < @ours);
57 return -1 if ($i < @theirs);
62 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
65 if (::compare_svn_version('1.1.0') < 0) {
66 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
69 my $can_compress = eval { require Compress::Zlib; 1};
73 use File::Basename qw/dirname basename/;
74 use File::Path qw/mkpath/;
77 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
80 use Git::SVN::Editor qw//;
81 use Git::SVN::Fetcher qw//;
82 use Git::SVN::Ra qw//;
83 use Git::SVN::Prompt qw//;
84 use Memoize; # core since 5.8.0, Jul 2002
87 # import functions from Git into our packages, en masse
89 foreach (qw/command command_oneline command_noisy command_output_pipe
90 command_input_pipe command_close_pipe
91 command_bidi_pipe command_close_bidi_pipe/) {
92 for my $package ( qw(Git::SVN::Migration Git::SVN::Log Git::SVN),
94 *{"${package}::$_"} = \&{"Git::$_"};
97 Memoize::memoize 'Git::config';
98 Memoize::memoize 'Git::config_bool';
103 $sha1 = qr/[a-f\d]{40}/;
104 $sha1_short = qr/[a-f\d]{4,40}/;
105 my ($_stdin, $_help, $_edit,
106 $_message, $_file, $_branch_dest,
107 $_template, $_shared,
108 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
109 $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
110 $_prefix, $_no_checkout, $_url, $_verbose,
111 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
112 $Git::SVN::_follow_parent = 1;
113 $Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
115 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
116 'config-dir=s' => \$Git::SVN::Ra::config_dir,
117 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
118 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
119 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
120 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
121 'authors-file|A=s' => \$_authors,
122 'authors-prog=s' => \$_authors_prog,
123 'repack:i' => \$Git::SVN::_repack,
124 'noMetadata' => \$Git::SVN::_no_metadata,
125 'useSvmProps' => \$Git::SVN::_use_svm_props,
126 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
127 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
128 'no-checkout' => \$_no_checkout,
130 'repack-flags|repack-args|repack-opts=s' =>
131 \$Git::SVN::_repack_flags,
132 'use-log-author' => \$Git::SVN::_use_log_author,
133 'add-author-from' => \$Git::SVN::_add_author_from,
134 'localtime' => \$Git::SVN::_localtime,
137 my ($_trunk, @_tags, @_branches, $_stdlayout);
139 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
140 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
141 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
142 'stdlayout|s' => \$_stdlayout,
143 'minimize-url|m!' => \$Git::SVN::_minimize_url,
144 'no-metadata' => sub { $icv{noMetadata} = 1 },
145 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
146 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
147 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
148 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
150 my %cmt_opts = ( 'edit|e' => \$_edit,
151 'rmdir' => \$Git::SVN::Editor::_rmdir,
152 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
153 'l=i' => \$Git::SVN::Editor::_rename_limit,
154 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
158 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
159 { 'revision|r=s' => \$_revision,
160 'fetch-all|all' => \$_fetch_all,
161 'parent|p' => \$_fetch_parent,
163 clone => [ \&cmd_clone, "Initialize and fetch revisions",
164 { 'revision|r=s' => \$_revision,
165 'preserve-empty-dirs' =>
166 \$Git::SVN::Fetcher::_preserve_empty_dirs,
167 'placeholder-filename=s' =>
168 \$Git::SVN::Fetcher::_placeholder_filename,
169 %fc_opts, %init_opts } ],
170 init => [ \&cmd_init, "Initialize a repo for tracking" .
171 " (requires URL argument)",
173 'multi-init' => [ \&cmd_multi_init,
174 "Deprecated alias for ".
175 "'$0 init -T<trunk> -b<branches> -t<tags>'",
177 dcommit => [ \&cmd_dcommit,
178 'Commit several diffs to merge with upstream',
179 { 'merge|m|M' => \$_merge,
180 'strategy|s=s' => \$_strategy,
181 'verbose|v' => \$_verbose,
182 'dry-run|n' => \$_dry_run,
183 'fetch-all|all' => \$_fetch_all,
184 'commit-url=s' => \$_commit_url,
185 'revision|r=i' => \$_revision,
186 'no-rebase' => \$_no_rebase,
187 'mergeinfo=s' => \$_merge_info,
188 'interactive|i' => \$_interactive,
189 %cmt_opts, %fc_opts } ],
190 branch => [ \&cmd_branch,
191 'Create a branch in the SVN repository',
192 { 'message|m=s' => \$_message,
193 'destination|d=s' => \$_branch_dest,
194 'dry-run|n' => \$_dry_run,
196 'username=s' => \$Git::SVN::Prompt::_username,
197 'commit-url=s' => \$_commit_url } ],
198 tag => [ sub { $_tag = 1; cmd_branch(@_) },
199 'Create a tag in the SVN repository',
200 { 'message|m=s' => \$_message,
201 'destination|d=s' => \$_branch_dest,
202 'dry-run|n' => \$_dry_run,
203 'username=s' => \$Git::SVN::Prompt::_username,
204 'commit-url=s' => \$_commit_url } ],
205 'set-tree' => [ \&cmd_set_tree,
206 "Set an SVN repository to a git tree-ish",
207 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
208 'create-ignore' => [ \&cmd_create_ignore,
209 'Create a .gitignore per svn:ignore',
210 { 'revision|r=i' => \$_revision
212 'mkdirs' => [ \&cmd_mkdirs ,
213 "recreate empty directories after a checkout",
214 { 'revision|r=i' => \$_revision } ],
215 'propget' => [ \&cmd_propget,
216 'Print the value of a property on a file or directory',
217 { 'revision|r=i' => \$_revision } ],
218 'proplist' => [ \&cmd_proplist,
219 'List all properties of a file or directory',
220 { 'revision|r=i' => \$_revision } ],
221 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
222 { 'revision|r=i' => \$_revision
224 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
225 { 'revision|r=i' => \$_revision
227 'multi-fetch' => [ \&cmd_multi_fetch,
228 "Deprecated alias for $0 fetch --all",
229 { 'revision|r=s' => \$_revision, %fc_opts } ],
230 'migrate' => [ sub { },
231 # no-op, we automatically run this anyways,
232 'Migrate configuration/metadata/layout from
233 previous versions of git-svn',
234 { 'minimize' => \$Git::SVN::Migration::_minimize,
236 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
237 { 'limit=i' => \$Git::SVN::Log::limit,
238 'revision|r=s' => \$_revision,
239 'verbose|v' => \$Git::SVN::Log::verbose,
240 'incremental' => \$Git::SVN::Log::incremental,
241 'oneline' => \$Git::SVN::Log::oneline,
242 'show-commit' => \$Git::SVN::Log::show_commit,
243 'non-recursive' => \$Git::SVN::Log::non_recursive,
244 'authors-file|A=s' => \$_authors,
245 'color' => \$Git::SVN::Log::color,
246 'pager=s' => \$Git::SVN::Log::pager
248 'find-rev' => [ \&cmd_find_rev,
249 "Translate between SVN revision numbers and tree-ish",
251 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
252 { 'merge|m|M' => \$_merge,
253 'verbose|v' => \$_verbose,
254 'strategy|s=s' => \$_strategy,
255 'local|l' => \$_local,
256 'fetch-all|all' => \$_fetch_all,
257 'dry-run|n' => \$_dry_run,
258 'preserve-merges|p' => \$_preserve_merges,
260 'commit-diff' => [ \&cmd_commit_diff,
261 'Commit a diff between two trees',
262 { 'message|m=s' => \$_message,
263 'file|F=s' => \$_file,
264 'revision|r=s' => \$_revision,
266 'info' => [ \&cmd_info,
267 "Show info about the latest SVN revision
268 on the current branch",
269 { 'url' => \$_url, } ],
270 'blame' => [ \&Git::SVN::Log::cmd_blame,
271 "Show what revision and author last modified each line of a file",
272 { 'git-format' => \$_git_format } ],
273 'reset' => [ \&cmd_reset,
274 "Undo fetches back to the specified SVN revision",
275 { 'revision|r=s' => \$_revision,
276 'parent|p' => \$_fetch_parent } ],
278 "Compress unhandled.log files in .git/svn and remove " .
279 "index files in .git/svn",
286 my ($class, $reason) = @_;
287 return bless \$reason, shift;
291 die "Cannot use readline on FakeTerm: $$self";
296 $ENV{"GIT_SVN_NOTTY"}
297 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
298 : new Term::ReadLine 'git-svn';
301 $term = new FakeTerm "$@: going non-interactive";
305 for (my $i = 0; $i < @ARGV; $i++) {
306 if (defined $cmd{$ARGV[$i]}) {
310 } elsif ($ARGV[$i] eq 'help') {
316 # make sure we're always running at the top-level working directory
317 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
318 unless (-d $ENV{GIT_DIR}) {
319 if ($git_dir_user_set) {
320 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
321 "but it is not a directory\n";
323 my $git_dir = delete $ENV{GIT_DIR};
326 $cdup = command_oneline(qw/rev-parse --show-cdup/);
327 $git_dir = '.' unless ($cdup);
328 chomp $cdup if ($cdup);
329 $cdup = "." unless ($cdup && length $cdup);
330 } "Already at toplevel, but $git_dir not found\n";
331 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
332 unless (-d $git_dir) {
333 die "$git_dir still not found after going to ",
336 $ENV{GIT_DIR} = $git_dir;
338 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
341 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
343 read_git_config(\%opts);
344 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
345 Getopt::Long::Configure('pass_through');
347 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
348 'minimize-connections' => \$Git::SVN::Migration::_minimize,
349 'id|i=s' => \$Git::SVN::default_ref_id,
350 'svn-remote|remote|R=s' => sub {
351 $Git::SVN::no_reuse_existing = 1;
352 $Git::SVN::default_repo_id = $_[1] });
353 exit 1 if (!$rv && $cmd && $cmd ne 'log');
356 version() if $_version;
357 usage(1) unless defined $cmd;
358 load_authors() if $_authors;
359 if (defined $_authors_prog) {
360 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
363 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
364 Git::SVN::Migration::migration_check();
366 Git::SVN::init_vars();
368 Git::SVN::verify_remotes_sanity();
369 $cmd{$cmd}->[0]->(@ARGV);
370 post_fetch_checkout();
375 ####################### primary functions ######################
377 my $exit = shift || 0;
378 my $fd = $exit ? \*STDERR : \*STDOUT;
380 git-svn - bidirectional operations between a single Subversion tree and git
381 Usage: git svn <command> [options] [arguments]\n
383 print $fd "Available commands:\n" unless $cmd;
385 foreach (sort keys %cmd) {
386 next if $cmd && $cmd ne $_;
387 next if /^multi-/; # don't show deprecated commands
388 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
389 foreach (sort keys %{$cmd{$_}->[2]}) {
390 # mixed-case options are for .git/config only
391 next if /[A-Z]/ && /^[a-z]+$/i;
392 # prints out arguments as they should be passed:
393 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
394 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
396 split /\|/,$_)," $x\n";
400 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
401 arbitrary identifier if you're tracking multiple SVN branches/repositories in
402 one git repository and want to keep them separate. See git-svn(1) for more
410 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
415 my ($prompt, %arg) = @_;
416 my $valid_re = $arg{valid_re};
417 my $default = $arg{default};
421 if ( !( defined($term->IN)
422 && defined( fileno($term->IN) )
423 && defined( $term->OUT )
424 && defined( fileno($term->OUT) ) ) ){
425 return defined($default) ? $default : undef;
429 $resp = $term->readline($prompt);
430 if (!defined $resp) { # EOF
432 return defined $default ? $default : undef;
434 if ($resp eq '' and defined $default) {
437 if (!defined $valid_re or $resp =~ /$valid_re/) {
445 unless (-d $ENV{GIT_DIR}) {
446 my @init_db = ('init');
447 push @init_db, "--template=$_template" if defined $_template;
448 if (defined $_shared) {
449 if ($_shared =~ /[a-z]/) {
450 push @init_db, "--shared=$_shared";
452 push @init_db, "--shared";
455 command_noisy(@init_db);
456 $_repository = Git->repository(Repository => ".git");
459 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
460 foreach my $i (keys %icv) {
461 die "'$set' and '$i' cannot both be set\n" if $set;
462 next unless defined $icv{$i};
463 command_noisy('config', "$pfx.$i", $icv{$i});
466 my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
467 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
468 if defined $$ignore_paths_regex;
469 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
470 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
471 if defined $$ignore_refs_regex;
473 if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
474 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
475 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
476 command_noisy('config', "$pfx.placeholder-filename", $$fname);
481 my $repo_path = shift or return;
482 mkpath([$repo_path]) unless -d $repo_path;
483 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
484 $ENV{GIT_DIR} = '.git';
485 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
489 my ($url, $path) = @_;
490 if (!defined $path &&
491 (defined $_trunk || @_branches || @_tags ||
492 defined $_stdlayout) &&
493 $url !~ m#^[a-z\+]+://#) {
496 $path = basename($url) if !defined $path || !length $path;
497 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
498 cmd_init($url, $path);
499 command_oneline('config', 'svn.authorsfile', $authors_absolute)
501 Git::SVN::fetch_all($Git::SVN::default_repo_id);
505 if (defined $_stdlayout) {
506 $_trunk = 'trunk' if (!defined $_trunk);
507 @_tags = 'tags' if (! @_tags);
508 @_branches = 'branches' if (! @_branches);
510 if (defined $_trunk || @_branches || @_tags) {
511 return cmd_multi_init(@_);
513 my $url = shift or die "SVN repository location required ",
514 "as a command-line argument\n";
515 $url = canonicalize_url($url);
519 if ($Git::SVN::_minimize_url eq 'unset') {
520 $Git::SVN::_minimize_url = 0;
523 Git::SVN->init($url);
527 if (grep /^\d+=./, @_) {
528 die "'<rev>=<commit>' fetch arguments are ",
529 "no longer supported.\n";
533 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
535 $Git::SVN::no_reuse_existing = undef;
536 if ($_fetch_parent) {
537 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
539 die "Unable to determine upstream SVN information from ",
540 "working tree history\n";
542 # just fetch, don't checkout.
543 $_no_checkout = 'true';
544 $_fetch_all ? $gs->fetch_all : $gs->fetch;
545 } elsif ($_fetch_all) {
548 $remote ||= $Git::SVN::default_repo_id;
549 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
555 if ($_stdin || !@commits) {
556 print "Reading from stdin...\n";
559 if (/\b($sha1_short)\b/o) {
560 unshift @commits, $1;
565 foreach my $c (@commits) {
566 my @tmp = command('rev-parse',$c);
567 if (scalar @tmp == 1) {
569 } elsif (scalar @tmp > 1) {
570 push @revs, reverse(command('rev-list',@tmp));
572 fatal "Failed to rev-parse $c";
575 my $gs = Git::SVN->new;
576 my ($r_last, $cmt_last) = $gs->last_rev_commit;
578 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
579 fatal "There are new revisions that were fetched ",
580 "and need to be merged (or acknowledged) ",
581 "before committing.\nlast rev: $r_last\n",
582 " current: $gs->{last_rev}";
584 $gs->set_tree($_) foreach @revs;
585 print "Done committing ",scalar @revs," revisions to SVN\n";
589 sub split_merge_info_range {
591 if ($range =~ /(\d+)-(\d+)/) {
592 return (int($1), int($2));
594 return (int($range), int($range));
602 my @arr = split(/,/, $in);
603 for my $element (@arr) {
604 my ($start, $end) = split_merge_info_range($element);
608 my @sorted = @arr [ sort {
609 $fnums[$a] <=> $fnums[$b]
615 for my $element (@sorted) {
616 my ($start, $end) = split_merge_info_range($element);
623 if ($start <= $last+1) {
629 if ($first == $last) {
630 push @return, "$first";
632 push @return, "$first-$last";
639 if ($first == $last) {
640 push @return, "$first";
642 push @return, "$first-$last";
646 return join(',', @return);
649 sub merge_revs_into_hash {
650 my ($hash, $minfo) = @_;
651 my @lines = split(' ', $minfo);
653 for my $line (@lines) {
654 my ($branchpath, $revs) = split(/:/, $line);
656 if (exists($hash->{$branchpath})) {
657 # Merge the two revision sets
658 my $combined = "$hash->{$branchpath},$revs";
659 $hash->{$branchpath} = combine_ranges($combined);
661 # Just do range combining for consolidation
662 $hash->{$branchpath} = combine_ranges($revs);
667 sub merge_merge_info {
668 my ($mergeinfo_one, $mergeinfo_two) = @_;
669 my %result_hash = ();
671 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
672 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
675 # Sort below is for consistency's sake
676 for my $branchname (sort keys(%result_hash)) {
677 my $revlist = $result_hash{$branchname};
678 $result .= "$branchname:$revlist\n"
683 sub populate_merge_info {
684 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
687 read_commit_parents(\%parentshash, $d);
688 my @parents = @{$parentshash{$d}};
691 my $all_parents_ok = 1;
692 my $aggregate_mergeinfo = '';
693 my $rooturl = $gs->repos_root;
695 if (defined($rewritten_parent)) {
696 # Replace first parent with newly-rewritten version
698 unshift @parents, $rewritten_parent;
701 foreach my $parent (@parents) {
702 my ($branchurl, $svnrev, $paruuid) =
703 cmt_metadata($parent);
705 unless (defined($svnrev)) {
706 # Should have been caught be preflight check
707 fatal "merge commit $d has ancestor $parent, but that change "
708 ."does not have git-svn metadata!";
710 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
711 fatal "commit $parent git-svn metadata changed mid-run!";
715 my $ra = Git::SVN::Ra->new($branchurl);
716 my (undef, undef, $props) =
717 $ra->get_dir(canonicalize_path("."), $svnrev);
718 my $par_mergeinfo = $props->{'svn:mergeinfo'};
719 unless (defined $par_mergeinfo) {
722 # Merge previous mergeinfo values
723 $aggregate_mergeinfo =
724 merge_merge_info($aggregate_mergeinfo,
727 next if $parent eq $parents[0]; # Skip first parent
728 # Add new changes being placed in tree by merge
729 my @cmd = (qw/rev-list --reverse/,
731 foreach my $par (@parents) {
732 unless ($par eq $parent) {
737 my ($revlist, $ctx) = command_output_pipe(@cmd);
741 my (undef, $csvnrev, undef) =
743 unless (defined $csvnrev) {
744 # A child is missing SVN annotations...
745 # this might be OK, or might not be.
746 warn "W:child $irev is merged into revision "
747 ."$d but does not have git-svn metadata. "
748 ."This means git-svn cannot determine the "
749 ."svn revision numbers to place into the "
750 ."svn:mergeinfo property. You must ensure "
751 ."a branch is entirely committed to "
752 ."SVN before merging it in order for "
753 ."svn:mergeinfo population to function "
756 push @revsin, $csvnrev;
758 command_close_pipe($revlist, $ctx);
760 last unless $all_parents_ok;
762 # We now have a list of all SVN revnos which are
763 # merged by this particular parent. Integrate them.
764 next if $#revsin == -1;
765 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
766 $aggregate_mergeinfo =
767 merge_merge_info($aggregate_mergeinfo,
770 if ($all_parents_ok and $aggregate_mergeinfo) {
771 return $aggregate_mergeinfo;
780 command_noisy(qw/update-index --refresh/);
781 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
782 'Cannot dcommit with a dirty index. Commit your changes first, '
783 . "or stash them with `git stash'.\n";
787 if ($head ne 'HEAD') {
789 command_oneline([qw/symbolic-ref -q HEAD/])
792 $old_head =~ s{^refs/heads/}{};
794 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
796 command(['checkout', $head], STDERR => 0);
800 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
802 die "Unable to determine upstream SVN information from ",
803 "$head history.\nPerhaps the repository is empty.";
806 if (defined $_commit_url) {
809 $url = eval { command_oneline('config', '--get',
810 "svn-remote.$gs->{repo_id}.commiturl") };
812 $url = $gs->full_pushurl
816 my $last_rev = $_revision if defined $_revision;
818 print "Committing to $url ...\n";
820 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
821 if ($_no_rebase && scalar(@$linear_refs) > 1) {
822 warn "Attempting to commit more than one change while ",
823 "--no-rebase is enabled.\n",
824 "If these changes depend on each other, re-running ",
825 "without --no-rebase may be required."
828 if (defined $_interactive){
829 my $ask_default = "y";
830 foreach my $d (@$linear_refs){
831 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
835 command_close_pipe($fh, $ctx);
836 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
837 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
838 default => $ask_default);
839 die "Commit this patch reply required" unless defined $_;
848 my $expect_url = $url;
850 my $push_merge_info = eval {
851 command_oneline(qw/config --get svn.pushmergeinfo/)
853 if (not defined($push_merge_info)
854 or $push_merge_info eq "false"
855 or $push_merge_info eq "no"
856 or $push_merge_info eq "never") {
857 $push_merge_info = 0;
860 unless (defined($_merge_info) || ! $push_merge_info) {
861 # Preflight check of changes to ensure no issues with mergeinfo
862 # This includes check for uncommitted-to-SVN parents
863 # (other than the first parent, which we will handle),
864 # information from different SVN repos, and paths
865 # which are not underneath this repository root.
866 my $rooturl = $gs->repos_root;
867 foreach my $d (@$linear_refs) {
869 read_commit_parents(\%parentshash, $d);
870 my @realparents = @{$parentshash{$d}};
871 if ($#realparents > 0) {
873 shift @realparents; # Remove/ignore first parent
874 foreach my $parent (@realparents) {
875 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
876 unless (defined $paruuid) {
877 # A parent is missing SVN annotations...
878 # abort the whole operation.
879 fatal "$parent is merged into revision $d, "
880 ."but does not have git-svn metadata. "
881 ."Either dcommit the branch or use a "
882 ."local cherry-pick, FF merge, or rebase "
883 ."instead of an explicit merge commit.";
886 unless ($paruuid eq $uuid) {
887 # Parent has SVN metadata from different repository
888 fatal "merge parent $parent for change $d has "
889 ."git-svn uuid $paruuid, while current change "
893 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
894 # This branch is very strange indeed.
895 fatal "merge parent $parent for $d is on branch "
896 ."$branchurl, which is not under the "
897 ."git-svn root $rooturl!";
904 my $rewritten_parent;
905 Git::SVN::remove_username($expect_url);
906 if (defined($_merge_info)) {
907 $_merge_info =~ tr{ }{\n};
910 my $d = shift @$linear_refs or last;
911 unless (defined $last_rev) {
912 (undef, $last_rev, undef) = cmt_metadata("$d~1");
913 unless (defined $last_rev) {
914 fatal "Unable to extract revision information ",
919 print "diff-tree $d~1 $d\n";
923 unless (defined($_merge_info) || ! $push_merge_info) {
924 $_merge_info = populate_merge_info($d, $gs,
930 my %ed_opts = ( r => $last_rev,
931 log => get_commit_entry($d)->{log},
932 ra => Git::SVN::Ra->new($url),
933 config => SVN::Core::config_get_config(
934 $Git::SVN::Ra::config_dir
939 print "Committed r$_[0]\n";
942 mergeinfo => $_merge_info,
944 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
945 print "No changes\n$d~1 == $d\n";
946 } elsif ($parents->{$d} && @{$parents->{$d}}) {
947 $gs->{inject_parents_dcommit}->{$cmt_rev} =
950 $_fetch_all ? $gs->fetch_all : $gs->fetch;
951 $last_rev = $cmt_rev;
954 # we always want to rebase against the current HEAD,
955 # not any head that was passed to us
956 my @diff = command('diff-tree', $d,
960 @finish = rebase_cmd();
961 print STDERR "W: $d and ", $gs->refname,
962 " differ, using @finish:\n",
963 join("\n", @diff), "\n";
965 print "No changes between current HEAD and ",
967 "\nResetting to the latest ",
969 @finish = qw/reset --mixed/;
971 command_noisy(@finish, $gs->refname);
973 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
977 my ($url_, $rev_, $uuid_, $gs_) =
978 working_head_info('HEAD', \@refs);
979 my ($linear_refs_, $parents_) =
980 linearize_history($gs_, \@refs);
981 if (scalar(@$linear_refs) !=
982 scalar(@$linear_refs_)) {
983 fatal "# of revisions changed ",
985 join("\n", @$linear_refs),
987 join("\n", @$linear_refs_), "\n",
988 'If you are attempting to commit ',
989 "merges, try running:\n\t",
990 'git rebase --interactive',
991 '--preserve-merges ',
993 "\nBefore dcommitting";
995 if ($url_ ne $expect_url) {
996 if ($url_ eq $gs->metadata_url) {
998 "Accepting rewritten URL:",
1002 "URL mismatch after rebase:",
1003 " $url_ != $expect_url";
1006 if ($uuid_ ne $uuid) {
1007 fatal "uuid mismatch after rebase: ",
1012 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1013 my $new = $linear_refs_->[$i] or next;
1015 $parents->{$linear_refs->[$i]};
1025 my $new_head = command_oneline(qw/rev-parse HEAD/);
1026 my $new_is_symbolic = eval {
1027 command_oneline(qw/symbolic-ref -q HEAD/);
1029 if ($new_is_symbolic) {
1030 print "dcommitted the branch ", $head, "\n";
1032 print "dcommitted on a detached HEAD because you gave ",
1033 "a revision argument.\n",
1034 "The rewritten commit is: ", $new_head, "\n";
1036 command(['checkout', $old_head], STDERR => 0);
1039 unlink $gs->{index};
1043 my ($branch_name, $head) = @_;
1045 unless (defined $branch_name && length $branch_name) {
1046 die(($_tag ? "tag" : "branch") . " name required\n");
1050 my (undef, $rev, undef, $gs) = working_head_info($head);
1051 my $src = $gs->full_pushurl;
1053 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1054 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1056 if ($#{$allglobs} == 0) {
1057 $glob = $allglobs->[0];
1059 unless(defined $_branch_dest) {
1061 $_tag ? "tag" : "branch",
1062 " paths defined for Subversion repository.\n",
1063 "You must specify where you want to create the ",
1064 $_tag ? "tag" : "branch",
1065 " with the --destination argument.\n";
1067 foreach my $g (@{$allglobs}) {
1068 my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
1069 if ($_branch_dest =~ /$re/) {
1074 unless (defined $glob) {
1075 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1076 foreach my $g (@{$allglobs}) {
1077 $g->{path}->{left} =~ /$dest_re/ or next;
1078 if (defined $glob) {
1079 die "Ambiguous destination: ",
1080 $_branch_dest, "\nmatches both '",
1081 $glob->{path}->{left}, "' and '",
1082 $g->{path}->{left}, "'\n";
1086 unless (defined $glob) {
1088 $_tag ? "tag" : "branch",
1089 " destination $_branch_dest\n";
1093 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1095 if (defined $_commit_url) {
1096 $url = $_commit_url;
1098 $url = eval { command_oneline('config', '--get',
1099 "svn-remote.$gs->{repo_id}.commiturl") };
1101 $url = $remote->{pushurl} || $remote->{url};
1104 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1106 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1107 $src=~s/^http:/https:/;
1112 my $ctx = SVN::Client->new(
1113 auth => Git::SVN::Ra::_auth_providers(),
1115 ${ $_[0] } = defined $_message
1117 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1123 $ctx->ls($dst, 'HEAD', 0);
1124 } and die "branch ${branch_name} already exists\n";
1126 print "Copying ${src} at r${rev} to ${dst}...\n";
1127 $ctx->copy($src, $rev, $dst)
1134 my $revision_or_hash = shift or die "SVN or git revision required ",
1135 "as a command-line argument\n";
1137 if ($revision_or_hash =~ /^r\d+$/) {
1141 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1143 die "Unable to determine upstream SVN information from ",
1146 my $desired_revision = substr($revision_or_hash, 1);
1147 $result = $gs->rev_map_get($desired_revision, $uuid);
1149 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1152 print "$result\n" if $result;
1155 sub auto_create_empty_directories {
1157 my $var = eval { command_oneline('config', '--get', '--bool',
1158 "svn-remote.$gs->{repo_id}.automkdirs") };
1159 # By default, create empty directories by consulting the unhandled log,
1160 # but allow setting it to 'false' to skip it.
1161 return !($var && $var eq 'false');
1165 command_noisy(qw/update-index --refresh/);
1166 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1168 die "Unable to determine upstream SVN information from ",
1169 "working tree history\n";
1172 print "Remote Branch: " . $gs->refname . "\n";
1173 print "SVN URL: " . $url . "\n";
1176 if (command(qw/diff-index HEAD --/)) {
1177 print STDERR "Cannot rebase with uncommited changes:\n";
1178 command_noisy('status');
1182 # rebase will checkout for us, so no need to do it explicitly
1183 $_no_checkout = 'true';
1184 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1186 command_noisy(rebase_cmd(), $gs->refname);
1187 if (auto_create_empty_directories($gs)) {
1192 sub cmd_show_ignore {
1193 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1194 $gs ||= Git::SVN->new;
1195 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1196 $gs->prop_walk($gs->{path}, $r, sub {
1197 my ($gs, $path, $props) = @_;
1198 print STDOUT "\n# $path\n";
1199 my $s = $props->{'svn:ignore'} or return;
1200 $s =~ s/[\r\n]+/\n/g;
1204 print STDOUT "$s\n";
1208 sub cmd_show_externals {
1209 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1210 $gs ||= Git::SVN->new;
1211 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1212 $gs->prop_walk($gs->{path}, $r, sub {
1213 my ($gs, $path, $props) = @_;
1214 print STDOUT "\n# $path\n";
1215 my $s = $props->{'svn:externals'} or return;
1216 $s =~ s/[\r\n]+/\n/g;
1219 print STDOUT "$s\n";
1223 sub cmd_create_ignore {
1224 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1225 $gs ||= Git::SVN->new;
1226 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1227 $gs->prop_walk($gs->{path}, $r, sub {
1228 my ($gs, $path, $props) = @_;
1229 # $path is of the form /path/to/dir/
1230 $path = '.' . $path;
1231 # SVN can have attributes on empty directories,
1232 # which git won't track
1233 mkpath([$path]) unless -d $path;
1234 my $ignore = $path . '.gitignore';
1235 my $s = $props->{'svn:ignore'} or return;
1236 open(GITIGNORE, '>', $ignore)
1237 or fatal("Failed to open `$ignore' for writing: $!");
1238 $s =~ s/[\r\n]+/\n/g;
1241 # Prefix all patterns so that the ignore doesn't apply
1242 # to sub-directories.
1244 print GITIGNORE "$s\n";
1246 or fatal("Failed to close `$ignore': $!");
1247 command_noisy('add', '-f', $ignore);
1252 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1253 $gs ||= Git::SVN->new;
1254 $gs->mkemptydirs($_revision);
1257 sub canonicalize_path {
1259 my $dot_slash_added = 0;
1260 if (substr($path, 0, 1) ne "/") {
1261 $path = "./" . $path;
1262 $dot_slash_added = 1;
1264 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1265 # good reason), so let's do this manually.
1267 $path =~ s#/\.(?:/|$)#/#g;
1268 $path =~ s#/[^/]+/\.\.##g;
1270 $path =~ s#^\./## if $dot_slash_added;
1276 sub canonicalize_url {
1278 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1282 # get_svnprops(PATH)
1283 # ------------------
1284 # Helper for cmd_propget and cmd_proplist below.
1287 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1288 $gs ||= Git::SVN->new;
1290 # prefix THE PATH by the sub-directory from which the user
1292 $path = $cmd_dir_prefix . $path;
1293 fatal("No such file or directory: $path") unless -e $path;
1294 my $is_dir = -d $path ? 1 : 0;
1295 $path = $gs->{path} . '/' . $path;
1297 # canonicalize the path (otherwise libsvn will abort or fail to
1299 $path = canonicalize_path($path);
1301 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1304 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1307 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1312 # cmd_propget (PROP, PATH)
1313 # ------------------------
1314 # Print the SVN property PROP for PATH.
1316 my ($prop, $path) = @_;
1317 $path = '.' if not defined $path;
1318 usage(1) if not defined $prop;
1319 my $props = get_svnprops($path);
1320 if (not defined $props->{$prop}) {
1321 fatal("`$path' does not have a `$prop' SVN property.");
1323 print $props->{$prop} . "\n";
1326 # cmd_proplist (PATH)
1327 # -------------------
1328 # Print the list of SVN properties for PATH.
1331 $path = '.' if not defined $path;
1332 my $props = get_svnprops($path);
1333 print "Properties on '$path':\n";
1334 foreach (sort keys %{$props}) {
1339 sub cmd_multi_init {
1341 unless (defined $_trunk || @_branches || @_tags) {
1345 $_prefix = '' unless defined $_prefix;
1347 $url = canonicalize_url($url);
1351 if (defined $_trunk) {
1353 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1354 # try both old-style and new-style lookups:
1355 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1356 unless ($gs_trunk) {
1357 my ($trunk_url, $trunk_path) =
1358 complete_svn_url($url, $_trunk);
1359 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1363 return unless @_branches || @_tags;
1364 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1365 foreach my $path (@_branches) {
1366 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1368 foreach my $path (@_tags) {
1369 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1373 sub cmd_multi_fetch {
1374 $Git::SVN::no_reuse_existing = undef;
1375 my $remotes = Git::SVN::read_all_remotes();
1376 foreach my $repo_id (sort keys %$remotes) {
1377 if ($remotes->{$repo_id}->{url}) {
1378 Git::SVN::fetch_all($repo_id, $remotes);
1383 # this command is special because it requires no metadata
1384 sub cmd_commit_diff {
1385 my ($ta, $tb, $url) = @_;
1386 my $usage = "Usage: $0 commit-diff -r<revision> ".
1387 "<tree-ish> <tree-ish> [<URL>]";
1388 fatal($usage) if (!defined $ta || !defined $tb);
1390 if (!defined $url) {
1391 my $gs = eval { Git::SVN->new };
1393 fatal("Needed URL or usable git-svn --id in ",
1394 "the command-line\n", $usage);
1397 $svn_path = $gs->{path};
1399 unless (defined $_revision) {
1400 fatal("-r|--revision is a required argument\n", $usage);
1402 if (defined $_message && defined $_file) {
1403 fatal("Both --message/-m and --file/-F specified ",
1404 "for the commit message.\n",
1405 "I have no idea what you mean");
1407 if (defined $_file) {
1408 $_message = file_to_s($_file);
1410 $_message ||= get_commit_entry($tb)->{log};
1412 my $ra ||= Git::SVN::Ra->new($url);
1415 $r = $ra->get_latest_revnum;
1416 } elsif ($r !~ /^\d+$/) {
1417 die "revision argument: $r not understood by git-svn\n";
1419 my %ed_opts = ( r => $r,
1424 editor_cb => sub { print "Committed r$_[0]\n" },
1425 svn_path => $svn_path );
1426 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
1427 print "No changes\n$ta == $tb\n";
1431 sub escape_uri_only {
1434 foreach (split m{/}, $uri) {
1435 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1443 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1444 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1445 $url = "$scheme://$domain$uri";
1451 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1452 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1454 die "Too many arguments specified\n";
1457 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1459 if (!$file_type && !$diff_status) {
1460 print STDERR "svn: '$path' is not under version control\n";
1464 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1466 die "Unable to determine upstream SVN information from ",
1467 "working tree history\n";
1470 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1471 $path = "." if $path eq "";
1473 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1476 print escape_url($full_url), "\n";
1480 my $result = "Path: $path\n";
1481 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1482 $result .= "URL: " . escape_url($full_url) . "\n";
1485 my $repos_root = $gs->repos_root;
1486 Git::SVN::remove_username($repos_root);
1487 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1490 $result .= "Repository Root: (offline)\n";
1493 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1494 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1495 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1497 $result .= "Node Kind: " .
1498 ($file_type eq "dir" ? "directory" : "file") . "\n";
1500 my $schedule = $diff_status eq "A"
1502 : ($diff_status eq "D" ? "delete" : "normal");
1503 $result .= "Schedule: $schedule\n";
1505 if ($diff_status eq "A") {
1506 print $result, "\n";
1510 my ($lc_author, $lc_rev, $lc_date_utc);
1511 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1512 my $log = command_output_pipe(@args);
1513 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1515 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1517 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1518 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1519 (undef, $lc_rev, undef) = ::extract_metadata($1);
1524 Git::SVN::Log::set_local_timezone();
1526 $result .= "Last Changed Author: $lc_author\n";
1527 $result .= "Last Changed Rev: $lc_rev\n";
1528 $result .= "Last Changed Date: " .
1529 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1531 if ($file_type ne "dir") {
1532 my $text_last_updated_date =
1533 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1535 "Text Last Updated: " .
1536 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1539 if ($diff_status eq "D") {
1541 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1542 if ($file_type eq "link") {
1543 my $file_name = <$fh>;
1544 $checksum = md5sum("link $file_name");
1546 $checksum = md5sum($fh);
1548 command_close_pipe($fh, $ctx);
1549 } elsif ($file_type eq "link") {
1551 command(qw(cat-file blob), "HEAD:$path");
1553 md5sum("link " . $file_name);
1555 open FILE, "<", $path or die $!;
1556 $checksum = md5sum(\*FILE);
1557 close FILE or die $!;
1559 $result .= "Checksum: " . $checksum . "\n";
1562 print $result, "\n";
1566 my $target = shift || $_revision or die "SVN revision required\n";
1567 $target = $1 if $target =~ /^r(\d+)$/;
1568 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1569 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1571 die "Unable to determine upstream SVN information from ".
1574 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1575 die "Cannot find SVN revision $target\n" unless defined($c);
1576 $gs->rev_map_set($r, $c, 'reset', $uuid);
1577 print "r$r = $c ($gs->{ref_id})\n";
1581 if (!$can_compress) {
1582 warn "Compress::Zlib could not be found; unhandled.log " .
1583 "files will not be compressed.\n";
1585 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1588 ########################### utility functions #########################
1591 my @cmd = qw/rebase/;
1592 push @cmd, '-v' if $_verbose;
1593 push @cmd, qw/--merge/ if $_merge;
1594 push @cmd, "--strategy=$_strategy" if $_strategy;
1595 push @cmd, "--preserve-merges" if $_preserve_merges;
1599 sub post_fetch_checkout {
1600 return if $_no_checkout;
1601 return if verify_ref('HEAD^0');
1602 my $gs = $Git::SVN::_head or return;
1604 # look for "trunk" ref if it exists
1605 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1606 my $fetch = $remote->{fetch};
1608 foreach my $p (keys %$fetch) {
1609 basename($fetch->{$p}) eq 'trunk' or next;
1610 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1615 command_noisy(qw(update-ref HEAD), $gs->refname);
1616 return unless verify_ref('HEAD^0');
1618 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1619 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1620 return if -f $index;
1622 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1623 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1624 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1625 print STDERR "Checked out HEAD:\n ",
1626 $gs->full_url, " r", $gs->last_rev, "\n";
1627 if (auto_create_empty_directories($gs)) {
1628 $gs->mkemptydirs($gs->last_rev);
1632 sub complete_svn_url {
1633 my ($url, $path) = @_;
1635 if ($path !~ m#^[a-z\+]+://#) {
1636 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1637 fatal("E: '$path' is not a complete URL ",
1638 "and a separate URL is not specified");
1640 return ($url, $path);
1645 sub complete_url_ls_init {
1646 my ($ra, $repo_path, $switch, $pfx) = @_;
1647 unless ($repo_path) {
1648 print STDERR "W: $switch not specified\n";
1651 $repo_path =~ s#/+$##;
1652 if ($repo_path =~ m#^[a-z\+]+://#) {
1653 $ra = Git::SVN::Ra->new($repo_path);
1656 $repo_path =~ s#^/+##;
1658 fatal("E: '$repo_path' is not a complete URL ",
1659 "and a separate URL is not specified");
1662 my $url = $ra->{url};
1663 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1664 my $k = "svn-remote.$gs->{repo_id}.url";
1665 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1666 if ($orig_url && ($orig_url ne $gs->{url})) {
1667 die "$k already set: $orig_url\n",
1668 "wanted to set to: $gs->{url}\n";
1670 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1671 my $remote_path = "$gs->{path}/$repo_path";
1672 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1673 $remote_path =~ s#/+#/#g;
1674 $remote_path =~ s#^/##g;
1675 $remote_path .= "/*" if $remote_path !~ /\*/;
1676 my ($n) = ($switch =~ /^--(\w+)/);
1677 if (length $pfx && $pfx !~ m#/$#) {
1678 die "--prefix='$pfx' must have a trailing slash '/'\n";
1680 command_noisy('config',
1682 "svn-remote.$gs->{repo_id}.$n",
1683 "$remote_path:refs/remotes/$pfx*" .
1684 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1689 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1690 { STDERR => 0 }); };
1693 sub get_tree_from_treeish {
1695 # $treeish can be a symbolic ref, too:
1696 my $type = command_oneline(qw/cat-file -t/, $treeish);
1698 while ($type eq 'tag') {
1699 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1701 if ($type eq 'commit') {
1702 $expected = (grep /^tree /, command(qw/cat-file commit/,
1704 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1705 die "Unable to get tree from $treeish\n" unless $expected;
1706 } elsif ($type eq 'tree') {
1707 $expected = $treeish;
1709 die "$treeish is a $type, expected tree, tag or commit\n";
1714 sub get_commit_entry {
1715 my ($treeish) = shift;
1716 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1717 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1718 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1719 open my $log_fh, '>', $commit_editmsg or croak $!;
1721 my $type = command_oneline(qw/cat-file -t/, $treeish);
1722 if ($type eq 'commit' || $type eq 'tag') {
1723 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1731 $in_msg = 1 if (/^\s*$/);
1732 $author = $1 if (/^author (.*>)/);
1733 } elsif (/^git-svn-id: /) {
1734 # skip this for now, we regenerate the
1735 # correct one on re-fetch anyways
1736 # TODO: set *:merge properties or like...
1738 if (/^From:/ || /^Signed-off-by:/) {
1744 $msgbuf =~ s/\s+$//s;
1745 if ($Git::SVN::_add_author_from && defined($author)
1747 $msgbuf .= "\n\nFrom: $author";
1749 print $log_fh $msgbuf or croak $!;
1750 command_close_pipe($msg_fh, $ctx);
1752 close $log_fh or croak $!;
1754 if ($_edit || ($type eq 'tree')) {
1755 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1756 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1758 rename $commit_editmsg, $commit_msg or croak $!;
1761 # SVN requires messages to be UTF-8 when entering the repo
1763 open $log_fh, '<', $commit_msg or croak $!;
1765 chomp($log_entry{log} = <$log_fh>);
1767 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1768 my $msg = $log_entry{log};
1770 eval { $msg = Encode::decode($enc, $msg, 1) };
1772 die "Could not decode as $enc:\n", $msg,
1773 "\nPerhaps you need to set i18n.commitencoding\n";
1776 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1777 die "Could not encode as UTF-8:\n$msg\n" if $@;
1779 $log_entry{log} = $msg;
1781 close $log_fh or croak $!;
1788 my ($str, $file, $mode) = @_;
1789 open my $fd,'>',$file or croak $!;
1790 print $fd $str,"\n" or croak $!;
1791 close $fd or croak $!;
1792 chmod ($mode &~ umask, $file) if (defined $mode);
1797 open my $fd,'<',$file or croak "$!: file: $file\n";
1800 close $fd or croak $!;
1805 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1807 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1808 my $log = $cmd eq 'log';
1809 while (<$authors>) {
1811 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1812 my ($user, $name, $email) = ($1, $2, $3);
1814 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1816 $users{$user} = [$name, $email];
1819 close $authors or croak $!;
1822 # convert GetOpt::Long specs for use by git-config
1823 sub read_git_config {
1826 foreach my $o (keys %$opts) {
1827 # if we have mixedCase and a long option-only, then
1828 # it's a config-only variable that we don't need for
1830 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1831 my $v = $opts->{$o};
1832 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1834 my $arg = 'git config';
1835 $arg .= ' --int' if ($o =~ /[:=]i$/);
1836 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1837 if (ref $v eq 'ARRAY') {
1838 chomp(my @tmp = `$arg --get-all svn.$key`);
1841 chomp(my $tmp = `$arg --get svn.$key`);
1842 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1847 delete @$opts{@config_only} if @config_only;
1850 sub extract_metadata {
1851 my $id = shift or return (undef, undef, undef);
1852 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1853 \s([a-f\d\-]+)$/ix);
1854 if (!defined $rev || !$uuid || !$url) {
1855 # some of the original repositories I made had
1856 # identifiers like this:
1857 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1859 return ($url, $rev, $uuid);
1863 return extract_metadata((grep(/^git-svn-id: /,
1864 command(qw/cat-file commit/, shift)))[-1]);
1867 sub cmt_sha2rev_batch {
1869 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1872 foreach my $sha (@{$list}) {
1875 print $out $sha, "\n";
1877 while (my $line = <$in>) {
1878 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1881 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1885 } elsif ($line =~ /^(git-svn-id: )/) {
1886 my (undef, $rev, undef) =
1887 extract_metadata($line);
1891 $size -= length($line);
1892 last if ($size == 0);
1896 command_close_bidi_pipe($pid, $in, $out, $ctx);
1901 sub working_head_info {
1902 my ($head, $refs) = @_;
1903 my @args = qw/rev-list --first-parent --pretty=medium/;
1904 my ($fh, $ctx) = command_output_pipe(@args, $head);
1908 if ( m{^commit ($::sha1)$} ) {
1909 unshift @$refs, $hash if $hash and $refs;
1913 next unless s{^\s*(git-svn-id:)}{$1};
1914 my ($url, $rev, $uuid) = extract_metadata($_);
1915 if (defined $url && defined $rev) {
1916 next if $max{$url} and $max{$url} < $rev;
1917 if (my $gs = Git::SVN->find_by_url($url)) {
1918 my $c = $gs->rev_map_get($rev, $uuid);
1919 if ($c && $c eq $hash) {
1920 close $fh; # break the pipe
1921 return ($url, $rev, $uuid, $gs);
1923 $max{$url} ||= $gs->rev_map_max;
1928 command_close_pipe($fh, $ctx);
1929 (undef, undef, undef, undef);
1932 sub read_commit_parents {
1933 my ($parents, $c) = @_;
1934 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1935 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1936 @{$parents->{$c}} = split(/ /, $p);
1939 sub linearize_history {
1940 my ($gs, $refs) = @_;
1942 foreach my $c (@$refs) {
1943 read_commit_parents(\%parents, $c);
1948 my $last_svn_commit = $gs->last_commit;
1949 foreach my $c (reverse @$refs) {
1950 next if $c eq $last_svn_commit;
1953 unshift @linear_refs, $c;
1956 # we only want the first parent to diff against for linear
1957 # history, we save the rest to inject when we finalize the
1959 my $fp_a = verify_ref("$c~1");
1960 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1961 if (!$fp_a || !$fp_b) {
1963 "has no parent commit, and therefore ",
1964 "nothing to diff against.\n",
1965 "You should be working from a repository ",
1966 "originally created by git-svn\n";
1968 if ($fp_a ne $fp_b) {
1969 die "$c~1 = $fp_a, however parsing commit $c ",
1970 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1973 foreach my $p (@{$parents{$c}}) {
1977 (\@linear_refs, \%parents);
1980 sub find_file_type_and_diff_status {
1982 return ('dir', '') if $path eq '';
1985 command_oneline(qw(diff --cached --name-status --), $path) || "";
1986 my $diff_status = (split(' ', $diff_output))[0] || "";
1988 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1990 return (undef, undef) if !$diff_status && !$ls_tree;
1992 if ($diff_status eq "A") {
1993 return ("link", $diff_status) if -l $path;
1994 return ("dir", $diff_status) if -d $path;
1995 return ("file", $diff_status);
1998 my $mode = (split(' ', $ls_tree))[0] || "";
2000 return ("link", $diff_status) if $mode eq "120000";
2001 return ("dir", $diff_status) if $mode eq "040000";
2002 return ("file", $diff_status);
2008 my $md5 = Digest::MD5->new();
2009 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2010 $md5->addfile($arg) or croak $!;
2011 } elsif ($ref eq 'SCALAR') {
2012 $md5->add($$arg) or croak $!;
2014 $md5->add($arg) or croak $!;
2016 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2018 return $md5->hexdigest();
2022 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2023 my $out_filename = $_ . ".gz";
2024 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2026 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2027 die "Unable to open $out_filename: $!\n";
2030 while ($res = sysread($in_fh, my $str, 1024)) {
2031 $gz->gzwrite($str) or
2032 die "Unable to write: ".$gz->gzerror()."!\n";
2034 unlink $_ or die "unlink $File::Find::name: $!\n";
2035 } elsif (-f $_ && basename($_) eq "index") {
2036 unlink $_ or die "unlink $_: $!\n";
2043 use Fcntl qw/:DEFAULT :seek/;
2044 use constant rev_map_fmt => 'NH40';
2045 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2046 $_repack $_repack_flags $_use_svm_props $_head
2047 $_use_svnsync_props $no_reuse_existing $_minimize_url
2048 $_use_log_author $_add_author_from $_localtime/;
2050 use File::Path qw/mkpath/;
2051 use File::Copy qw/copy/;
2054 use Memoize; # core since 5.8.0, Jul 2002
2055 use Memoize::Storable;
2056 use POSIX qw(:signal_h);
2059 $can_use_yaml = eval { require Git::SVN::Memoize::YAML; 1};
2062 my ($_gc_nr, $_gc_period);
2064 # properties that we do not log:
2067 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2068 svn:special svn:executable
2069 svn:entry:committed-rev
2070 svn:entry:last-author
2072 svn:entry:committed-date/;
2074 # some options are read globally, but can be overridden locally
2075 # per [svn-remote "..."] section. Command-line options will *NOT*
2076 # override options set in an [svn-remote "..."] section
2078 for my $option (qw/follow_parent no_metadata use_svm_props
2079 use_svnsync_props/) {
2082 my $prop = "-$option";
2085 return $self->{$prop} if exists $self->{$prop};
2086 my $k = "svn-remote.$self->{repo_id}.$key";
2087 eval { command_oneline(qw/config --get/, $k) };
2089 $self->{$prop} = ${"Git::SVN::_$option"};
2091 my $v = command_oneline(qw/config --bool/,$k);
2092 $self->{$prop} = $v eq 'false' ? 0 : 1;
2094 return $self->{$prop};
2100 my (%LOCKFILES, %INDEX_FILES);
2102 unlink keys %LOCKFILES if %LOCKFILES;
2103 unlink keys %INDEX_FILES if %INDEX_FILES;
2106 sub resolve_local_globs {
2107 my ($url, $fetch, $glob_spec) = @_;
2108 return unless defined $glob_spec;
2109 my $ref = $glob_spec->{ref};
2110 my $path = $glob_spec->{path};
2111 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2112 next unless m#^$ref->{regex}$#;
2114 my $pathname = desanitize_refname($path->full_path($p));
2115 my $refname = desanitize_refname($ref->full_path($p));
2116 if (my $existing = $fetch->{$pathname}) {
2117 if ($existing ne $refname) {
2118 die "Refspec conflict:\n",
2119 "existing: $existing\n",
2120 " globbed: $refname\n";
2122 my $u = (::cmt_metadata("$refname"))[0];
2123 $u =~ s!^\Q$url\E(/|$)!! or die
2124 "$refname: '$url' not found in '$u'\n";
2125 if ($pathname ne $u) {
2126 warn "W: Refspec glob conflict ",
2127 "(ref: $refname):\n",
2128 "expected path: $pathname\n",
2130 "Continuing ahead with $u\n";
2134 $fetch->{$pathname} = $refname;
2139 sub parse_revision_argument {
2140 my ($base, $head) = @_;
2141 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2142 return ($base, $head);
2144 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2145 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2146 return ($head, $head) if ($::_revision eq 'HEAD');
2147 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2148 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2149 die "revision argument: $::_revision not understood by git-svn\n";
2153 my ($repo_id, $remotes) = @_;
2157 $repo_id = $gs->{repo_id};
2159 $remotes ||= read_all_remotes();
2160 my $remote = $remotes->{$repo_id} or
2161 die "[svn-remote \"$repo_id\"] unknown\n";
2162 my $fetch = $remote->{fetch};
2163 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2165 my $ra = Git::SVN::Ra->new($url);
2166 my $uuid = $ra->get_uuid;
2167 my $head = $ra->get_latest_revnum;
2169 # ignore errors, $head revision may not even exist anymore
2170 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2171 warn "W: $@\n" if $@;
2173 my $base = defined $fetch ? $head : 0;
2175 # read the max revs for wildcard expansion (branches/*, tags/*)
2176 foreach my $t (qw/branches tags/) {
2177 defined $remote->{$t} or next;
2178 push @globs, @{$remote->{$t}};
2180 my $max_rev = eval { tmp_config(qw/--int --get/,
2181 "svn-remote.$repo_id.${t}-maxRev") };
2182 if (defined $max_rev && ($max_rev < $base)) {
2184 } elsif (!defined $max_rev) {
2190 foreach my $p (sort keys %$fetch) {
2191 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2192 my $lr = $gs->rev_map_max;
2194 $base = $lr if ($lr < $base);
2200 ($base, $head) = parse_revision_argument($base, $head);
2201 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2204 sub read_all_remotes {
2206 my $use_svm_props = eval { command_oneline(qw/config --bool
2207 svn.useSvmProps/) };
2208 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2209 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2210 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2211 if (m!^(.+)\.fetch=$svn_refspec$!) {
2212 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2213 die("svn-remote.$remote: remote ref '$remote_ref' "
2214 . "must start with 'refs/'\n")
2215 unless $remote_ref =~ m{^refs/};
2216 $local_ref = uri_decode($local_ref);
2217 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2218 $r->{$remote}->{svm} = {} if $use_svm_props;
2219 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2220 $r->{$1}->{svm} = {};
2221 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2222 $r->{$1}->{url} = $2;
2223 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2224 $r->{$1}->{pushurl} = $2;
2225 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2226 $r->{$1}->{ignore_refs_regex} = $2;
2227 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2228 my ($remote, $t, $local_ref, $remote_ref) =
2230 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2231 . "must start with 'refs/'\n")
2232 unless $remote_ref =~ m{^refs/};
2233 $local_ref = uri_decode($local_ref);
2237 path => Git::SVN::GlobSpec->new($local_ref, 1),
2238 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2239 if (length($rs->{ref}->{right}) != 0) {
2240 die "The '*' glob character must be the last ",
2241 "character of '$remote_ref'\n";
2243 push @{ $r->{$remote}->{$t} }, $rs;
2248 if (defined $r->{$_}->{svm}) {
2251 my $section = "svn-remote.$_";
2253 source => tmp_config('--get',
2254 "$section.svm-source"),
2255 replace => tmp_config('--get',
2256 "$section.svm-replace"),
2259 $r->{$_}->{svm} = $svm;
2263 foreach my $remote (keys %$r) {
2264 foreach ( grep { defined $_ }
2265 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2266 foreach my $rs ( @$_ ) {
2267 $rs->{ignore_refs_regex} =
2268 $r->{$remote}->{ignore_refs_regex};
2277 $_gc_nr = $_gc_period = 1000;
2278 if (defined $_repack || defined $_repack_flags) {
2279 warn "Repack options are obsolete; they have no effect.\n";
2283 sub verify_remotes_sanity {
2284 return unless -d $ENV{GIT_DIR};
2286 foreach (command(qw/config -l/)) {
2287 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2289 die "Remote ref refs/remote/$1 is tracked by",
2290 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2291 "Please resolve this ambiguity in ",
2292 "your git configuration file before ",
2300 sub find_existing_remote {
2301 my ($url, $remotes) = @_;
2302 return undef if $no_reuse_existing;
2304 foreach my $repo_id (keys %$remotes) {
2305 my $u = $remotes->{$repo_id}->{url} or next;
2307 $existing = $repo_id;
2313 sub init_remote_config {
2314 my ($self, $url, $no_write) = @_;
2315 $url =~ s!/+$!!; # strip trailing slash
2316 my $r = read_all_remotes();
2317 my $existing = find_existing_remote($url, $r);
2319 unless ($no_write) {
2320 print STDERR "Using existing ",
2321 "[svn-remote \"$existing\"]\n";
2323 $self->{repo_id} = $existing;
2324 } elsif ($_minimize_url) {
2325 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2326 $existing = find_existing_remote($min_url, $r);
2328 unless ($no_write) {
2329 print STDERR "Using existing ",
2330 "[svn-remote \"$existing\"]\n";
2332 $self->{repo_id} = $existing;
2334 if ($min_url ne $url) {
2335 unless ($no_write) {
2336 print STDERR "Using higher level of URL: ",
2337 "$url => $min_url\n";
2339 my $old_path = $self->{path};
2340 $self->{path} = $url;
2341 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2342 if (length $old_path) {
2343 $self->{path} .= "/$old_path";
2350 # verify that we aren't overwriting anything:
2352 command_oneline('config', '--get',
2353 "svn-remote.$self->{repo_id}.url")
2355 if ($orig_url && ($orig_url ne $url)) {
2356 die "svn-remote.$self->{repo_id}.url already set: ",
2357 "$orig_url\nwanted to set to: $url\n";
2360 my ($xrepo_id, $xpath) = find_ref($self->refname);
2361 if (!$no_write && defined $xpath) {
2362 die "svn-remote.$xrepo_id.fetch already set to track ",
2363 "$xpath:", $self->refname, "\n";
2365 unless ($no_write) {
2366 command_noisy('config',
2367 "svn-remote.$self->{repo_id}.url", $url);
2368 $self->{path} =~ s{^/}{};
2369 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2370 command_noisy('config', '--add',
2371 "svn-remote.$self->{repo_id}.fetch",
2372 "$self->{path}:".$self->refname);
2374 $self->{url} = $url;
2377 sub find_by_url { # repos_root and, path are optional
2378 my ($class, $full_url, $repos_root, $path) = @_;
2380 return undef unless defined $full_url;
2381 remove_username($full_url);
2382 remove_username($repos_root) if defined $repos_root;
2383 my $remotes = read_all_remotes();
2384 if (defined $full_url && defined $repos_root && !defined $path) {
2386 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2388 foreach my $repo_id (keys %$remotes) {
2389 my $u = $remotes->{$repo_id}->{url} or next;
2390 remove_username($u);
2391 next if defined $repos_root && $repos_root ne $u;
2393 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2394 foreach my $t (qw/branches tags/) {
2395 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2396 resolve_local_globs($u, $fetch, $globspec);
2400 my $rwr = rewrite_root({repo_id => $repo_id});
2401 my $svm = $remotes->{$repo_id}->{svm}
2402 if defined $remotes->{$repo_id}->{svm};
2403 unless (defined $p) {
2409 remove_username($z);
2410 } elsif (defined $svm) {
2411 $z = $svm->{source};
2412 $prefix = $svm->{replace};
2413 $prefix =~ s#^\Q$u\E(?:/|$)##;
2416 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2418 foreach my $f (keys %$fetch) {
2420 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2427 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2428 my $self = _new($class, $repo_id, $ref_id, $path);
2430 $self->init_remote_config($url, $no_write);
2437 foreach (command(qw/config -l/)) {
2438 next unless m!^svn-remote\.(.+)\.fetch=
2439 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2440 my ($repo_id, $path, $ref) = ($1, $2, $3);
2441 if ($ref eq $ref_id) {
2442 $path = '' if ($path =~ m#^\./?#);
2443 return ($repo_id, $path);
2446 (undef, undef, undef);
2450 my ($class, $ref_id, $repo_id, $path) = @_;
2451 if (defined $ref_id && !defined $repo_id && !defined $path) {
2452 ($repo_id, $path) = find_ref($ref_id);
2453 if (!defined $repo_id) {
2454 die "Could not find a \"svn-remote.*.fetch\" key ",
2455 "in the repository configuration matching: ",
2459 my $self = _new($class, $repo_id, $ref_id, $path);
2460 if (!defined $self->{path} || !length $self->{path}) {
2461 my $fetch = command_oneline('config', '--get',
2462 "svn-remote.$repo_id.fetch",
2464 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2465 "\":$ref_id\$\" in config\n";
2466 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2468 $self->{path} =~ s{/+}{/}g;
2469 $self->{path} =~ s{\A/}{};
2470 $self->{path} =~ s{/\z}{};
2471 $self->{url} = command_oneline('config', '--get',
2472 "svn-remote.$repo_id.url") or
2473 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2474 $self->{pushurl} = eval { command_oneline('config', '--get',
2475 "svn-remote.$repo_id.pushurl") };
2481 my ($refname) = $_[0]->{ref_id} ;
2483 # It cannot end with a slash /, we'll throw up on this because
2484 # SVN can't have directories with a slash in their name, either:
2485 if ($refname =~ m{/$}) {
2486 die "ref: '$refname' ends with a trailing slash, this is ",
2487 "not permitted by git nor Subversion\n";
2490 # It cannot have ASCII control character space, tilde ~, caret ^,
2491 # colon :, question-mark ?, asterisk *, space, or open bracket [
2494 # Additionally, % must be escaped because it is used for escaping
2495 # and we want our escaped refname to be reversible
2496 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2498 # no slash-separated component can begin with a dot .
2500 $refname =~ s{/\.}{/%2E}g;
2502 # It cannot have two consecutive dots .. anywhere
2504 $refname =~ s{\.\.}{%2E%2E}g;
2506 # trailing dots and .lock are not allowed
2507 # .$ becomes %2E and .lock becomes %2Elock
2508 $refname =~ s{\.(?=$|lock$)}{%2E};
2510 # the sequence @{ is used to access the reflog
2512 $refname =~ s{\@\{}{%40\{}g;
2517 sub desanitize_refname {
2519 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2525 return $self->{svm}->{uuid} if $self->svm;
2527 unless ($self->{svm}) {
2528 die "SVM UUID not cached, and reading remotely failed\n";
2530 $self->{svm}->{uuid};
2535 return $self->{svm} if $self->{svm};
2537 # see if we have it in our config, first:
2539 my $section = "svn-remote.$self->{repo_id}";
2541 source => tmp_config('--get', "$section.svm-source"),
2542 uuid => tmp_config('--get', "$section.svm-uuid"),
2543 replace => tmp_config('--get', "$section.svm-replace"),
2546 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2547 $self->{svm} = $svm;
2553 my ($self, $ra) = @_;
2554 return $ra if $self->svm;
2556 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2557 "(svm:source, svm:uuid) ",
2558 "from the following URLs:\n" );
2559 sub read_svm_props {
2560 my ($self, $ra, $path, $r) = @_;
2561 my $props = ($ra->get_dir($path, $r))[2];
2562 my $src = $props->{'svm:source'};
2563 my $uuid = $props->{'svm:uuid'};
2564 return undef if (!$src || !$uuid);
2568 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2569 or die "doesn't look right - svm:uuid is '$uuid'\n";
2571 # the '!' is used to mark the repos_root!/relative/path
2572 $src =~ s{/?!/?}{/};
2573 $src =~ s{/+$}{}; # no trailing slashes please
2574 # username is of no interest
2575 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2577 my $replace = $ra->{url};
2578 $replace .= "/$path" if length $path;
2580 my $section = "svn-remote.$self->{repo_id}";
2581 tmp_config("$section.svm-source", $src);
2582 tmp_config("$section.svm-replace", $replace);
2583 tmp_config("$section.svm-uuid", $uuid);
2591 my $r = $ra->get_latest_revnum;
2592 my $path = $self->{path};
2594 while (length $path) {
2595 unless ($tried{"$self->{url}/$path"}) {
2596 return $ra if $self->read_svm_props($ra, $path, $r);
2597 $tried{"$self->{url}/$path"} = 1;
2599 $path =~ s#/?[^/]+$##;
2601 die "Path: '$path' should be ''\n" if $path ne '';
2602 return $ra if $self->read_svm_props($ra, $path, $r);
2603 $tried{"$self->{url}/$path"} = 1;
2605 if ($ra->{repos_root} eq $self->{url}) {
2606 die @err, (map { " $_\n" } keys %tried), "\n";
2609 # nope, make sure we're connected to the repository root:
2612 $path = $ra->{svn_path};
2613 $ra = Git::SVN::Ra->new($ra->{repos_root});
2614 while (length $path) {
2615 unless ($tried{"$ra->{url}/$path"}) {
2616 $ok = $self->read_svm_props($ra, $path, $r);
2618 $tried{"$ra->{url}/$path"} = 1;
2620 $path =~ s#/?[^/]+$##;
2622 die "Path: '$path' should be ''\n" if $path ne '';
2623 $ok ||= $self->read_svm_props($ra, $path, $r);
2624 $tried{"$ra->{url}/$path"} = 1;
2626 die @err, (map { " $_\n" } keys %tried), "\n";
2628 Git::SVN::Ra->new($self->{url});
2633 return $self->{svnsync} if $self->{svnsync};
2635 if ($self->no_metadata) {
2636 die "Can't have both 'noMetadata' and ",
2637 "'useSvnsyncProps' options set!\n";
2639 if ($self->rewrite_root) {
2640 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2643 if ($self->rewrite_uuid) {
2644 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2649 # see if we have it in our config, first:
2651 my $section = "svn-remote.$self->{repo_id}";
2653 my $url = tmp_config('--get', "$section.svnsync-url");
2654 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2655 die "doesn't look right - svn:sync-from-url is '$url'\n";
2657 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2658 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2659 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2661 $svnsync = { url => $url, uuid => $uuid }
2663 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2664 return $self->{svnsync} = $svnsync;
2667 my $err = "useSvnsyncProps set, but failed to read " .
2668 "svnsync property: svn:sync-from-";
2669 my $rp = $self->ra->rev_proplist(0);
2671 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2672 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2673 die "doesn't look right - svn:sync-from-url is '$url'\n";
2675 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2676 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2677 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2679 my $section = "svn-remote.$self->{repo_id}";
2680 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2681 tmp_config('--add', "$section.svnsync-url", $url);
2682 return $self->{svnsync} = { url => $url, uuid => $uuid };
2685 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2686 # remote lookup (useful for 'git svn log').
2689 unless ($self->{ra_uuid}) {
2690 my $key = "svn-remote.$self->{repo_id}.uuid";
2691 my $uuid = eval { tmp_config('--get', $key) };
2692 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2693 $self->{ra_uuid} = $uuid;
2695 die "ra_uuid called without URL\n" unless $self->{url};
2696 $self->{ra_uuid} = $self->ra->get_uuid;
2697 tmp_config('--add', $key, $self->{ra_uuid});
2703 sub _set_repos_root {
2704 my ($self, $repos_root) = @_;
2705 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2706 $repos_root ||= $self->ra->{repos_root};
2707 tmp_config($k, $repos_root);
2713 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2714 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2719 my $ra = Git::SVN::Ra->new($self->{url});
2720 $self->_set_repos_root($ra->{repos_root});
2721 if ($self->use_svm_props && !$self->{svm}) {
2722 if ($self->no_metadata) {
2723 die "Can't have both 'noMetadata' and ",
2724 "'useSvmProps' options set!\n";
2725 } elsif ($self->use_svnsync_props) {
2726 die "Can't have both 'useSvnsyncProps' and ",
2727 "'useSvmProps' options set!\n";
2729 $ra = $self->_set_svm_vars($ra);
2730 $self->{-want_revprops} = 1;
2735 # prop_walk(PATH, REV, SUB)
2736 # -------------------------
2737 # Recursively traverse PATH at revision REV and invoke SUB for each
2738 # directory that contains a SVN property. SUB will be invoked as
2739 # follows: &SUB(gs, path, props); where `gs' is this instance of
2740 # Git::SVN, `path' the path to the directory where the properties
2741 # `props' were found. The `path' will be relative to point of checkout,
2742 # that is, if url://repo/trunk is the current Git branch, and that
2743 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2744 # as `path' (note the trailing `/').
2746 my ($self, $path, $rev, $sub) = @_;
2749 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2752 # Strip the irrelevant part of the path.
2753 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2754 # Ensure the path is terminated by a `/'.
2757 # The properties contain all the internal SVN stuff nobody
2758 # (usually) cares about.
2759 my $interesting_props = 0;
2760 foreach (keys %{$props}) {
2761 # If it doesn't start with `svn:', it must be a
2762 # user-defined property.
2763 ++$interesting_props and next if $_ !~ /^svn:/;
2764 # FIXME: Fragile, if SVN adds new public properties,
2765 # this needs to be updated.
2766 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2767 |eol-style|mime-type
2768 |externals|needs-lock)$/x;
2770 &$sub($self, $p, $props) if $interesting_props;
2772 foreach (sort keys %$dirent) {
2773 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2774 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2778 sub last_rev { ($_[0]->last_rev_commit)[0] }
2779 sub last_commit { ($_[0]->last_rev_commit)[1] }
2781 # returns the newest SVN revision number and newest commit SHA1
2782 sub last_rev_commit {
2784 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2785 return ($self->{last_rev}, $self->{last_commit});
2787 my $c = ::verify_ref($self->refname.'^0');
2788 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2789 my $rev = (::cmt_metadata($c))[1];
2791 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2795 my $map_path = $self->map_path;
2796 unless (-e $map_path) {
2797 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2798 return (undef, undef);
2800 my ($rev, $commit) = $self->rev_map_max(1);
2801 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2802 return ($rev, $commit);
2805 sub get_fetch_range {
2806 my ($self, $min, $max) = @_;
2807 $max ||= $self->ra->get_latest_revnum;
2808 $min ||= $self->rev_map_max;
2814 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2815 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2816 if (! -f $config && -f $old_def_config) {
2817 rename $old_def_config, $config or
2818 die "Failed rename $old_def_config => $config: $!\n";
2820 my $old_config = $ENV{GIT_CONFIG};
2821 $ENV{GIT_CONFIG} = $config;
2824 unless (-f $config) {
2826 open my $fh, '>', $config or
2827 die "Can't open $config: $!\n";
2828 print $fh "; This file is used internally by ",
2830 "Couldn't write to $config: $!\n";
2831 print $fh "; You should not have to edit it\n" or
2832 die "Couldn't write to $config: $!\n";
2833 close $fh or die "Couldn't close $config: $!\n";
2835 command('config', @args);
2838 if (defined $old_config) {
2839 $ENV{GIT_CONFIG} = $old_config;
2841 delete $ENV{GIT_CONFIG};
2844 wantarray ? @ret : $ret[0];
2848 my ($self, $sub) = @_;
2849 my $old_index = $ENV{GIT_INDEX_FILE};
2850 $ENV{GIT_INDEX_FILE} = $self->{index};
2853 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2854 mkpath([$dir]) unless -d $dir;
2858 if (defined $old_index) {
2859 $ENV{GIT_INDEX_FILE} = $old_index;
2861 delete $ENV{GIT_INDEX_FILE};
2864 wantarray ? @ret : $ret[0];
2867 sub assert_index_clean {
2868 my ($self, $treeish) = @_;
2870 $self->tmp_index_do(sub {
2871 command_noisy('read-tree', $treeish) unless -e $self->{index};
2872 my $x = command_oneline('write-tree');
2873 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2874 /^tree ($::sha1)/mo);
2877 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2878 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2879 command_noisy('read-tree', $treeish);
2880 $x = command_oneline('write-tree');
2882 ::fatal "trees ($treeish) $y != $x\n",
2883 "Something is seriously wrong...";
2888 sub get_commit_parents {
2889 my ($self, $log_entry) = @_;
2890 my (%seen, @ret, @tmp);
2891 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2892 if (my $ip = $self->{inject_parents}) {
2893 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2897 if (my $cur = ::verify_ref($self->refname.'^0')) {
2900 if (my $ipd = $self->{inject_parents_dcommit}) {
2901 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2902 push @tmp, @$commit;
2905 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2906 while (my $p = shift @tmp) {
2916 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2917 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2918 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2921 if ($rwr !~ m#^[a-z\+]+://#) {
2922 die "$rwr is not a valid URL (key: $k)\n";
2925 $self->{-rewrite_root} = $rwr;
2930 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2931 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2932 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2935 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2936 die "$rwid is not a valid UUID (key: $k)\n";
2939 $self->{-rewrite_uuid} = $rwid;
2944 ($self->rewrite_root || $self->{url}) .
2945 (length $self->{path} ? '/' . $self->{path} : '');
2950 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2955 if ($self->{pushurl}) {
2956 return $self->{pushurl} . (length $self->{path} ? '/' .
2957 $self->{path} : '');
2959 return $self->full_url;
2963 sub set_commit_header_env {
2964 my ($log_entry) = @_;
2966 foreach my $ned (qw/NAME EMAIL DATE/) {
2967 foreach my $ac (qw/AUTHOR COMMITTER/) {
2968 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2972 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2973 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2974 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2976 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2977 ? $log_entry->{commit_name}
2978 : $log_entry->{name};
2979 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2980 ? $log_entry->{commit_email}
2981 : $log_entry->{email};
2985 sub restore_commit_header_env {
2987 foreach my $ned (qw/NAME EMAIL DATE/) {
2988 foreach my $ac (qw/AUTHOR COMMITTER/) {
2989 my $k = "GIT_${ac}_${ned}";
2990 if (defined $env->{$k}) {
2991 $ENV{$k} = $env->{$k};
3000 command_noisy('gc', '--auto');
3004 my ($self, $log_entry) = @_;
3005 my $lr = $self->last_rev;
3006 if (defined $lr && $lr >= $log_entry->{revision}) {
3007 die "Last fetched revision of ", $self->refname,
3008 " was r$lr, but we are about to fetch: ",
3009 "r$log_entry->{revision}!\n";
3011 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3012 croak "$log_entry->{revision} = $c already exists! ",
3013 "Why are we refetching it?\n";
3015 my $old_env = set_commit_header_env($log_entry);
3016 my $tree = $log_entry->{tree};
3017 if (!defined $tree) {
3018 $tree = $self->tmp_index_do(sub {
3019 command_oneline('write-tree') });
3021 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3023 my @exec = ('git', 'commit-tree', $tree);
3024 foreach ($self->get_commit_parents($log_entry)) {
3025 push @exec, '-p', $_;
3027 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3031 # we always get UTF-8 from SVN, but we may want our commits in
3032 # a different encoding.
3033 if (my $enc = Git::config('i18n.commitencoding')) {
3035 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3037 print $msg_fh $log_entry->{log} or croak $!;
3038 restore_commit_header_env($old_env);
3039 unless ($self->no_metadata) {
3040 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3043 $msg_fh->flush == 0 or croak $!;
3044 close $msg_fh or croak $!;
3045 chomp(my $commit = do { local $/; <$out_fh> });
3046 close $out_fh or croak $!;
3049 if ($commit !~ /^$::sha1$/o) {
3050 die "Failed to commit, invalid sha1: $commit\n";
3053 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3055 $self->{last_rev} = $log_entry->{revision};
3056 $self->{last_commit} = $commit;
3057 print "r$log_entry->{revision}" unless $::_q > 1;
3058 if (defined $log_entry->{svm_revision}) {
3059 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3060 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3061 0, $self->svm_uuid);
3063 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3064 if (--$_gc_nr == 0) {
3065 $_gc_nr = $_gc_period;
3072 my ($self, $paths, $r) = @_;
3073 return 1 if $self->{path} eq '';
3074 if (my $path = $paths->{"/$self->{path}"}) {
3075 return ($path->{action} eq 'D') ? 0 : 1;
3077 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3078 if (grep /$self->{path_regex}/, keys %$paths) {
3082 foreach (split m#/#, $self->{path}) {
3084 next unless ($paths->{$c} &&
3085 ($paths->{$c}->{action} =~ /^[AR]$/));
3086 if ($self->ra->check_path($self->{path}, $r) ==
3094 sub find_parent_branch {
3095 my ($self, $paths, $rev) = @_;
3096 return undef unless $self->follow_parent;
3097 unless (defined $paths) {
3098 my $err_handler = $SVN::Error::handler;
3099 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3100 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3101 sub { $paths = $_[0] });
3102 $SVN::Error::handler = $err_handler;
3104 return undef unless defined $paths;
3106 # look for a parent from another branch:
3107 my @b_path_components = split m#/#, $self->{path};
3108 my @a_path_components;
3110 while (@b_path_components) {
3111 $i = $paths->{'/'.join('/', @b_path_components)};
3112 last if $i && defined $i->{copyfrom_path};
3113 unshift(@a_path_components, pop(@b_path_components));
3115 return undef unless defined $i && defined $i->{copyfrom_path};
3116 my $branch_from = $i->{copyfrom_path};
3117 if (@a_path_components) {
3118 print STDERR "branch_from: $branch_from => ";
3119 $branch_from .= '/'.join('/', @a_path_components);
3120 print STDERR $branch_from, "\n";
3122 my $r = $i->{copyfrom_rev};
3123 my $repos_root = $self->ra->{repos_root};
3124 my $url = $self->ra->{url};
3125 my $new_url = $url . $branch_from;
3126 print STDERR "Found possible branch point: ",
3127 "$new_url => ", $self->full_url, ", $r\n"
3129 $branch_from =~ s#^/##;
3130 my $gs = $self->other_gs($new_url, $url,
3131 $branch_from, $r, $self->{ref_id});
3132 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3135 if (!defined $r0 || !defined $parent) {
3136 ($base, $head) = parse_revision_argument(0, $r);
3139 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3140 0, 1, sub { $base = $_[1] - 1 });
3143 if (defined $base && $base <= $r) {
3144 $gs->fetch($base, $r);
3146 ($r0, $parent) = $gs->find_rev_before($r, 1);
3148 if (defined $r0 && defined $parent) {
3149 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3152 if ($self->ra->can_do_switch) {
3153 $self->assert_index_clean($parent);
3154 print STDERR "Following parent with do_switch\n"
3156 # do_switch works with svn/trunk >= r22312, but that
3157 # is not included with SVN 1.4.3 (the latest version
3158 # at the moment), so we can't rely on it
3159 $self->{last_rev} = $r0;
3160 $self->{last_commit} = $parent;
3161 $ed = Git::SVN::Fetcher->new($self, $gs->{path});
3162 $gs->ra->gs_do_switch($r0, $rev, $gs,
3163 $self->full_url, $ed)
3164 or die "SVN connection failed somewhere...\n";
3165 } elsif ($self->ra->trees_match($new_url, $r0,
3166 $self->full_url, $rev)) {
3167 print STDERR "Trees match:\n",
3169 " ${\$self->full_url}\@$rev\n",
3170 "Following parent with no changes\n"
3172 $self->tmp_index_do(sub {
3173 command_noisy('read-tree', $parent);
3175 $self->{last_commit} = $parent;
3177 print STDERR "Following parent with do_update\n"
3179 $ed = Git::SVN::Fetcher->new($self);
3180 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3181 or die "SVN connection failed somewhere...\n";
3183 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3184 return $self->make_log_entry($rev, [$parent], $ed);
3190 my ($self, $paths, $rev) = @_;
3192 my ($last_rev, @parents);
3193 if (my $lc = $self->last_commit) {
3194 # we can have a branch that was deleted, then re-added
3195 # under the same name but copied from another path, in
3196 # which case we'll have multiple parents (we don't
3197 # want to break the original ref, nor lose copypath info):
3198 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3199 push @{$log_entry->{parents}}, $lc;
3202 $ed = Git::SVN::Fetcher->new($self);
3203 $last_rev = $self->{last_rev};
3208 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3211 $ed = Git::SVN::Fetcher->new($self);
3213 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3214 die "SVN connection failed somewhere...\n";
3216 $self->make_log_entry($rev, \@parents, $ed);
3220 my ($self, $r) = @_;
3223 my ($r, $empty_dirs, $line) = @_;
3224 if (defined $r && $line =~ /^r(\d+)$/) {
3225 return 0 if $1 > $r;
3226 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3227 $empty_dirs->{$1} = 1;
3228 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3229 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3230 delete @$empty_dirs{@d};
3235 my %empty_dirs = ();
3236 my $gz_file = "$self->{dir}/unhandled.log.gz";
3238 if (!$can_compress) {
3239 warn "Compress::Zlib could not be found; ",
3240 "empty directories in $gz_file will not be read\n";
3242 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3243 die "Unable to open $gz_file: $!\n";
3245 while ($gz->gzreadline($line) > 0) {
3246 scan($r, \%empty_dirs, $line) or last;
3252 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3253 binmode $fh or croak "binmode: $!";
3255 scan($r, \%empty_dirs, $_) or last;
3260 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3261 foreach my $d (sort keys %empty_dirs) {
3262 $d = uri_decode($d);
3264 next unless length($d);
3267 warn "$d exists but is not a directory\n";
3269 print "creating empty directory: $d\n";
3276 my ($self, $ed) = @_;
3278 my $h = $ed->{empty};
3279 foreach (sort keys %$h) {
3280 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3281 push @out, " $act: " . uri_encode($_);
3282 warn "W: $act: $_\n";
3284 foreach my $t (qw/dir_prop file_prop/) {
3285 $h = $ed->{$t} or next;
3286 foreach my $path (sort keys %$h) {
3287 my $ppath = $path eq '' ? '.' : $path;
3288 foreach my $prop (sort keys %{$h->{$path}}) {
3289 next if $SKIP_PROP{$prop};
3290 my $v = $h->{$path}->{$prop};
3291 my $t_ppath_prop = "$t: " .
3292 uri_encode($ppath) . ' ' .
3295 push @out, " +$t_ppath_prop " .
3298 push @out, " -$t_ppath_prop";
3303 foreach my $t (qw/absent_file absent_directory/) {
3304 $h = $ed->{$t} or next;
3305 foreach my $parent (sort keys %$h) {
3306 foreach my $path (sort @{$h->{$parent}}) {
3307 push @out, " $t: " .
3308 uri_encode("$parent/$path");
3309 warn "W: $t: $parent/$path ",
3310 "Insufficient permissions?\n";
3318 # some systmes don't handle or mishandle %z, so be creative.
3319 my $t = shift || time;
3320 my $gm = timelocal(gmtime($t));
3321 my $sign = qw( + + - )[ $t <=> $gm ];
3322 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3325 # parse_svn_date(DATE)
3326 # --------------------
3327 # Given a date (in UTC) from Subversion, return a string in the format
3328 # "<TZ Offset> <local date/time>" that Git will use.
3330 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3331 # is true we'll convert it to the local timezone instead.
3332 sub parse_svn_date {
3333 my $date = shift || return '+0000 1970-01-01 00:00:00';
3334 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3335 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3336 croak "Unable to parse date: $date\n";
3337 my $parsed_date; # Set next.
3339 if ($Git::SVN::_localtime) {
3340 # Translate the Subversion datetime to an epoch time.
3341 # Begin by switching ourselves to $date's timezone, UTC.
3342 my $old_env_TZ = $ENV{TZ};
3346 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3348 # Determine our local timezone (including DST) at the
3349 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3350 # value of TZ, if any, at the time we were run.
3351 if (defined $Git::SVN::Log::TZ) {
3352 $ENV{TZ} = $Git::SVN::Log::TZ;
3357 my $our_TZ = get_tz();
3359 # This converts $epoch_in_UTC into our local timezone.
3360 my ($sec, $min, $hour, $mday, $mon, $year,
3361 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3363 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3364 $our_TZ, $year + 1900, $mon + 1,
3365 $mday, $hour, $min, $sec);
3367 # Reset us to the timezone in effect when we entered
3369 if (defined $old_env_TZ) {
3370 $ENV{TZ} = $old_env_TZ;
3375 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3378 return $parsed_date;
3382 my ($self, $new_url, $url,
3383 $branch_from, $r, $old_ref_id) = @_;
3384 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3386 my $ref_id = $old_ref_id;
3387 $ref_id =~ s/\@\d+-*$//;
3389 # just grow a tail if we're not unique enough :x
3390 $ref_id .= '-' while find_ref($ref_id);
3391 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3392 if ($u =~ s#^\Q$url\E(/|$)##) {
3395 $repo_id = $self->{repo_id};
3398 # It is possible to tag two different subdirectories at
3399 # the same revision. If the url for an existing ref
3400 # does not match, we must either find a ref with a
3401 # matching url or create a new ref by growing a tail.
3402 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3403 my (undef, $max_commit) = $gs->rev_map_max(1);
3404 last if (!$max_commit);
3405 my ($url) = ::cmt_metadata($max_commit);
3406 last if ($url eq $gs->metadata_url);
3409 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3414 sub call_authors_prog {
3415 my ($orig_author) = @_;
3416 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3417 my $author = `$::_authors_prog $orig_author`;
3419 die "$::_authors_prog failed with exit code $?\n"
3421 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3422 my ($name, $email) = ($1, $2);
3423 $email = undef if length $2 == 0;
3424 return [$name, $email];
3426 die "Author: $orig_author: $::_authors_prog returned "
3427 . "invalid author format: $author\n";
3433 if (!defined $author || length $author == 0) {
3434 $author = '(no author)';
3436 if (!defined $::users{$author}) {
3437 if (defined $::_authors_prog) {
3438 $::users{$author} = call_authors_prog($author);
3439 } elsif (defined $::_authors) {
3440 die "Author: $author not defined in $::_authors file\n";
3446 sub find_extra_svk_parents {
3447 my ($self, $ed, $tickets, $parents) = @_;
3448 # aha! svk:merge property changed...
3449 my @tickets = split "\n", $tickets;
3451 for my $ticket ( @tickets ) {
3452 my ($uuid, $path, $rev) = split /:/, $ticket;
3453 if ( $uuid eq $self->ra_uuid ) {
3454 my $url = $self->{url};
3455 my $repos_root = $url;
3456 my $branch_from = $path;
3457 $branch_from =~ s{^/}{};
3458 my $gs = $self->other_gs($repos_root."/".$branch_from,
3463 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3464 # wahey! we found it, but it might be
3466 push @known_parents, [ $rev, $commit ];
3470 # Ordering matters; highest-numbered commit merge tickets
3471 # first, as they may account for later merge ticket additions
3473 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3474 for my $parent ( @known_parents ) {
3475 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3476 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3478 while ( <$msg_fh> ) {
3481 command_close_pipe($msg_fh, $ctx);
3484 "Found merge parent (svk:merge ticket): $parent\n";
3485 push @$parents, $parent;
3490 sub lookup_svn_merge {
3495 my ($source, $revs) = split ":", $merge;
3498 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3500 warn "Couldn't find revmap for $url$source\n";
3503 my @ranges = split ",", $revs;
3504 my ($tip, $tip_commit);
3505 my @merged_commit_ranges;
3507 for my $range ( @ranges ) {
3508 my ($bottom, $top) = split "-", $range;
3510 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3511 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3513 unless ($top_commit and $bottom_commit) {
3514 warn "W:unknown path/rev in svn:mergeinfo "
3515 ."dirprop: $source:$range\n";
3519 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3520 push @merged_commit_ranges,
3521 "$bottom_commit^..$top_commit";
3523 push @merged_commit_ranges, "$top_commit";
3526 if ( !defined $tip or $top > $tip ) {
3528 $tip_commit = $top_commit;
3531 return ($tip_commit, @merged_commit_ranges);
3535 my ($msg_fh, $ctx) = command_output_pipe(
3539 while ( <$msg_fh> ) {
3543 command_close_pipe($msg_fh, $ctx);
3547 sub check_cherry_pick {
3550 my $parents = shift;
3552 my %commits = map { $_ => 1 }
3553 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3554 for my $range ( @ranges ) {
3555 delete @commits{_rev_list($range, "--")};
3557 for my $commit (keys %commits) {
3558 if (has_no_changes($commit)) {
3559 delete $commits{$commit};
3562 return (keys %commits);
3565 sub has_no_changes {
3568 my @revs = split / /, command_oneline(
3569 qw(rev-list --parents -1 -m), $commit);
3571 # Commits with no parents, e.g. the start of a partial branch,
3572 # have changes by definition.
3573 return 1 if (@revs < 2);
3575 # Commits with multiple parents, e.g a merge, have no changes
3577 return 0 if (@revs > 2);
3579 return (command_oneline("rev-parse", "$commit^{tree}") eq
3580 command_oneline("rev-parse", "$commit~1^{tree}"));
3583 sub tie_for_persistent_memoization {
3587 if ($can_use_yaml) {
3588 tie %$hash => 'Git::SVN::Memoize::YAML', "$path.yaml";
3590 tie %$hash => 'Memoize::Storable', "$path.db", 'nstore';
3594 # The GIT_DIR environment variable is not always set until after the command
3595 # line arguments are processed, so we can't memoize in a BEGIN block.
3599 sub memoize_svn_mergeinfo_functions {
3600 return if $memoized;
3603 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3604 mkpath([$cache_path]) unless -d $cache_path;
3606 my %lookup_svn_merge_cache;
3607 my %check_cherry_pick_cache;
3608 my %has_no_changes_cache;
3610 tie_for_persistent_memoization(\%lookup_svn_merge_cache,
3611 "$cache_path/lookup_svn_merge");
3612 memoize 'lookup_svn_merge',
3613 SCALAR_CACHE => 'FAULT',
3614 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3617 tie_for_persistent_memoization(\%check_cherry_pick_cache,
3618 "$cache_path/check_cherry_pick");
3619 memoize 'check_cherry_pick',
3620 SCALAR_CACHE => 'FAULT',
3621 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3624 tie_for_persistent_memoization(\%has_no_changes_cache,
3625 "$cache_path/has_no_changes");
3626 memoize 'has_no_changes',
3627 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3628 LIST_CACHE => 'FAULT',
3632 sub unmemoize_svn_mergeinfo_functions {
3633 return if not $memoized;
3636 Memoize::unmemoize 'lookup_svn_merge';
3637 Memoize::unmemoize 'check_cherry_pick';
3638 Memoize::unmemoize 'has_no_changes';
3641 Memoize::memoize 'Git::SVN::repos_root';
3645 # Force cache writeout explicitly instead of waiting for
3646 # global destruction to avoid segfault in Storable:
3647 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3648 unmemoize_svn_mergeinfo_functions();
3651 sub parents_exclude {
3652 my $parents = shift;
3654 return unless @commits;
3659 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3660 $excluded = command_oneline(@cmd);
3664 for my $commit ( @commits ) {
3665 if ( $commit eq $excluded ) {
3666 push @excluded, $commit;
3674 die "saw commit '$excluded' in rev-list output, "
3675 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3680 while ($excluded and @commits);
3686 # note: this function should only be called if the various dirprops
3687 # have actually changed
3688 sub find_extra_svn_parents {
3689 my ($self, $ed, $mergeinfo, $parents) = @_;
3690 # aha! svk:merge property changed...
3692 memoize_svn_mergeinfo_functions();
3694 # We first search for merged tips which are not in our
3695 # history. Then, we figure out which git revisions are in
3696 # that tip, but not this revision. If all of those revisions
3697 # are now marked as merge, we can add the tip as a parent.
3698 my @merges = split "\n", $mergeinfo;
3700 my $url = $self->{url};
3701 my $uuid = $self->ra_uuid;
3703 for my $merge ( @merges ) {
3704 my ($tip_commit, @ranges) =
3705 lookup_svn_merge( $uuid, $url, $merge );
3706 unless (!$tip_commit or
3707 grep { $_ eq $tip_commit } @$parents ) {
3708 push @merge_tips, $tip_commit;
3709 $ranges{$tip_commit} = \@ranges;
3711 push @merge_tips, undef;
3715 my %excluded = map { $_ => 1 }
3716 parents_exclude($parents, grep { defined } @merge_tips);
3718 # check merge tips for new parents
3720 for my $merge_tip ( @merge_tips ) {
3721 my $spec = shift @merges;
3722 next unless $merge_tip and $excluded{$merge_tip};
3724 my $ranges = $ranges{$merge_tip};
3726 # check out 'new' tips
3729 $merge_base = command_oneline(
3731 @$parents, $merge_tip,
3735 die "An error occurred during merge-base"
3736 unless $@->isa("Git::Error::Command");
3738 warn "W: Cannot find common ancestor between ".
3739 "@$parents and $merge_tip. Ignoring merge info.\n";
3743 # double check that there are no missing non-merge commits
3744 my (@incomplete) = check_cherry_pick(
3745 $merge_base, $merge_tip,
3750 if ( @incomplete ) {
3751 warn "W:svn cherry-pick ignored ($spec) - missing "
3752 .@incomplete." commit(s) (eg $incomplete[0])\n";
3755 "Found merge parent (svn:mergeinfo prop): ",
3757 push @new_parents, $merge_tip;
3761 # cater for merges which merge commits from multiple branches
3762 if ( @new_parents > 1 ) {
3763 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3764 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3766 next unless $new_parents[$i];
3767 next unless $new_parents[$j];
3768 my $revs = command_oneline(
3770 "$new_parents[$i]..$new_parents[$j]",
3773 undef($new_parents[$j]);
3778 push @$parents, grep { defined } @new_parents;
3781 sub make_log_entry {
3782 my ($self, $rev, $parents, $ed) = @_;
3783 my $untracked = $self->get_untracked($ed);
3785 my @parents = @$parents;
3786 my $ps = $ed->{path_strip} || "";
3787 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3788 my $props = $ed->{dir_prop}{$path};
3789 if ( $props->{"svk:merge"} ) {
3790 $self->find_extra_svk_parents
3791 ($ed, $props->{"svk:merge"}, \@parents);
3793 if ( $props->{"svn:mergeinfo"} ) {
3794 $self->find_extra_svn_parents
3796 $props->{"svn:mergeinfo"},
3801 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3802 print $un "r$rev\n" or croak $!;
3803 print $un $_, "\n" foreach @$untracked;
3804 my %log_entry = ( parents => \@parents, revision => $rev,
3808 my $logged = delete $self->{logged_rev_props};
3809 if (!$logged || $self->{-want_revprops}) {
3810 my $rp = $self->ra->rev_proplist($rev);
3811 foreach (sort keys %$rp) {
3813 if (/^svn:(author|date|log)$/) {
3814 $log_entry{$1} = $v;
3815 } elsif ($_ eq 'svm:headrev') {
3818 print $un " rev_prop: ", uri_encode($_), ' ',
3819 uri_encode($v), "\n";
3823 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3825 close $un or croak $!;
3827 $log_entry{date} = parse_svn_date($log_entry{date});
3828 $log_entry{log} .= "\n";
3829 my $author = $log_entry{author} = check_author($log_entry{author});
3830 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3833 my ($commit_name, $commit_email) = ($name, $email);
3834 if ($_use_log_author) {
3836 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3838 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3841 if (!defined $name_field) {
3842 if (!defined $email) {
3845 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3846 ($name, $email) = ($1, $2);
3847 } elsif ($name_field =~ /(.*)@/) {
3848 ($name, $email) = ($1, $name_field);
3850 ($name, $email) = ($name_field, $name_field);
3853 if (defined $headrev && $self->use_svm_props) {
3854 if ($self->rewrite_root) {
3855 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3858 if ($self->rewrite_uuid) {
3859 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3862 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3863 # we don't want "SVM: initializing mirror for junk" ...
3864 return undef if $r == 0;
3865 my $svm = $self->svm;
3866 if ($uuid ne $svm->{uuid}) {
3867 die "UUID mismatch on SVM path:\n",
3868 "expected: $svm->{uuid}\n",
3871 my $full_url = $self->full_url;
3872 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3873 die "Failed to replace '$svm->{replace}' with ",
3874 "'$svm->{source}' in $full_url\n";
3875 # throw away username for storing in records
3876 remove_username($full_url);
3877 $log_entry{metadata} = "$full_url\@$r $uuid";
3878 $log_entry{svm_revision} = $r;
3879 $email ||= "$author\@$uuid";
3880 $commit_email ||= "$author\@$uuid";
3881 } elsif ($self->use_svnsync_props) {
3882 my $full_url = $self->svnsync->{url};
3883 $full_url .= "/$self->{path}" if length $self->{path};
3884 remove_username($full_url);
3885 my $uuid = $self->svnsync->{uuid};
3886 $log_entry{metadata} = "$full_url\@$rev $uuid";
3887 $email ||= "$author\@$uuid";
3888 $commit_email ||= "$author\@$uuid";
3890 my $url = $self->metadata_url;
3891 remove_username($url);
3892 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3893 $log_entry{metadata} = "$url\@$rev " . $uuid;
3894 $email ||= "$author\@" . $uuid;
3895 $commit_email ||= "$author\@" . $uuid;
3897 $log_entry{name} = $name;
3898 $log_entry{email} = $email;
3899 $log_entry{commit_name} = $commit_name;
3900 $log_entry{commit_email} = $commit_email;
3905 my ($self, $min_rev, $max_rev, @parents) = @_;
3906 my ($last_rev, $last_commit) = $self->last_rev_commit;
3907 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3908 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3912 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3913 $self->{inject_parents} = { $rev => $tree };
3914 $self->fetch(undef, undef);
3918 my ($self, $tree) = (shift, shift);
3919 my $log_entry = ::get_commit_entry($tree);
3920 unless ($self->{last_rev}) {
3921 ::fatal("Must have an existing revision to commit");
3923 my %ed_opts = ( r => $self->{last_rev},
3924 log => $log_entry->{log},
3926 tree_a => $self->{last_commit},
3929 $self->set_tree_cb($log_entry, $tree, @_) },
3930 svn_path => $self->{path} );
3931 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
3932 print "No changes\nr$self->{last_rev} = $tree\n";
3936 sub rebuild_from_rev_db {
3937 my ($self, $path) = @_;
3939 open my $fh, '<', $path or croak "open: $!";
3940 binmode $fh or croak "binmode: $!";
3942 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3945 next if $_ eq ('0' x 40);
3946 $self->rev_map_set($r, $_);
3949 close $fh or croak "close: $!";
3950 unlink $path or croak "unlink: $!";
3955 my $map_path = $self->map_path;
3956 my $partial = (-e $map_path && ! -z $map_path);
3957 return unless ::verify_ref($self->refname.'^0');
3958 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3959 my $rev_db = $self->rev_db_path;
3960 $self->rebuild_from_rev_db($rev_db);
3961 if ($self->use_svm_props) {
3962 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3963 $self->rebuild_from_rev_db($svm_rev_db);
3965 $self->unlink_rev_db_symlink;
3968 print "Rebuilding $map_path ...\n" if (!$partial);
3969 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3972 command_output_pipe(qw/rev-list --pretty=raw --reverse/,
3973 ($head ? "$head.." : "") . $self->refname,
3975 my $metadata_url = $self->metadata_url;
3976 remove_username($metadata_url);
3977 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3980 if ( m{^commit ($::sha1)$} ) {
3984 next unless s{^\s*(git-svn-id:)}{$1};
3985 my ($url, $rev, $uuid) = ::extract_metadata($_);
3986 remove_username($url);
3988 # ignore merges (from set-tree)
3989 next if (!defined $rev || !$uuid);
3991 # if we merged or otherwise started elsewhere, this is
3992 # how we break out of it
3993 if (($uuid ne $svn_uuid) ||
3994 ($metadata_url && $url && ($url ne $metadata_url))) {
3997 if ($partial && $head) {
3998 print "Partial-rebuilding $map_path ...\n";
3999 print "Currently at $base_rev = $head\n";
4003 $self->rev_map_set($rev, $c);
4004 print "r$rev = $c\n";
4006 command_close_pipe($log, $ctx);
4007 print "Done rebuilding $map_path\n" if (!$partial || !$head);
4008 my $rev_db_path = $self->rev_db_path;
4009 if (-f $self->rev_db_path) {
4010 unlink $self->rev_db_path or croak "unlink: $!";
4012 $self->unlink_rev_db_symlink;
4016 # Tie::File seems to be prone to offset errors if revisions get sparse,
4017 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
4018 # one of my favorite modules is out :< Next up would be one of the DBM
4019 # modules, but I'm not sure which is most portable...
4021 # This is the replacement for the rev_db format, which was too big
4022 # and inefficient for large repositories with a lot of sparse history
4025 # The format is this:
4026 # - 24 bytes for every record,
4027 # * 4 bytes for the integer representing an SVN revision number
4028 # * 20 bytes representing the sha1 of a git commit
4029 # - No empty padding records like the old format
4030 # (except the last record, which can be overwritten)
4031 # - new records are written append-only since SVN revision numbers
4032 # increase monotonically
4033 # - lookups on SVN revision number are done via a binary search
4034 # - Piping the file to xxd -c24 is a good way of dumping it for
4035 # viewing or editing (piped back through xxd -r), should the need
4037 # - The last record can be padding revision with an all-zero sha1
4038 # This is used to optimize fetch performance when using multiple
4039 # "fetch" directives in .git/config
4041 # These files are disposable unless noMetadata or useSvmProps is set
4044 my ($fh, $rev, $commit) = @_;
4046 binmode $fh or croak "binmode: $!";
4047 my $size = (stat($fh))[7];
4048 ($size % 24) == 0 or croak "inconsistent size: $size";
4052 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4053 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
4054 $read == 24 or croak "read only $read bytes (!= 24)";
4055 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
4056 if ($last_commit eq ('0' x40)) {
4058 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4059 $read = sysread($fh, $buf, 24) or
4062 croak "read only $read bytes (!= 24)";
4063 ($last_rev, $last_commit) =
4064 unpack(rev_map_fmt, $buf);
4065 if ($last_commit eq ('0' x40)) {
4066 croak "inconsistent .rev_map\n";
4069 if ($last_rev >= $rev) {
4070 croak "last_rev is higher!: $last_rev >= $rev";
4075 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
4076 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
4080 sub _rev_map_reset {
4081 my ($fh, $rev, $commit) = @_;
4082 my $c = _rev_map_get($fh, $rev);
4083 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
4084 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
4085 truncate $fh, $offset or croak "truncate: $!";
4091 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
4092 mkpath([$dir]) unless -d $dir;
4093 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
4094 close $fh or die "Couldn't close (create) $path: $!\n";
4099 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
4100 defined $commit or die "missing arg3\n";
4101 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
4102 my $db = $self->map_path($uuid);
4103 my $db_lock = "$db.lock";
4107 $sigmask = POSIX::SigSet->new();
4108 my $signew = POSIX::SigSet->new(SIGINT, SIGHUP, SIGTERM,
4109 SIGALRM, SIGUSR1, SIGUSR2);
4110 sigprocmask(SIG_BLOCK, $signew, $sigmask) or
4111 croak "Can't block signals: $!";
4115 $LOCKFILES{$db_lock} = 1;
4117 # both of these options make our .rev_db file very, very important
4118 # and we can't afford to lose it because rebuild() won't work
4119 if ($self->use_svm_props || $self->no_metadata) {
4121 copy($db, $db_lock) or die "rev_map_set(@_): ",
4123 "$db => $db_lock ($!)\n";
4125 rename $db, $db_lock or die "rev_map_set(@_): ",
4126 "Failed to rename: ",
4127 "$db => $db_lock ($!)\n";
4130 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
4131 or croak "Couldn't open $db_lock: $!\n";
4132 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
4133 _rev_map_set($fh, $rev, $commit);
4135 $fh->flush or die "Couldn't flush $db_lock: $!\n";
4136 $fh->sync or die "Couldn't sync $db_lock: $!\n";
4138 close $fh or croak $!;
4142 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
4143 command_noisy('update-ref', '-m', "r$rev$note",
4144 $self->refname, $commit);
4146 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
4147 "$db_lock => $db ($!)\n";
4148 delete $LOCKFILES{$db_lock};
4150 sigprocmask(SIG_SETMASK, $sigmask) or
4151 croak "Can't restore signal mask: $!";
4155 # If want_commit, this will return an array of (rev, commit) where
4156 # commit _must_ be a valid commit in the archive.
4157 # Otherwise, it'll return the max revision (whether or not the
4158 # commit is valid or just a 0x40 placeholder).
4160 my ($self, $want_commit) = @_;
4162 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
4163 $want_commit ? ($r, $c) : $r;
4166 sub rev_map_max_norebuild {
4167 my ($self, $want_commit) = @_;
4168 my $map_path = $self->map_path;
4169 stat $map_path or return $want_commit ? (0, undef) : 0;
4170 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4171 binmode $fh or croak "binmode: $!";
4172 my $size = (stat($fh))[7];
4173 ($size % 24) == 0 or croak "inconsistent size: $size";
4176 close $fh or croak "close: $!";
4177 return $want_commit ? (0, undef) : 0;
4180 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
4181 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4182 my ($r, $c) = unpack(rev_map_fmt, $buf);
4183 if ($want_commit && $c eq ('0' x40)) {
4185 return $want_commit ? (0, undef) : 0;
4187 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
4188 sysread($fh, $buf, 24) == 24 or croak "read: $!";
4189 ($r, $c) = unpack(rev_map_fmt, $buf);
4190 if ($c eq ('0'x40)) {
4191 croak "Penultimate record is all-zeroes in $map_path";
4194 close $fh or croak "close: $!";
4195 $want_commit ? ($r, $c) : $r;
4199 my ($self, $rev, $uuid) = @_;
4200 my $map_path = $self->map_path($uuid);
4201 return undef unless -e $map_path;
4203 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4204 my $c = _rev_map_get($fh, $rev);
4205 close($fh) or croak "close: $!";
4210 my ($fh, $rev) = @_;
4212 binmode $fh or croak "binmode: $!";
4213 my $size = (stat($fh))[7];
4214 ($size % 24) == 0 or croak "inconsistent size: $size";
4220 my ($l, $u) = (0, $size - 24);
4224 my $i = int(($l/24 + $u/24) / 2) * 24;
4225 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
4226 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
4227 my ($r, $c) = unpack(rev_map_fmt, $buf);
4231 } elsif ($r > $rev) {
4233 } else { # $r == $rev
4234 return $c eq ('0' x 40) ? undef : $c;
4240 # Finds the first svn revision that exists on (if $eq_ok is true) or
4241 # before $rev for the current branch. It will not search any lower
4242 # than $min_rev. Returns the git commit hash and svn revision number
4243 # if found, else (undef, undef).
4244 sub find_rev_before {
4245 my ($self, $rev, $eq_ok, $min_rev) = @_;
4246 --$rev unless $eq_ok;
4248 my $max_rev = $self->rev_map_max;
4249 $rev = $max_rev if ($rev > $max_rev);
4250 while ($rev >= $min_rev) {
4251 if (my $c = $self->rev_map_get($rev)) {
4256 return (undef, undef);
4259 # Finds the first svn revision that exists on (if $eq_ok is true) or
4260 # after $rev for the current branch. It will not search any higher
4261 # than $max_rev. Returns the git commit hash and svn revision number
4262 # if found, else (undef, undef).
4263 sub find_rev_after {
4264 my ($self, $rev, $eq_ok, $max_rev) = @_;
4265 ++$rev unless $eq_ok;
4266 $max_rev ||= $self->rev_map_max;
4267 while ($rev <= $max_rev) {
4268 if (my $c = $self->rev_map_get($rev)) {
4273 return (undef, undef);
4277 my ($class, $repo_id, $ref_id, $path) = @_;
4278 unless (defined $repo_id && length $repo_id) {
4279 $repo_id = $Git::SVN::default_repo_id;
4281 unless (defined $ref_id && length $ref_id) {
4282 $_prefix = '' unless defined($_prefix);
4284 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
4287 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
4289 # Older repos imported by us used $GIT_DIR/svn/foo instead of
4290 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
4291 if ($ref_id =~ m{^refs/remotes/(.*)}) {
4292 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
4293 if (-d $old_dir && ! -d $dir) {
4298 $_[3] = $path = '' unless (defined $path);
4301 ref_id => $ref_id, dir => $dir, index => "$dir/index",
4302 path => $path, config => "$ENV{GIT_DIR}/svn/config",
4303 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
4306 # for read-only access of old .rev_db formats
4307 sub unlink_rev_db_symlink {
4309 my $link = $self->rev_db_path;
4310 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
4312 unlink $link or croak "unlink: $link failed!";
4317 my ($self, $uuid) = @_;
4318 my $db_path = $self->map_path($uuid);
4319 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
4320 or croak "map_path: $db_path does not contain '/.rev_map.' !";
4324 # the new replacement for .rev_db
4326 my ($self, $uuid) = @_;
4327 $uuid ||= $self->ra_uuid;
4328 "$self->{map_root}.$uuid";
4333 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
4339 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
4343 sub remove_username {
4344 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
4347 package Git::SVN::Log;
4350 use POSIX qw/strftime/;
4351 use constant commit_log_separator => ('-' x 72) . "\n";
4352 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4353 %rusers $show_commit $incremental/;
4358 return 1 if defined $c->{r};
4360 # big commit message got truncated by the 16k pretty buffer in rev-list
4361 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4362 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4364 my @log = command(qw/cat-file commit/, $c->{c});
4366 # shift off the headers
4367 shift @log while ($log[0] ne '');
4370 # TODO: make $c->{l} not have a trailing newline in the future
4371 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4373 (undef, $c->{r}, undef) = ::extract_metadata(
4374 (grep(/^git-svn-id: /, @log))[-1]);
4376 return defined $c->{r};
4380 return $color || Git->repository->get_colorbool('color.diff');
4383 sub git_svn_log_cmd {
4384 my ($r_min, $r_max, @args) = @_;
4386 my (@files, @log_opts);
4387 foreach my $x (@args) {
4388 if ($x eq '--' || @files) {
4391 if (::verify_ref("$x^0")) {
4399 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4400 $gs ||= Git::SVN->_new;
4401 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4403 push @cmd, '-r' unless $non_recursive;
4404 push @cmd, qw/--raw --name-status/ if $verbose;
4405 push @cmd, '--color' if log_use_color();
4406 push @cmd, @log_opts;
4407 if (defined $r_max && $r_max == $r_min) {
4408 push @cmd, '--max-count=1';
4409 if (my $c = $gs->rev_map_get($r_max)) {
4412 } elsif (defined $r_max) {
4413 if ($r_max < $r_min) {
4414 ($r_min, $r_max) = ($r_max, $r_min);
4416 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4417 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4418 # If there are no commits in the range, both $c_max and $c_min
4419 # will be undefined. If there is at least 1 commit in the
4420 # range, both will be defined.
4421 return () if !defined $c_min || !defined $c_max;
4422 if ($c_min eq $c_max) {
4423 push @cmd, '--max-count=1', $c_min;
4425 push @cmd, '--boundary', "$c_min..$c_max";
4428 return (@cmd, @files);
4431 # adapted from pager.c
4434 $ENV{GIT_PAGER_IN_USE} = 'false';
4438 chomp($pager = command_oneline(qw(var GIT_PAGER)));
4439 if ($pager eq 'cat') {
4442 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4446 return unless defined $pager;
4447 pipe my ($rfd, $wfd) or return;
4448 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4450 open STDOUT, '>&', $wfd or
4451 ::fatal "Can't redirect to stdout: $!";
4454 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4455 $ENV{LESS} ||= 'FRSX';
4456 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4459 sub format_svn_date {
4460 my $t = shift || time;
4461 my $gmoff = Git::SVN::get_tz($t);
4462 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4465 sub parse_git_date {
4467 # Date::Parse isn't in the standard Perl distro :(
4468 if ($tz =~ s/^\+//) {
4469 $t += tz_to_s_offset($tz);
4470 } elsif ($tz =~ s/^\-//) {
4471 $t -= tz_to_s_offset($tz);
4476 sub set_local_timezone {
4484 sub tz_to_s_offset {
4487 return ($1 * 60) + ($tz * 3600);
4490 sub get_author_info {
4491 my ($dest, $author, $t, $tz) = @_;
4492 $author =~ s/(?:^\s*|\s*$)//g;
4493 $dest->{a_raw} = $author;
4496 $au = $rusers{$author} || undef;
4499 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4504 $dest->{t_utc} = parse_git_date($t, $tz);
4507 sub process_commit {
4508 my ($c, $r_min, $r_max, $defer) = @_;
4509 if (defined $r_min && defined $r_max) {
4510 if ($r_min == $c->{r} && $r_min == $r_max) {
4514 return 1 if $r_min == $r_max;
4515 if ($r_min < $r_max) {
4516 # we need to reverse the print order
4517 return 0 if (defined $limit && --$limit < 0);
4521 if ($r_min != $r_max) {
4522 return 1 if ($r_min < $c->{r});
4523 return 1 if ($r_max > $c->{r});
4526 return 0 if (defined $limit && --$limit < 0);
4535 if (my $l = $c->{l}) {
4536 while ($l->[0] =~ /^\s*$/) { shift @$l }
4539 $l_fmt ||= 'A' . length($c->{r});
4540 print 'r',pack($l_fmt, $c->{r}),' | ';
4541 print "$c->{c} | " if $show_commit;
4544 show_commit_normal($c);
4548 sub show_commit_changed_paths {
4550 return unless $c->{changed};
4551 print "Changed paths:\n", @{$c->{changed}};
4554 sub show_commit_normal {
4556 print commit_log_separator, "r$c->{r} | ";
4557 print "$c->{c} | " if $show_commit;
4558 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4561 if (my $l = $c->{l}) {
4562 while ($l->[$#$l] eq "\n" && $#$l > 0
4563 && $l->[($#$l - 1)] eq "\n") {
4566 $nr_line = scalar @$l;
4568 print "1 line\n\n\n";
4570 if ($nr_line == 1) {
4571 $nr_line = '1 line';
4573 $nr_line .= ' lines';
4575 print $nr_line, "\n";
4576 show_commit_changed_paths($c);
4578 print $_ foreach @$l;
4582 show_commit_changed_paths($c);
4586 foreach my $x (qw/raw stat diff/) {
4589 print $_ foreach @{$c->{$x}}
4596 my ($r_min, $r_max);
4597 my $r_last = -1; # prevent dupes
4598 set_local_timezone();
4599 if (defined $::_revision) {
4600 if ($::_revision =~ /^(\d+):(\d+)$/) {
4601 ($r_min, $r_max) = ($1, $2);
4602 } elsif ($::_revision =~ /^\d+$/) {
4603 $r_min = $r_max = $::_revision;
4605 ::fatal "-r$::_revision is not supported, use ",
4606 "standard 'git log' arguments instead";
4611 @args = git_svn_log_cmd($r_min, $r_max, @args);
4613 print commit_log_separator unless $incremental || $oneline;
4616 my $log = command_output_pipe(@args);
4618 my (@k, $c, $d, $stat);
4619 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4621 if (/^${esc_color}commit (?:- )?($::sha1_short)/o) {
4623 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4625 process_commit($c, $r_min, $r_max, \@k) or
4630 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4631 get_author_info($c, $1, $2, $3);
4632 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4634 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4635 push @{$c->{raw}}, $_;
4636 } elsif (/^${esc_color}[ACRMDT]\t/) {
4637 # we could add $SVN->{svn_path} here, but that requires
4638 # remote access at the moment (repo_path_split)...
4639 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4640 push @{$c->{changed}}, $_;
4641 } elsif (/^${esc_color}diff /o) {
4643 push @{$c->{diff}}, $_;
4645 push @{$c->{diff}}, $_;
4646 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4647 $esc_color*[\+\-]*$esc_color$/x) {
4649 push @{$c->{stat}}, $_;
4650 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4651 push @{$c->{stat}}, $_;
4653 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4654 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4655 } elsif (s/^${esc_color} //o) {
4656 push @{$c->{l}}, $_;
4659 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4661 process_commit($c, $r_min, $r_max, \@k);
4664 ($r_min, $r_max) = ($r_max, $r_min);
4665 process_commit($_, $r_min, $r_max) foreach reverse @k;
4669 print commit_log_separator unless $incremental || $oneline;
4678 my ($fh, $ctx, $rev);
4681 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4682 while (my $line = <$fh>) {
4683 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4684 # Uncommitted edits show up as a rev ID of
4685 # all zeros, which we can't look up with
4688 (undef, $rev, undef) =
4690 $rev = '0' if (!$rev);
4694 $rev = sprintf('%-10s', $rev);
4695 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4700 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4705 my %dsha; #distinct sha keys
4707 while (my $line = <$fh>) {
4708 push @buffer, $line;
4709 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4714 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
4716 foreach my $line (@buffer) {
4717 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4719 $rev = '0' if (!$rev)
4721 elsif ($line =~ /^author (.*)/) {
4722 $authors{$rev} = $1;
4723 $authors{$rev} =~ s/\s/_/g;
4725 elsif ($line =~ /^\t(.*)$/) {
4726 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4730 command_close_pipe($fh, $ctx);
4733 package Git::SVN::Migration;
4734 # these version numbers do NOT correspond to actual version numbers
4735 # of git nor git-svn. They are just relative.
4737 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4739 # v1 layout: .git/$id/info/url, refs/remotes/$id
4741 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4743 # v3 layout: .git/svn/$id, refs/remotes/$id
4744 # - info/url may remain for backwards compatibility
4745 # - this is what we migrate up to this layout automatically,
4746 # - this will be used by git svn init on single branches
4747 # v3.1 layout (auto migrated):
4748 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4749 # for backwards compatibility
4751 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4752 # - this is only created for newly multi-init-ed
4753 # repositories. Similar in spirit to the
4754 # --use-separate-remotes option in git-clone (now default)
4755 # - we do not automatically migrate to this (following
4756 # the example set by core git)
4758 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4759 # - newer, more-efficient format that uses 24-bytes per record
4760 # with no filler space.
4761 # - use xxd -c24 < .rev_map.$UUID to view and debug
4762 # - This is a one-way migration, repositories updated to the
4763 # new format will not be able to use old git-svn without
4764 # rebuilding the .rev_db. Rebuilding the rev_db is not
4765 # possible if noMetadata or useSvmProps are set; but should
4766 # be no problem for users that use the (sensible) defaults.
4770 use File::Path qw/mkpath/;
4771 use File::Basename qw/dirname basename/;
4772 use vars qw/$_minimize/;
4774 sub migrate_from_v0 {
4775 my $git_dir = $ENV{GIT_DIR};
4776 return undef unless -d $git_dir;
4777 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4781 my ($id, $orig_ref) = ($_, $_);
4782 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4783 next unless -f "$git_dir/$id/info/url";
4784 my $new_ref = "refs/remotes/$id";
4785 if (::verify_ref("$new_ref^0")) {
4786 print STDERR "W: $orig_ref is probably an old ",
4787 "branch used by an ancient version of ",
4789 "However, $new_ref also exists.\n",
4790 "We will not be able ",
4791 "to use this branch until this ",
4792 "ambiguity is resolved.\n";
4795 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4796 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4797 command_noisy('update-ref', $new_ref, $orig_ref);
4798 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4801 command_close_pipe($fh, $ctx);
4802 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4806 sub migrate_from_v1 {
4807 my $git_dir = $ENV{GIT_DIR};
4809 return $migrated unless -d $git_dir;
4810 my $svn_dir = "$git_dir/svn";
4812 # just in case somebody used 'svn' as their $id at some point...
4813 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4815 print STDERR "Migrating from a git-svn v1 layout...\n";
4817 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4818 "$svn_dir\n\t(required for this version ",
4819 "($::VERSION) of git-svn) does not exist.\n";
4820 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4823 next unless $x =~ s#^refs/remotes/##;
4825 next unless -f "$git_dir/$x/info/url";
4826 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4828 my $dn = dirname("$git_dir/svn/$x");
4829 mkpath([$dn]) unless -d $dn;
4830 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4831 mkpath(["$git_dir/svn/svn"]);
4832 print STDERR " - $git_dir/$x/info => ",
4833 "$git_dir/svn/$x/info\n";
4834 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4836 # don't worry too much about these, they probably
4837 # don't exist with repos this old (save for index,
4838 # and we can easily regenerate that)
4839 foreach my $f (qw/unhandled.log index .rev_db/) {
4840 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4843 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4844 rename "$git_dir/$x", "$git_dir/svn/$x" or
4849 command_close_pipe($fh, $ctx);
4850 print STDERR "Done migrating from a git-svn v1 layout\n";
4855 my ($l_map, $pfx, $path) = @_;
4857 foreach (<$path/*>) {
4858 if (-r "$_/info/url") {
4859 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4860 my $ref_id = $pfx . basename $_;
4861 my $url = ::file_to_s("$_/info/url");
4862 $l_map->{$ref_id} = $url;
4869 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4870 read_old_urls($l_map, $x, $_);
4874 sub migrate_from_v2 {
4875 my @cfg = command(qw/config -l/);
4876 return if grep /^svn-remote\..+\.url=/, @cfg;
4878 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4881 foreach my $ref_id (sort keys %l_map) {
4882 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4884 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4891 sub minimize_connections {
4892 my $r = Git::SVN::read_all_remotes();
4894 my $root_repos = {};
4895 foreach my $repo_id (keys %$r) {
4896 my $url = $r->{$repo_id}->{url} or next;
4897 my $fetch = $r->{$repo_id}->{fetch} or next;
4898 my $ra = Git::SVN::Ra->new($url);
4900 # skip existing cases where we already connect to the root
4901 if (($ra->{url} eq $ra->{repos_root}) ||
4902 ($ra->{repos_root} eq $repo_id)) {
4903 $root_repos->{$ra->{url}} = $repo_id;
4907 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4908 my $root_path = $ra->{url};
4909 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4910 foreach my $path (keys %$fetch) {
4911 my $ref_id = $fetch->{$path};
4912 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4914 # make sure we can read when connecting to
4915 # a higher level of a repository
4916 my ($last_rev, undef) = $gs->last_rev_commit;
4917 if (!defined $last_rev) {
4919 $root_ra->get_latest_revnum;
4923 my $new = $root_path;
4924 $new .= length $path ? "/$path" : '';
4926 $root_ra->get_log([$new], $last_rev, $last_rev,
4930 $new_urls->{$ra->{repos_root}}->{$new} =
4931 { ref_id => $ref_id,
4932 old_repo_id => $repo_id,
4933 old_path => $path };
4938 foreach my $url (keys %$new_urls) {
4939 # see if we can re-use an existing [svn-remote "repo_id"]
4940 # instead of creating a(n ugly) new section:
4941 my $repo_id = $root_repos->{$url} || $url;
4943 my $fetch = $new_urls->{$url};
4944 foreach my $path (keys %$fetch) {
4945 my $x = $fetch->{$path};
4946 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4947 my $pfx = "svn-remote.$x->{old_repo_id}";
4949 my $old_fetch = quotemeta("$x->{old_path}:".
4951 command_noisy(qw/config --unset/,
4952 "$pfx.fetch", '^'. $old_fetch . '$');
4953 delete $r->{$x->{old_repo_id}}->
4954 {fetch}->{$x->{old_path}};
4955 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4956 command_noisy(qw/config --unset/,
4958 push @emptied, $x->{old_repo_id}
4963 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
4965 The following [svn-remote] sections in your config file ($file) are empty
4966 and can be safely removed:
4968 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4972 sub migration_check {
4976 minimize_connections() if $_minimize;
4979 package Git::IndexInfo;
4982 use Git qw/command_input_pipe command_close_pipe/;
4986 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4987 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4991 my ($self, $path) = @_;
4992 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4993 return ++$self->{nr};
4999 my ($self, $mode, $hash, $path) = @_;
5000 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5001 return ++$self->{nr};
5008 command_close_pipe($self->{gui}, $self->{ctx});
5011 package Git::SVN::GlobSpec;
5016 my ($class, $glob, $pattern_ok) = @_;
5018 $re =~ s!/+$!!g; # no need for trailing slashes
5019 my (@left, @right, @patterns);
5021 my $die_msg = "Only one set of wildcard directories " .
5022 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5023 for my $part (split(m|/|, $glob)) {
5024 if ($part =~ /\*/ && $part ne "*") {
5025 die "Invalid pattern in '$glob': $part\n";
5026 } elsif ($pattern_ok && $part =~ /[{}]/ &&
5027 $part !~ /^\{[^{}]+\}/) {
5028 die "Invalid pattern in '$glob': $part\n";
5031 die $die_msg if $state eq "right";
5033 push(@patterns, "[^/]*");
5034 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
5035 die $die_msg if $state eq "right";
5037 my $p = quotemeta($1);
5039 push(@patterns, "(?:$p)");
5041 if ($state eq "left") {
5044 push(@right, $part);
5049 my $depth = @patterns;
5051 die "One '*' is needed in glob: '$glob'\n";
5053 my $left = join('/', @left);
5054 my $right = join('/', @right);
5055 $re = join('/', @patterns);
5057 grep(length, quotemeta($left), "($re)", quotemeta($right)));
5058 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5059 bless { left => $left, right => $right, left_regex => $left_re,
5060 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5064 my ($self, $path) = @_;
5065 return (length $self->{left} ? "$self->{left}/" : '') .
5066 $path . (length $self->{right} ? "/$self->{right}" : '');
5074 $remotes = { # returned by read_all_remotes()
5076 # svn-remote.svn.url=https://svn.musicpd.org
5077 url => 'https://svn.musicpd.org',
5078 # svn-remote.svn.fetch=mpd/trunk:trunk
5080 'mpd/trunk' => 'trunk',
5082 # svn-remote.svn.tags=mpd/tags/*:tags/*
5087 regex => qr!mpd/tags/([^/]+)$!,
5093 regex => qr!tags/([^/]+)$!,
5100 $log_entry hashref as returned by libsvn_log_entry()
5102 log => 'whitespace-formatted log entry
5103 ', # trailing newline is preserved
5104 revision => '8', # integer
5105 date => '2004-02-24T17:01:44.108345Z', # commit date
5106 author => 'committer name'
5110 # this is generated by generate_diff();
5111 @mods = array of diff-index line hashes, each element represents one line
5112 of diff-index output
5114 diff-index line ($m hash)
5116 mode_a => first column of diff-index output, no leading ':',
5117 mode_b => second column of diff-index output,
5118 sha1_b => sha1sum of the final blob,
5119 chg => change type [MCRADT],
5120 file_a => original file name of a file (iff chg is 'C' or 'R')
5121 file_b => new/current file name of a file (any chg)
5125 # retval of read_url_paths{,_all}();
5127 # repository root url
5128 'https://svn.musicpd.org' => {
5129 # repository path # GIT_SVN_ID
5130 'mpd/trunk' => 'trunk',
5131 'mpd/tags/0.11.5' => 'tags/0.11.5',
5136 I don't trust the each() function on unless I created %hash myself
5137 because the internal iterator may not have started at base.