submodule: Use cat instead of echo to avoid DOS line-endings
[git/dscho.git] / git-svn.perl
bloba0410f055406eaaf54ddb056d4b501b3cd250d72
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use 5.008;
5 use warnings;
6 use strict;
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)
16 } || '';
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH}) {
26 if (exists $ENV{GIT_SSH}) {
27 $ENV{SVN_SSH} = $ENV{GIT_SSH};
28 if ($^O eq 'msys') {
29 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
35 $Git::SVN::Log::TZ = $ENV{TZ};
36 $ENV{TZ} = 'UTC';
37 $| = 1; # unbuffer STDOUT
39 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 sub _req_svn {
41 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
42 require SVN::Ra;
43 require SVN::Delta;
44 if ($SVN::Core::VERSION lt '1.1.0') {
45 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
48 my $can_compress = eval { require Compress::Zlib; 1};
49 push @Git::SVN::Ra::ISA, 'SVN::Ra';
50 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
51 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
52 use Carp qw/croak/;
53 use Digest::MD5;
54 use IO::File qw//;
55 use File::Basename qw/dirname basename/;
56 use File::Path qw/mkpath/;
57 use File::Spec;
58 use File::Find;
59 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
60 use IPC::Open3;
61 use Git;
62 use Memoize; # core since 5.8.0, Jul 2002
64 BEGIN {
65 # import functions from Git into our packages, en masse
66 no strict 'refs';
67 foreach (qw/command command_oneline command_noisy command_output_pipe
68 command_input_pipe command_close_pipe
69 command_bidi_pipe command_close_bidi_pipe/) {
70 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
71 Git::SVN::Migration Git::SVN::Log Git::SVN),
72 __PACKAGE__) {
73 *{"${package}::$_"} = \&{"Git::$_"};
76 Memoize::memoize 'Git::config';
77 Memoize::memoize 'Git::config_bool';
80 my ($SVN);
82 $sha1 = qr/[a-f\d]{40}/;
83 $sha1_short = qr/[a-f\d]{4,40}/;
84 my ($_stdin, $_help, $_edit,
85 $_message, $_file, $_branch_dest,
86 $_template, $_shared,
87 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
88 $_merge, $_strategy, $_dry_run, $_local,
89 $_prefix, $_no_checkout, $_url, $_verbose,
90 $_git_format, $_commit_url, $_tag, $_merge_info);
91 $Git::SVN::_follow_parent = 1;
92 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
93 $_q ||= 0;
94 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
95 'config-dir=s' => \$Git::SVN::Ra::config_dir,
96 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
97 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
98 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
99 'authors-file|A=s' => \$_authors,
100 'authors-prog=s' => \$_authors_prog,
101 'repack:i' => \$Git::SVN::_repack,
102 'noMetadata' => \$Git::SVN::_no_metadata,
103 'useSvmProps' => \$Git::SVN::_use_svm_props,
104 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
105 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
106 'no-checkout' => \$_no_checkout,
107 'quiet|q+' => \$_q,
108 'repack-flags|repack-args|repack-opts=s' =>
109 \$Git::SVN::_repack_flags,
110 'use-log-author' => \$Git::SVN::_use_log_author,
111 'add-author-from' => \$Git::SVN::_add_author_from,
112 'localtime' => \$Git::SVN::_localtime,
113 %remote_opts );
115 my ($_trunk, @_tags, @_branches, $_stdlayout);
116 my %icv;
117 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
118 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
119 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
120 'stdlayout|s' => \$_stdlayout,
121 'minimize-url|m!' => \$Git::SVN::_minimize_url,
122 'no-metadata' => sub { $icv{noMetadata} = 1 },
123 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
124 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
125 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
126 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
127 %remote_opts );
128 my %cmt_opts = ( 'edit|e' => \$_edit,
129 'rmdir' => \$SVN::Git::Editor::_rmdir,
130 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
131 'l=i' => \$SVN::Git::Editor::_rename_limit,
132 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
135 my %cmd = (
136 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
137 { 'revision|r=s' => \$_revision,
138 'fetch-all|all' => \$_fetch_all,
139 'parent|p' => \$_fetch_parent,
140 %fc_opts } ],
141 clone => [ \&cmd_clone, "Initialize and fetch revisions",
142 { 'revision|r=s' => \$_revision,
143 'preserve-empty-dirs' =>
144 \$SVN::Git::Fetcher::_preserve_empty_dirs,
145 'placeholder-filename=s' =>
146 \$SVN::Git::Fetcher::_placeholder_filename,
147 %fc_opts, %init_opts } ],
148 init => [ \&cmd_init, "Initialize a repo for tracking" .
149 " (requires URL argument)",
150 \%init_opts ],
151 'multi-init' => [ \&cmd_multi_init,
152 "Deprecated alias for ".
153 "'$0 init -T<trunk> -b<branches> -t<tags>'",
154 \%init_opts ],
155 dcommit => [ \&cmd_dcommit,
156 'Commit several diffs to merge with upstream',
157 { 'merge|m|M' => \$_merge,
158 'strategy|s=s' => \$_strategy,
159 'verbose|v' => \$_verbose,
160 'dry-run|n' => \$_dry_run,
161 'fetch-all|all' => \$_fetch_all,
162 'commit-url=s' => \$_commit_url,
163 'revision|r=i' => \$_revision,
164 'no-rebase' => \$_no_rebase,
165 'mergeinfo=s' => \$_merge_info,
166 %cmt_opts, %fc_opts } ],
167 branch => [ \&cmd_branch,
168 'Create a branch in the SVN repository',
169 { 'message|m=s' => \$_message,
170 'destination|d=s' => \$_branch_dest,
171 'dry-run|n' => \$_dry_run,
172 'tag|t' => \$_tag,
173 'username=s' => \$Git::SVN::Prompt::_username,
174 'commit-url=s' => \$_commit_url } ],
175 tag => [ sub { $_tag = 1; cmd_branch(@_) },
176 'Create a tag in the SVN repository',
177 { 'message|m=s' => \$_message,
178 'destination|d=s' => \$_branch_dest,
179 'dry-run|n' => \$_dry_run,
180 'username=s' => \$Git::SVN::Prompt::_username,
181 'commit-url=s' => \$_commit_url } ],
182 'set-tree' => [ \&cmd_set_tree,
183 "Set an SVN repository to a git tree-ish",
184 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
185 'create-ignore' => [ \&cmd_create_ignore,
186 'Create a .gitignore per svn:ignore',
187 { 'revision|r=i' => \$_revision
188 } ],
189 'mkdirs' => [ \&cmd_mkdirs ,
190 "recreate empty directories after a checkout",
191 { 'revision|r=i' => \$_revision } ],
192 'propget' => [ \&cmd_propget,
193 'Print the value of a property on a file or directory',
194 { 'revision|r=i' => \$_revision } ],
195 'proplist' => [ \&cmd_proplist,
196 'List all properties of a file or directory',
197 { 'revision|r=i' => \$_revision } ],
198 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
199 { 'revision|r=i' => \$_revision
200 } ],
201 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
202 { 'revision|r=i' => \$_revision
203 } ],
204 'multi-fetch' => [ \&cmd_multi_fetch,
205 "Deprecated alias for $0 fetch --all",
206 { 'revision|r=s' => \$_revision, %fc_opts } ],
207 'migrate' => [ sub { },
208 # no-op, we automatically run this anyways,
209 'Migrate configuration/metadata/layout from
210 previous versions of git-svn',
211 { 'minimize' => \$Git::SVN::Migration::_minimize,
212 %remote_opts } ],
213 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
214 { 'limit=i' => \$Git::SVN::Log::limit,
215 'revision|r=s' => \$_revision,
216 'verbose|v' => \$Git::SVN::Log::verbose,
217 'incremental' => \$Git::SVN::Log::incremental,
218 'oneline' => \$Git::SVN::Log::oneline,
219 'show-commit' => \$Git::SVN::Log::show_commit,
220 'non-recursive' => \$Git::SVN::Log::non_recursive,
221 'authors-file|A=s' => \$_authors,
222 'color' => \$Git::SVN::Log::color,
223 'pager=s' => \$Git::SVN::Log::pager
224 } ],
225 'find-rev' => [ \&cmd_find_rev,
226 "Translate between SVN revision numbers and tree-ish",
227 {} ],
228 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
229 { 'merge|m|M' => \$_merge,
230 'verbose|v' => \$_verbose,
231 'strategy|s=s' => \$_strategy,
232 'local|l' => \$_local,
233 'fetch-all|all' => \$_fetch_all,
234 'dry-run|n' => \$_dry_run,
235 %fc_opts } ],
236 'commit-diff' => [ \&cmd_commit_diff,
237 'Commit a diff between two trees',
238 { 'message|m=s' => \$_message,
239 'file|F=s' => \$_file,
240 'revision|r=s' => \$_revision,
241 %cmt_opts } ],
242 'info' => [ \&cmd_info,
243 "Show info about the latest SVN revision
244 on the current branch",
245 { 'url' => \$_url, } ],
246 'blame' => [ \&Git::SVN::Log::cmd_blame,
247 "Show what revision and author last modified each line of a file",
248 { 'git-format' => \$_git_format } ],
249 'reset' => [ \&cmd_reset,
250 "Undo fetches back to the specified SVN revision",
251 { 'revision|r=s' => \$_revision,
252 'parent|p' => \$_fetch_parent } ],
253 'gc' => [ \&cmd_gc,
254 "Compress unhandled.log files in .git/svn and remove " .
255 "index files in .git/svn",
256 {} ],
259 my $cmd;
260 for (my $i = 0; $i < @ARGV; $i++) {
261 if (defined $cmd{$ARGV[$i]}) {
262 $cmd = $ARGV[$i];
263 splice @ARGV, $i, 1;
264 last;
265 } elsif ($ARGV[$i] eq 'help') {
266 $cmd = $ARGV[$i+1];
267 usage(0);
271 # make sure we're always running at the top-level working directory
272 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
273 unless (-d $ENV{GIT_DIR}) {
274 if ($git_dir_user_set) {
275 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
276 "but it is not a directory\n";
278 my $git_dir = delete $ENV{GIT_DIR};
279 my $cdup = undef;
280 git_cmd_try {
281 $cdup = command_oneline(qw/rev-parse --show-cdup/);
282 $git_dir = '.' unless ($cdup);
283 chomp $cdup if ($cdup);
284 $cdup = "." unless ($cdup && length $cdup);
285 } "Already at toplevel, but $git_dir not found\n";
286 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
287 unless (-d $git_dir) {
288 die "$git_dir still not found after going to ",
289 "'$cdup'\n";
291 $ENV{GIT_DIR} = $git_dir;
293 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
296 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
298 read_git_config(\%opts);
299 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
300 Getopt::Long::Configure('pass_through');
302 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
303 'minimize-connections' => \$Git::SVN::Migration::_minimize,
304 'id|i=s' => \$Git::SVN::default_ref_id,
305 'svn-remote|remote|R=s' => sub {
306 $Git::SVN::no_reuse_existing = 1;
307 $Git::SVN::default_repo_id = $_[1] });
308 exit 1 if (!$rv && $cmd && $cmd ne 'log');
310 usage(0) if $_help;
311 version() if $_version;
312 usage(1) unless defined $cmd;
313 load_authors() if $_authors;
314 if (defined $_authors_prog) {
315 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
318 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
319 Git::SVN::Migration::migration_check();
321 Git::SVN::init_vars();
322 eval {
323 Git::SVN::verify_remotes_sanity();
324 $cmd{$cmd}->[0]->(@ARGV);
326 fatal $@ if $@;
327 post_fetch_checkout();
328 exit 0;
330 ####################### primary functions ######################
331 sub usage {
332 my $exit = shift || 0;
333 my $fd = $exit ? \*STDERR : \*STDOUT;
334 print $fd <<"";
335 git-svn - bidirectional operations between a single Subversion tree and git
336 Usage: git svn <command> [options] [arguments]\n
338 print $fd "Available commands:\n" unless $cmd;
340 foreach (sort keys %cmd) {
341 next if $cmd && $cmd ne $_;
342 next if /^multi-/; # don't show deprecated commands
343 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
344 foreach (sort keys %{$cmd{$_}->[2]}) {
345 # mixed-case options are for .git/config only
346 next if /[A-Z]/ && /^[a-z]+$/i;
347 # prints out arguments as they should be passed:
348 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
349 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
350 "--$_" : "-$_" }
351 split /\|/,$_)," $x\n";
354 print $fd <<"";
355 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
356 arbitrary identifier if you're tracking multiple SVN branches/repositories in
357 one git repository and want to keep them separate. See git-svn(1) for more
358 information.
360 exit $exit;
363 sub version {
364 ::_req_svn();
365 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
366 exit 0;
369 sub do_git_init_db {
370 unless (-d $ENV{GIT_DIR}) {
371 my @init_db = ('init');
372 push @init_db, "--template=$_template" if defined $_template;
373 if (defined $_shared) {
374 if ($_shared =~ /[a-z]/) {
375 push @init_db, "--shared=$_shared";
376 } else {
377 push @init_db, "--shared";
380 command_noisy(@init_db);
381 $_repository = Git->repository(Repository => ".git");
383 my $set;
384 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
385 foreach my $i (keys %icv) {
386 die "'$set' and '$i' cannot both be set\n" if $set;
387 next unless defined $icv{$i};
388 command_noisy('config', "$pfx.$i", $icv{$i});
389 $set = $i;
391 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
392 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
393 if defined $$ignore_regex;
395 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
396 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
397 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
398 command_noisy('config', "$pfx.placeholder-filename", $$fname);
402 sub init_subdir {
403 my $repo_path = shift or return;
404 mkpath([$repo_path]) unless -d $repo_path;
405 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
406 $ENV{GIT_DIR} = '.git';
407 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
410 sub cmd_clone {
411 my ($url, $path) = @_;
412 if (!defined $path &&
413 (defined $_trunk || @_branches || @_tags ||
414 defined $_stdlayout) &&
415 $url !~ m#^[a-z\+]+://#) {
416 $path = $url;
418 $path = basename($url) if !defined $path || !length $path;
419 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
420 cmd_init($url, $path);
421 command_oneline('config', 'svn.authorsfile', $authors_absolute)
422 if $_authors;
423 Git::SVN::fetch_all($Git::SVN::default_repo_id);
426 sub cmd_init {
427 if (defined $_stdlayout) {
428 $_trunk = 'trunk' if (!defined $_trunk);
429 @_tags = 'tags' if (! @_tags);
430 @_branches = 'branches' if (! @_branches);
432 if (defined $_trunk || @_branches || @_tags) {
433 return cmd_multi_init(@_);
435 my $url = shift or die "SVN repository location required ",
436 "as a command-line argument\n";
437 $url = canonicalize_url($url);
438 init_subdir(@_);
439 do_git_init_db();
441 if ($Git::SVN::_minimize_url eq 'unset') {
442 $Git::SVN::_minimize_url = 0;
445 Git::SVN->init($url);
448 sub cmd_fetch {
449 if (grep /^\d+=./, @_) {
450 die "'<rev>=<commit>' fetch arguments are ",
451 "no longer supported.\n";
453 my ($remote) = @_;
454 if (@_ > 1) {
455 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
457 $Git::SVN::no_reuse_existing = undef;
458 if ($_fetch_parent) {
459 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
460 unless ($gs) {
461 die "Unable to determine upstream SVN information from ",
462 "working tree history\n";
464 # just fetch, don't checkout.
465 $_no_checkout = 'true';
466 $_fetch_all ? $gs->fetch_all : $gs->fetch;
467 } elsif ($_fetch_all) {
468 cmd_multi_fetch();
469 } else {
470 $remote ||= $Git::SVN::default_repo_id;
471 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
475 sub cmd_set_tree {
476 my (@commits) = @_;
477 if ($_stdin || !@commits) {
478 print "Reading from stdin...\n";
479 @commits = ();
480 while (<STDIN>) {
481 if (/\b($sha1_short)\b/o) {
482 unshift @commits, $1;
486 my @revs;
487 foreach my $c (@commits) {
488 my @tmp = command('rev-parse',$c);
489 if (scalar @tmp == 1) {
490 push @revs, $tmp[0];
491 } elsif (scalar @tmp > 1) {
492 push @revs, reverse(command('rev-list',@tmp));
493 } else {
494 fatal "Failed to rev-parse $c";
497 my $gs = Git::SVN->new;
498 my ($r_last, $cmt_last) = $gs->last_rev_commit;
499 $gs->fetch;
500 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
501 fatal "There are new revisions that were fetched ",
502 "and need to be merged (or acknowledged) ",
503 "before committing.\nlast rev: $r_last\n",
504 " current: $gs->{last_rev}";
506 $gs->set_tree($_) foreach @revs;
507 print "Done committing ",scalar @revs," revisions to SVN\n";
508 unlink $gs->{index};
511 sub split_merge_info_range {
512 my ($range) = @_;
513 if ($range =~ /(\d+)-(\d+)/) {
514 return (int($1), int($2));
515 } else {
516 return (int($range), int($range));
520 sub combine_ranges {
521 my ($in) = @_;
523 my @fnums = ();
524 my @arr = split(/,/, $in);
525 for my $element (@arr) {
526 my ($start, $end) = split_merge_info_range($element);
527 push @fnums, $start;
530 my @sorted = @arr [ sort {
531 $fnums[$a] <=> $fnums[$b]
532 } 0..$#arr ];
534 my @return = ();
535 my $last = -1;
536 my $first = -1;
537 for my $element (@sorted) {
538 my ($start, $end) = split_merge_info_range($element);
540 if ($last == -1) {
541 $first = $start;
542 $last = $end;
543 next;
545 if ($start <= $last+1) {
546 if ($end > $last) {
547 $last = $end;
549 next;
551 if ($first == $last) {
552 push @return, "$first";
553 } else {
554 push @return, "$first-$last";
556 $first = $start;
557 $last = $end;
560 if ($first != -1) {
561 if ($first == $last) {
562 push @return, "$first";
563 } else {
564 push @return, "$first-$last";
568 return join(',', @return);
571 sub merge_revs_into_hash {
572 my ($hash, $minfo) = @_;
573 my @lines = split(' ', $minfo);
575 for my $line (@lines) {
576 my ($branchpath, $revs) = split(/:/, $line);
578 if (exists($hash->{$branchpath})) {
579 # Merge the two revision sets
580 my $combined = "$hash->{$branchpath},$revs";
581 $hash->{$branchpath} = combine_ranges($combined);
582 } else {
583 # Just do range combining for consolidation
584 $hash->{$branchpath} = combine_ranges($revs);
589 sub merge_merge_info {
590 my ($mergeinfo_one, $mergeinfo_two) = @_;
591 my %result_hash = ();
593 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
594 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
596 my $result = '';
597 # Sort below is for consistency's sake
598 for my $branchname (sort keys(%result_hash)) {
599 my $revlist = $result_hash{$branchname};
600 $result .= "$branchname:$revlist\n"
602 return $result;
605 sub populate_merge_info {
606 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
608 my %parentshash;
609 read_commit_parents(\%parentshash, $d);
610 my @parents = @{$parentshash{$d}};
611 if ($#parents > 0) {
612 # Merge commit
613 my $all_parents_ok = 1;
614 my $aggregate_mergeinfo = '';
615 my $rooturl = $gs->repos_root;
617 if (defined($rewritten_parent)) {
618 # Replace first parent with newly-rewritten version
619 shift @parents;
620 unshift @parents, $rewritten_parent;
623 foreach my $parent (@parents) {
624 my ($branchurl, $svnrev, $paruuid) =
625 cmt_metadata($parent);
627 unless (defined($svnrev)) {
628 # Should have been caught be preflight check
629 fatal "merge commit $d has ancestor $parent, but that change "
630 ."does not have git-svn metadata!";
632 unless ($branchurl =~ /^$rooturl(.*)/) {
633 fatal "commit $parent git-svn metadata changed mid-run!";
635 my $branchpath = $1;
637 my $ra = Git::SVN::Ra->new($branchurl);
638 my (undef, undef, $props) =
639 $ra->get_dir(canonicalize_path("."), $svnrev);
640 my $par_mergeinfo = $props->{'svn:mergeinfo'};
641 unless (defined $par_mergeinfo) {
642 $par_mergeinfo = '';
644 # Merge previous mergeinfo values
645 $aggregate_mergeinfo =
646 merge_merge_info($aggregate_mergeinfo,
647 $par_mergeinfo, 0);
649 next if $parent eq $parents[0]; # Skip first parent
650 # Add new changes being placed in tree by merge
651 my @cmd = (qw/rev-list --reverse/,
652 $parent, qw/--not/);
653 foreach my $par (@parents) {
654 unless ($par eq $parent) {
655 push @cmd, $par;
658 my @revsin = ();
659 my ($revlist, $ctx) = command_output_pipe(@cmd);
660 while (<$revlist>) {
661 my $irev = $_;
662 chomp $irev;
663 my (undef, $csvnrev, undef) =
664 cmt_metadata($irev);
665 unless (defined $csvnrev) {
666 # A child is missing SVN annotations...
667 # this might be OK, or might not be.
668 warn "W:child $irev is merged into revision "
669 ."$d but does not have git-svn metadata. "
670 ."This means git-svn cannot determine the "
671 ."svn revision numbers to place into the "
672 ."svn:mergeinfo property. You must ensure "
673 ."a branch is entirely committed to "
674 ."SVN before merging it in order for "
675 ."svn:mergeinfo population to function "
676 ."properly";
678 push @revsin, $csvnrev;
680 command_close_pipe($revlist, $ctx);
682 last unless $all_parents_ok;
684 # We now have a list of all SVN revnos which are
685 # merged by this particular parent. Integrate them.
686 next if $#revsin == -1;
687 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
688 $aggregate_mergeinfo =
689 merge_merge_info($aggregate_mergeinfo,
690 $newmergeinfo, 1);
692 if ($all_parents_ok and $aggregate_mergeinfo) {
693 return $aggregate_mergeinfo;
697 return undef;
700 sub cmd_dcommit {
701 my $head = shift;
702 command_noisy(qw/update-index --refresh/);
703 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
704 'Cannot dcommit with a dirty index. Commit your changes first, '
705 . "or stash them with `git stash'.\n";
706 $head ||= 'HEAD';
708 my $old_head;
709 if ($head ne 'HEAD') {
710 $old_head = eval {
711 command_oneline([qw/symbolic-ref -q HEAD/])
713 if ($old_head) {
714 $old_head =~ s{^refs/heads/}{};
715 } else {
716 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
718 command(['checkout', $head], STDERR => 0);
721 my @refs;
722 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
723 unless ($gs) {
724 die "Unable to determine upstream SVN information from ",
725 "$head history.\nPerhaps the repository is empty.";
728 if (defined $_commit_url) {
729 $url = $_commit_url;
730 } else {
731 $url = eval { command_oneline('config', '--get',
732 "svn-remote.$gs->{repo_id}.commiturl") };
733 if (!$url) {
734 $url = $gs->full_pushurl
738 my $last_rev = $_revision if defined $_revision;
739 if ($url) {
740 print "Committing to $url ...\n";
742 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
743 if ($_no_rebase && scalar(@$linear_refs) > 1) {
744 warn "Attempting to commit more than one change while ",
745 "--no-rebase is enabled.\n",
746 "If these changes depend on each other, re-running ",
747 "without --no-rebase may be required."
749 my $expect_url = $url;
751 my $push_merge_info = eval {
752 command_oneline(qw/config --get svn.pushmergeinfo/)
754 if (not defined($push_merge_info)
755 or $push_merge_info eq "false"
756 or $push_merge_info eq "no"
757 or $push_merge_info eq "never") {
758 $push_merge_info = 0;
761 unless (defined($_merge_info) || ! $push_merge_info) {
762 # Preflight check of changes to ensure no issues with mergeinfo
763 # This includes check for uncommitted-to-SVN parents
764 # (other than the first parent, which we will handle),
765 # information from different SVN repos, and paths
766 # which are not underneath this repository root.
767 my $rooturl = $gs->repos_root;
768 foreach my $d (@$linear_refs) {
769 my %parentshash;
770 read_commit_parents(\%parentshash, $d);
771 my @realparents = @{$parentshash{$d}};
772 if ($#realparents > 0) {
773 # Merge commit
774 shift @realparents; # Remove/ignore first parent
775 foreach my $parent (@realparents) {
776 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
777 unless (defined $paruuid) {
778 # A parent is missing SVN annotations...
779 # abort the whole operation.
780 fatal "$parent is merged into revision $d, "
781 ."but does not have git-svn metadata. "
782 ."Either dcommit the branch or use a "
783 ."local cherry-pick, FF merge, or rebase "
784 ."instead of an explicit merge commit.";
787 unless ($paruuid eq $uuid) {
788 # Parent has SVN metadata from different repository
789 fatal "merge parent $parent for change $d has "
790 ."git-svn uuid $paruuid, while current change "
791 ."has uuid $uuid!";
794 unless ($branchurl =~ /^$rooturl(.*)/) {
795 # This branch is very strange indeed.
796 fatal "merge parent $parent for $d is on branch "
797 ."$branchurl, which is not under the "
798 ."git-svn root $rooturl!";
805 my $rewritten_parent;
806 Git::SVN::remove_username($expect_url);
807 if (defined($_merge_info)) {
808 $_merge_info =~ tr{ }{\n};
810 while (1) {
811 my $d = shift @$linear_refs or last;
812 unless (defined $last_rev) {
813 (undef, $last_rev, undef) = cmt_metadata("$d~1");
814 unless (defined $last_rev) {
815 fatal "Unable to extract revision information ",
816 "from commit $d~1";
819 if ($_dry_run) {
820 print "diff-tree $d~1 $d\n";
821 } else {
822 my $cmt_rev;
824 unless (defined($_merge_info) || ! $push_merge_info) {
825 $_merge_info = populate_merge_info($d, $gs,
826 $uuid,
827 $linear_refs,
828 $rewritten_parent);
831 my %ed_opts = ( r => $last_rev,
832 log => get_commit_entry($d)->{log},
833 ra => Git::SVN::Ra->new($url),
834 config => SVN::Core::config_get_config(
835 $Git::SVN::Ra::config_dir
837 tree_a => "$d~1",
838 tree_b => $d,
839 editor_cb => sub {
840 print "Committed r$_[0]\n";
841 $cmt_rev = $_[0];
843 mergeinfo => $_merge_info,
844 svn_path => '');
845 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
846 print "No changes\n$d~1 == $d\n";
847 } elsif ($parents->{$d} && @{$parents->{$d}}) {
848 $gs->{inject_parents_dcommit}->{$cmt_rev} =
849 $parents->{$d};
851 $_fetch_all ? $gs->fetch_all : $gs->fetch;
852 $last_rev = $cmt_rev;
853 next if $_no_rebase;
855 # we always want to rebase against the current HEAD,
856 # not any head that was passed to us
857 my @diff = command('diff-tree', $d,
858 $gs->refname, '--');
859 my @finish;
860 if (@diff) {
861 @finish = rebase_cmd();
862 print STDERR "W: $d and ", $gs->refname,
863 " differ, using @finish:\n",
864 join("\n", @diff), "\n";
865 } else {
866 print "No changes between current HEAD and ",
867 $gs->refname,
868 "\nResetting to the latest ",
869 $gs->refname, "\n";
870 @finish = qw/reset --mixed/;
872 command_noisy(@finish, $gs->refname);
874 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
876 if (@diff) {
877 @refs = ();
878 my ($url_, $rev_, $uuid_, $gs_) =
879 working_head_info('HEAD', \@refs);
880 my ($linear_refs_, $parents_) =
881 linearize_history($gs_, \@refs);
882 if (scalar(@$linear_refs) !=
883 scalar(@$linear_refs_)) {
884 fatal "# of revisions changed ",
885 "\nbefore:\n",
886 join("\n", @$linear_refs),
887 "\n\nafter:\n",
888 join("\n", @$linear_refs_), "\n",
889 'If you are attempting to commit ',
890 "merges, try running:\n\t",
891 'git rebase --interactive',
892 '--preserve-merges ',
893 $gs->refname,
894 "\nBefore dcommitting";
896 if ($url_ ne $expect_url) {
897 if ($url_ eq $gs->metadata_url) {
898 print
899 "Accepting rewritten URL:",
900 " $url_\n";
901 } else {
902 fatal
903 "URL mismatch after rebase:",
904 " $url_ != $expect_url";
907 if ($uuid_ ne $uuid) {
908 fatal "uuid mismatch after rebase: ",
909 "$uuid_ != $uuid";
911 # remap parents
912 my (%p, @l, $i);
913 for ($i = 0; $i < scalar @$linear_refs; $i++) {
914 my $new = $linear_refs_->[$i] or next;
915 $p{$new} =
916 $parents->{$linear_refs->[$i]};
917 push @l, $new;
919 $parents = \%p;
920 $linear_refs = \@l;
925 if ($old_head) {
926 my $new_head = command_oneline(qw/rev-parse HEAD/);
927 my $new_is_symbolic = eval {
928 command_oneline(qw/symbolic-ref -q HEAD/);
930 if ($new_is_symbolic) {
931 print "dcommitted the branch ", $head, "\n";
932 } else {
933 print "dcommitted on a detached HEAD because you gave ",
934 "a revision argument.\n",
935 "The rewritten commit is: ", $new_head, "\n";
937 command(['checkout', $old_head], STDERR => 0);
940 unlink $gs->{index};
943 sub cmd_branch {
944 my ($branch_name, $head) = @_;
946 unless (defined $branch_name && length $branch_name) {
947 die(($_tag ? "tag" : "branch") . " name required\n");
949 $head ||= 'HEAD';
951 my (undef, $rev, undef, $gs) = working_head_info($head);
952 my $src = $gs->full_pushurl;
954 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
955 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
956 my $glob;
957 if ($#{$allglobs} == 0) {
958 $glob = $allglobs->[0];
959 } else {
960 unless(defined $_branch_dest) {
961 die "Multiple ",
962 $_tag ? "tag" : "branch",
963 " paths defined for Subversion repository.\n",
964 "You must specify where you want to create the ",
965 $_tag ? "tag" : "branch",
966 " with the --destination argument.\n";
968 foreach my $g (@{$allglobs}) {
969 # SVN::Git::Editor could probably be moved to Git.pm..
970 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
971 if ($_branch_dest =~ /$re/) {
972 $glob = $g;
973 last;
976 unless (defined $glob) {
977 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
978 foreach my $g (@{$allglobs}) {
979 $g->{path}->{left} =~ /$dest_re/ or next;
980 if (defined $glob) {
981 die "Ambiguous destination: ",
982 $_branch_dest, "\nmatches both '",
983 $glob->{path}->{left}, "' and '",
984 $g->{path}->{left}, "'\n";
986 $glob = $g;
988 unless (defined $glob) {
989 die "Unknown ",
990 $_tag ? "tag" : "branch",
991 " destination $_branch_dest\n";
995 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
996 my $url;
997 if (defined $_commit_url) {
998 $url = $_commit_url;
999 } else {
1000 $url = eval { command_oneline('config', '--get',
1001 "svn-remote.$gs->{repo_id}.commiturl") };
1002 if (!$url) {
1003 $url = $remote->{pushurl} || $remote->{url};
1006 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1008 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1009 $src=~s/^http:/https:/;
1012 ::_req_svn();
1014 my $ctx = SVN::Client->new(
1015 auth => Git::SVN::Ra::_auth_providers(),
1016 log_msg => sub {
1017 ${ $_[0] } = defined $_message
1018 ? $_message
1019 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1020 . $branch_name;
1024 eval {
1025 $ctx->ls($dst, 'HEAD', 0);
1026 } and die "branch ${branch_name} already exists\n";
1028 print "Copying ${src} at r${rev} to ${dst}...\n";
1029 $ctx->copy($src, $rev, $dst)
1030 unless $_dry_run;
1032 $gs->fetch_all;
1035 sub cmd_find_rev {
1036 my $revision_or_hash = shift or die "SVN or git revision required ",
1037 "as a command-line argument\n";
1038 my $result;
1039 if ($revision_or_hash =~ /^r\d+$/) {
1040 my $head = shift;
1041 $head ||= 'HEAD';
1042 my @refs;
1043 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1044 unless ($gs) {
1045 die "Unable to determine upstream SVN information from ",
1046 "$head history\n";
1048 my $desired_revision = substr($revision_or_hash, 1);
1049 $result = $gs->rev_map_get($desired_revision, $uuid);
1050 } else {
1051 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1052 $result = $rev;
1054 print "$result\n" if $result;
1057 sub auto_create_empty_directories {
1058 my ($gs) = @_;
1059 my $var = eval { command_oneline('config', '--get', '--bool',
1060 "svn-remote.$gs->{repo_id}.automkdirs") };
1061 # By default, create empty directories by consulting the unhandled log,
1062 # but allow setting it to 'false' to skip it.
1063 return !($var && $var eq 'false');
1066 sub cmd_rebase {
1067 command_noisy(qw/update-index --refresh/);
1068 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1069 unless ($gs) {
1070 die "Unable to determine upstream SVN information from ",
1071 "working tree history\n";
1073 if ($_dry_run) {
1074 print "Remote Branch: " . $gs->refname . "\n";
1075 print "SVN URL: " . $url . "\n";
1076 return;
1078 if (command(qw/diff-index HEAD --/)) {
1079 print STDERR "Cannot rebase with uncommited changes:\n";
1080 command_noisy('status');
1081 exit 1;
1083 unless ($_local) {
1084 # rebase will checkout for us, so no need to do it explicitly
1085 $_no_checkout = 'true';
1086 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1088 command_noisy(rebase_cmd(), $gs->refname);
1089 if (auto_create_empty_directories($gs)) {
1090 $gs->mkemptydirs;
1094 sub cmd_show_ignore {
1095 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1096 $gs ||= Git::SVN->new;
1097 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1098 $gs->prop_walk($gs->{path}, $r, sub {
1099 my ($gs, $path, $props) = @_;
1100 print STDOUT "\n# $path\n";
1101 my $s = $props->{'svn:ignore'} or return;
1102 $s =~ s/[\r\n]+/\n/g;
1103 $s =~ s/^\n+//;
1104 chomp $s;
1105 $s =~ s#^#$path#gm;
1106 print STDOUT "$s\n";
1110 sub cmd_show_externals {
1111 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1112 $gs ||= Git::SVN->new;
1113 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1114 $gs->prop_walk($gs->{path}, $r, sub {
1115 my ($gs, $path, $props) = @_;
1116 print STDOUT "\n# $path\n";
1117 my $s = $props->{'svn:externals'} or return;
1118 $s =~ s/[\r\n]+/\n/g;
1119 chomp $s;
1120 $s =~ s#^#$path#gm;
1121 print STDOUT "$s\n";
1125 sub cmd_create_ignore {
1126 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1127 $gs ||= Git::SVN->new;
1128 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1129 $gs->prop_walk($gs->{path}, $r, sub {
1130 my ($gs, $path, $props) = @_;
1131 # $path is of the form /path/to/dir/
1132 $path = '.' . $path;
1133 # SVN can have attributes on empty directories,
1134 # which git won't track
1135 mkpath([$path]) unless -d $path;
1136 my $ignore = $path . '.gitignore';
1137 my $s = $props->{'svn:ignore'} or return;
1138 open(GITIGNORE, '>', $ignore)
1139 or fatal("Failed to open `$ignore' for writing: $!");
1140 $s =~ s/[\r\n]+/\n/g;
1141 $s =~ s/^\n+//;
1142 chomp $s;
1143 # Prefix all patterns so that the ignore doesn't apply
1144 # to sub-directories.
1145 $s =~ s#^#/#gm;
1146 print GITIGNORE "$s\n";
1147 close(GITIGNORE)
1148 or fatal("Failed to close `$ignore': $!");
1149 command_noisy('add', '-f', $ignore);
1153 sub cmd_mkdirs {
1154 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1155 $gs ||= Git::SVN->new;
1156 $gs->mkemptydirs($_revision);
1159 sub canonicalize_path {
1160 my ($path) = @_;
1161 my $dot_slash_added = 0;
1162 if (substr($path, 0, 1) ne "/") {
1163 $path = "./" . $path;
1164 $dot_slash_added = 1;
1166 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1167 # good reason), so let's do this manually.
1168 $path =~ s#/+#/#g;
1169 $path =~ s#/\.(?:/|$)#/#g;
1170 $path =~ s#/[^/]+/\.\.##g;
1171 $path =~ s#/$##g;
1172 $path =~ s#^\./## if $dot_slash_added;
1173 $path =~ s#^/##;
1174 $path =~ s#^\.$##;
1175 return $path;
1178 sub canonicalize_url {
1179 my ($url) = @_;
1180 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1181 return $url;
1184 # get_svnprops(PATH)
1185 # ------------------
1186 # Helper for cmd_propget and cmd_proplist below.
1187 sub get_svnprops {
1188 my $path = shift;
1189 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1190 $gs ||= Git::SVN->new;
1192 # prefix THE PATH by the sub-directory from which the user
1193 # invoked us.
1194 $path = $cmd_dir_prefix . $path;
1195 fatal("No such file or directory: $path") unless -e $path;
1196 my $is_dir = -d $path ? 1 : 0;
1197 $path = $gs->{path} . '/' . $path;
1199 # canonicalize the path (otherwise libsvn will abort or fail to
1200 # find the file)
1201 $path = canonicalize_path($path);
1203 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1204 my $props;
1205 if ($is_dir) {
1206 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1208 else {
1209 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1211 return $props;
1214 # cmd_propget (PROP, PATH)
1215 # ------------------------
1216 # Print the SVN property PROP for PATH.
1217 sub cmd_propget {
1218 my ($prop, $path) = @_;
1219 $path = '.' if not defined $path;
1220 usage(1) if not defined $prop;
1221 my $props = get_svnprops($path);
1222 if (not defined $props->{$prop}) {
1223 fatal("`$path' does not have a `$prop' SVN property.");
1225 print $props->{$prop} . "\n";
1228 # cmd_proplist (PATH)
1229 # -------------------
1230 # Print the list of SVN properties for PATH.
1231 sub cmd_proplist {
1232 my $path = shift;
1233 $path = '.' if not defined $path;
1234 my $props = get_svnprops($path);
1235 print "Properties on '$path':\n";
1236 foreach (sort keys %{$props}) {
1237 print " $_\n";
1241 sub cmd_multi_init {
1242 my $url = shift;
1243 unless (defined $_trunk || @_branches || @_tags) {
1244 usage(1);
1247 $_prefix = '' unless defined $_prefix;
1248 if (defined $url) {
1249 $url = canonicalize_url($url);
1250 init_subdir(@_);
1252 do_git_init_db();
1253 if (defined $_trunk) {
1254 $_trunk =~ s#^/+##;
1255 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1256 # try both old-style and new-style lookups:
1257 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1258 unless ($gs_trunk) {
1259 my ($trunk_url, $trunk_path) =
1260 complete_svn_url($url, $_trunk);
1261 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1262 undef, $trunk_ref);
1265 return unless @_branches || @_tags;
1266 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1267 foreach my $path (@_branches) {
1268 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1270 foreach my $path (@_tags) {
1271 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1275 sub cmd_multi_fetch {
1276 $Git::SVN::no_reuse_existing = undef;
1277 my $remotes = Git::SVN::read_all_remotes();
1278 foreach my $repo_id (sort keys %$remotes) {
1279 if ($remotes->{$repo_id}->{url}) {
1280 Git::SVN::fetch_all($repo_id, $remotes);
1285 # this command is special because it requires no metadata
1286 sub cmd_commit_diff {
1287 my ($ta, $tb, $url) = @_;
1288 my $usage = "Usage: $0 commit-diff -r<revision> ".
1289 "<tree-ish> <tree-ish> [<URL>]";
1290 fatal($usage) if (!defined $ta || !defined $tb);
1291 my $svn_path = '';
1292 if (!defined $url) {
1293 my $gs = eval { Git::SVN->new };
1294 if (!$gs) {
1295 fatal("Needed URL or usable git-svn --id in ",
1296 "the command-line\n", $usage);
1298 $url = $gs->{url};
1299 $svn_path = $gs->{path};
1301 unless (defined $_revision) {
1302 fatal("-r|--revision is a required argument\n", $usage);
1304 if (defined $_message && defined $_file) {
1305 fatal("Both --message/-m and --file/-F specified ",
1306 "for the commit message.\n",
1307 "I have no idea what you mean");
1309 if (defined $_file) {
1310 $_message = file_to_s($_file);
1311 } else {
1312 $_message ||= get_commit_entry($tb)->{log};
1314 my $ra ||= Git::SVN::Ra->new($url);
1315 my $r = $_revision;
1316 if ($r eq 'HEAD') {
1317 $r = $ra->get_latest_revnum;
1318 } elsif ($r !~ /^\d+$/) {
1319 die "revision argument: $r not understood by git-svn\n";
1321 my %ed_opts = ( r => $r,
1322 log => $_message,
1323 ra => $ra,
1324 tree_a => $ta,
1325 tree_b => $tb,
1326 editor_cb => sub { print "Committed r$_[0]\n" },
1327 svn_path => $svn_path );
1328 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1329 print "No changes\n$ta == $tb\n";
1333 sub escape_uri_only {
1334 my ($uri) = @_;
1335 my @tmp;
1336 foreach (split m{/}, $uri) {
1337 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1338 push @tmp, $_;
1340 join('/', @tmp);
1343 sub escape_url {
1344 my ($url) = @_;
1345 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1346 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1347 $url = "$scheme://$domain$uri";
1349 $url;
1352 sub cmd_info {
1353 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1354 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1355 if (exists $_[1]) {
1356 die "Too many arguments specified\n";
1359 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1361 if (!$file_type && !$diff_status) {
1362 print STDERR "svn: '$path' is not under version control\n";
1363 exit 1;
1366 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1367 unless ($gs) {
1368 die "Unable to determine upstream SVN information from ",
1369 "working tree history\n";
1372 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1373 $path = "." if $path eq "";
1375 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1377 if ($_url) {
1378 print escape_url($full_url), "\n";
1379 return;
1382 my $result = "Path: $path\n";
1383 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1384 $result .= "URL: " . escape_url($full_url) . "\n";
1386 eval {
1387 my $repos_root = $gs->repos_root;
1388 Git::SVN::remove_username($repos_root);
1389 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1391 if ($@) {
1392 $result .= "Repository Root: (offline)\n";
1394 ::_req_svn();
1395 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1396 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1397 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1399 $result .= "Node Kind: " .
1400 ($file_type eq "dir" ? "directory" : "file") . "\n";
1402 my $schedule = $diff_status eq "A"
1403 ? "add"
1404 : ($diff_status eq "D" ? "delete" : "normal");
1405 $result .= "Schedule: $schedule\n";
1407 if ($diff_status eq "A") {
1408 print $result, "\n";
1409 return;
1412 my ($lc_author, $lc_rev, $lc_date_utc);
1413 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1414 my $log = command_output_pipe(@args);
1415 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1416 while (<$log>) {
1417 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1418 $lc_author = $1;
1419 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1420 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1421 (undef, $lc_rev, undef) = ::extract_metadata($1);
1424 close $log;
1426 Git::SVN::Log::set_local_timezone();
1428 $result .= "Last Changed Author: $lc_author\n";
1429 $result .= "Last Changed Rev: $lc_rev\n";
1430 $result .= "Last Changed Date: " .
1431 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1433 if ($file_type ne "dir") {
1434 my $text_last_updated_date =
1435 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1436 $result .=
1437 "Text Last Updated: " .
1438 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1439 "\n";
1440 my $checksum;
1441 if ($diff_status eq "D") {
1442 my ($fh, $ctx) =
1443 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1444 if ($file_type eq "link") {
1445 my $file_name = <$fh>;
1446 $checksum = md5sum("link $file_name");
1447 } else {
1448 $checksum = md5sum($fh);
1450 command_close_pipe($fh, $ctx);
1451 } elsif ($file_type eq "link") {
1452 my $file_name =
1453 command(qw(cat-file blob), "HEAD:$path");
1454 $checksum =
1455 md5sum("link " . $file_name);
1456 } else {
1457 open FILE, "<", $path or die $!;
1458 $checksum = md5sum(\*FILE);
1459 close FILE or die $!;
1461 $result .= "Checksum: " . $checksum . "\n";
1464 print $result, "\n";
1467 sub cmd_reset {
1468 my $target = shift || $_revision or die "SVN revision required\n";
1469 $target = $1 if $target =~ /^r(\d+)$/;
1470 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1471 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1472 unless ($gs) {
1473 die "Unable to determine upstream SVN information from ".
1474 "history\n";
1476 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1477 die "Cannot find SVN revision $target\n" unless defined($c);
1478 $gs->rev_map_set($r, $c, 'reset', $uuid);
1479 print "r$r = $c ($gs->{ref_id})\n";
1482 sub cmd_gc {
1483 if (!$can_compress) {
1484 warn "Compress::Zlib could not be found; unhandled.log " .
1485 "files will not be compressed.\n";
1487 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1490 ########################### utility functions #########################
1492 sub rebase_cmd {
1493 my @cmd = qw/rebase/;
1494 push @cmd, '-v' if $_verbose;
1495 push @cmd, qw/--merge/ if $_merge;
1496 push @cmd, "--strategy=$_strategy" if $_strategy;
1497 @cmd;
1500 sub post_fetch_checkout {
1501 return if $_no_checkout;
1502 my $gs = $Git::SVN::_head or return;
1503 return if verify_ref('refs/heads/master^0');
1505 # look for "trunk" ref if it exists
1506 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1507 my $fetch = $remote->{fetch};
1508 if ($fetch) {
1509 foreach my $p (keys %$fetch) {
1510 basename($fetch->{$p}) eq 'trunk' or next;
1511 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1512 last;
1516 my $valid_head = verify_ref('HEAD^0');
1517 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1518 return if ($valid_head || !verify_ref('HEAD^0'));
1520 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1521 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1522 return if -f $index;
1524 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1525 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1526 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1527 print STDERR "Checked out HEAD:\n ",
1528 $gs->full_url, " r", $gs->last_rev, "\n";
1529 if (auto_create_empty_directories($gs)) {
1530 $gs->mkemptydirs($gs->last_rev);
1534 sub complete_svn_url {
1535 my ($url, $path) = @_;
1536 $path =~ s#/+$##;
1537 if ($path !~ m#^[a-z\+]+://#) {
1538 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1539 fatal("E: '$path' is not a complete URL ",
1540 "and a separate URL is not specified");
1542 return ($url, $path);
1544 return ($path, '');
1547 sub complete_url_ls_init {
1548 my ($ra, $repo_path, $switch, $pfx) = @_;
1549 unless ($repo_path) {
1550 print STDERR "W: $switch not specified\n";
1551 return;
1553 $repo_path =~ s#/+$##;
1554 if ($repo_path =~ m#^[a-z\+]+://#) {
1555 $ra = Git::SVN::Ra->new($repo_path);
1556 $repo_path = '';
1557 } else {
1558 $repo_path =~ s#^/+##;
1559 unless ($ra) {
1560 fatal("E: '$repo_path' is not a complete URL ",
1561 "and a separate URL is not specified");
1564 my $url = $ra->{url};
1565 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1566 my $k = "svn-remote.$gs->{repo_id}.url";
1567 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1568 if ($orig_url && ($orig_url ne $gs->{url})) {
1569 die "$k already set: $orig_url\n",
1570 "wanted to set to: $gs->{url}\n";
1572 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1573 my $remote_path = "$gs->{path}/$repo_path";
1574 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1575 $remote_path =~ s#/+#/#g;
1576 $remote_path =~ s#^/##g;
1577 $remote_path .= "/*" if $remote_path !~ /\*/;
1578 my ($n) = ($switch =~ /^--(\w+)/);
1579 if (length $pfx && $pfx !~ m#/$#) {
1580 die "--prefix='$pfx' must have a trailing slash '/'\n";
1582 command_noisy('config',
1583 '--add',
1584 "svn-remote.$gs->{repo_id}.$n",
1585 "$remote_path:refs/remotes/$pfx*" .
1586 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1589 sub verify_ref {
1590 my ($ref) = @_;
1591 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1592 { STDERR => 0 }); };
1595 sub get_tree_from_treeish {
1596 my ($treeish) = @_;
1597 # $treeish can be a symbolic ref, too:
1598 my $type = command_oneline(qw/cat-file -t/, $treeish);
1599 my $expected;
1600 while ($type eq 'tag') {
1601 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1603 if ($type eq 'commit') {
1604 $expected = (grep /^tree /, command(qw/cat-file commit/,
1605 $treeish))[0];
1606 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1607 die "Unable to get tree from $treeish\n" unless $expected;
1608 } elsif ($type eq 'tree') {
1609 $expected = $treeish;
1610 } else {
1611 die "$treeish is a $type, expected tree, tag or commit\n";
1613 return $expected;
1616 sub get_commit_entry {
1617 my ($treeish) = shift;
1618 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1619 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1620 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1621 open my $log_fh, '>', $commit_editmsg or croak $!;
1623 my $type = command_oneline(qw/cat-file -t/, $treeish);
1624 if ($type eq 'commit' || $type eq 'tag') {
1625 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1626 $type, $treeish);
1627 my $in_msg = 0;
1628 my $author;
1629 my $saw_from = 0;
1630 my $msgbuf = "";
1631 while (<$msg_fh>) {
1632 if (!$in_msg) {
1633 $in_msg = 1 if (/^\s*$/);
1634 $author = $1 if (/^author (.*>)/);
1635 } elsif (/^git-svn-id: /) {
1636 # skip this for now, we regenerate the
1637 # correct one on re-fetch anyways
1638 # TODO: set *:merge properties or like...
1639 } else {
1640 if (/^From:/ || /^Signed-off-by:/) {
1641 $saw_from = 1;
1643 $msgbuf .= $_;
1646 $msgbuf =~ s/\s+$//s;
1647 if ($Git::SVN::_add_author_from && defined($author)
1648 && !$saw_from) {
1649 $msgbuf .= "\n\nFrom: $author";
1651 print $log_fh $msgbuf or croak $!;
1652 command_close_pipe($msg_fh, $ctx);
1654 close $log_fh or croak $!;
1656 if ($_edit || ($type eq 'tree')) {
1657 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1658 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1660 rename $commit_editmsg, $commit_msg or croak $!;
1662 require Encode;
1663 # SVN requires messages to be UTF-8 when entering the repo
1664 local $/;
1665 open $log_fh, '<', $commit_msg or croak $!;
1666 binmode $log_fh;
1667 chomp($log_entry{log} = <$log_fh>);
1669 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1670 my $msg = $log_entry{log};
1672 eval { $msg = Encode::decode($enc, $msg, 1) };
1673 if ($@) {
1674 die "Could not decode as $enc:\n", $msg,
1675 "\nPerhaps you need to set i18n.commitencoding\n";
1678 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1679 die "Could not encode as UTF-8:\n$msg\n" if $@;
1681 $log_entry{log} = $msg;
1683 close $log_fh or croak $!;
1685 unlink $commit_msg;
1686 \%log_entry;
1689 sub s_to_file {
1690 my ($str, $file, $mode) = @_;
1691 open my $fd,'>',$file or croak $!;
1692 print $fd $str,"\n" or croak $!;
1693 close $fd or croak $!;
1694 chmod ($mode &~ umask, $file) if (defined $mode);
1697 sub file_to_s {
1698 my $file = shift;
1699 open my $fd,'<',$file or croak "$!: file: $file\n";
1700 local $/;
1701 my $ret = <$fd>;
1702 close $fd or croak $!;
1703 $ret =~ s/\s*$//s;
1704 return $ret;
1707 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1708 sub load_authors {
1709 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1710 my $log = $cmd eq 'log';
1711 while (<$authors>) {
1712 chomp;
1713 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1714 my ($user, $name, $email) = ($1, $2, $3);
1715 if ($log) {
1716 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1717 } else {
1718 $users{$user} = [$name, $email];
1721 close $authors or croak $!;
1724 # convert GetOpt::Long specs for use by git-config
1725 sub read_git_config {
1726 my $opts = shift;
1727 my @config_only;
1728 foreach my $o (keys %$opts) {
1729 # if we have mixedCase and a long option-only, then
1730 # it's a config-only variable that we don't need for
1731 # the command-line.
1732 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1733 my $v = $opts->{$o};
1734 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1735 $key =~ s/-//g;
1736 my $arg = 'git config';
1737 $arg .= ' --int' if ($o =~ /[:=]i$/);
1738 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1739 if (ref $v eq 'ARRAY') {
1740 chomp(my @tmp = `$arg --get-all svn.$key`);
1741 @$v = @tmp if @tmp;
1742 } else {
1743 chomp(my $tmp = `$arg --get svn.$key`);
1744 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1745 $$v = $tmp;
1749 delete @$opts{@config_only} if @config_only;
1752 sub extract_metadata {
1753 my $id = shift or return (undef, undef, undef);
1754 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1755 \s([a-f\d\-]+)$/ix);
1756 if (!defined $rev || !$uuid || !$url) {
1757 # some of the original repositories I made had
1758 # identifiers like this:
1759 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1761 return ($url, $rev, $uuid);
1764 sub cmt_metadata {
1765 return extract_metadata((grep(/^git-svn-id: /,
1766 command(qw/cat-file commit/, shift)))[-1]);
1769 sub cmt_sha2rev_batch {
1770 my %s2r;
1771 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1772 my $list = shift;
1774 foreach my $sha (@{$list}) {
1775 my $first = 1;
1776 my $size = 0;
1777 print $out $sha, "\n";
1779 while (my $line = <$in>) {
1780 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1781 last;
1782 } elsif ($first &&
1783 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1784 $first = 0;
1785 $size = $1;
1786 next;
1787 } elsif ($line =~ /^(git-svn-id: )/) {
1788 my (undef, $rev, undef) =
1789 extract_metadata($line);
1790 $s2r{$sha} = $rev;
1793 $size -= length($line);
1794 last if ($size == 0);
1798 command_close_bidi_pipe($pid, $in, $out, $ctx);
1800 return \%s2r;
1803 sub working_head_info {
1804 my ($head, $refs) = @_;
1805 my @args = qw/log --no-color --no-decorate --first-parent
1806 --pretty=medium/;
1807 my ($fh, $ctx) = command_output_pipe(@args, $head);
1808 my $hash;
1809 my %max;
1810 while (<$fh>) {
1811 if ( m{^commit ($::sha1)$} ) {
1812 unshift @$refs, $hash if $hash and $refs;
1813 $hash = $1;
1814 next;
1816 next unless s{^\s*(git-svn-id:)}{$1};
1817 my ($url, $rev, $uuid) = extract_metadata($_);
1818 if (defined $url && defined $rev) {
1819 next if $max{$url} and $max{$url} < $rev;
1820 if (my $gs = Git::SVN->find_by_url($url)) {
1821 my $c = $gs->rev_map_get($rev, $uuid);
1822 if ($c && $c eq $hash) {
1823 close $fh; # break the pipe
1824 return ($url, $rev, $uuid, $gs);
1825 } else {
1826 $max{$url} ||= $gs->rev_map_max;
1831 command_close_pipe($fh, $ctx);
1832 (undef, undef, undef, undef);
1835 sub read_commit_parents {
1836 my ($parents, $c) = @_;
1837 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1838 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1839 @{$parents->{$c}} = split(/ /, $p);
1842 sub linearize_history {
1843 my ($gs, $refs) = @_;
1844 my %parents;
1845 foreach my $c (@$refs) {
1846 read_commit_parents(\%parents, $c);
1849 my @linear_refs;
1850 my %skip = ();
1851 my $last_svn_commit = $gs->last_commit;
1852 foreach my $c (reverse @$refs) {
1853 next if $c eq $last_svn_commit;
1854 last if $skip{$c};
1856 unshift @linear_refs, $c;
1857 $skip{$c} = 1;
1859 # we only want the first parent to diff against for linear
1860 # history, we save the rest to inject when we finalize the
1861 # svn commit
1862 my $fp_a = verify_ref("$c~1");
1863 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1864 if (!$fp_a || !$fp_b) {
1865 die "Commit $c\n",
1866 "has no parent commit, and therefore ",
1867 "nothing to diff against.\n",
1868 "You should be working from a repository ",
1869 "originally created by git-svn\n";
1871 if ($fp_a ne $fp_b) {
1872 die "$c~1 = $fp_a, however parsing commit $c ",
1873 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1876 foreach my $p (@{$parents{$c}}) {
1877 $skip{$p} = 1;
1880 (\@linear_refs, \%parents);
1883 sub find_file_type_and_diff_status {
1884 my ($path) = @_;
1885 return ('dir', '') if $path eq '';
1887 my $diff_output =
1888 command_oneline(qw(diff --cached --name-status --), $path) || "";
1889 my $diff_status = (split(' ', $diff_output))[0] || "";
1891 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1893 return (undef, undef) if !$diff_status && !$ls_tree;
1895 if ($diff_status eq "A") {
1896 return ("link", $diff_status) if -l $path;
1897 return ("dir", $diff_status) if -d $path;
1898 return ("file", $diff_status);
1901 my $mode = (split(' ', $ls_tree))[0] || "";
1903 return ("link", $diff_status) if $mode eq "120000";
1904 return ("dir", $diff_status) if $mode eq "040000";
1905 return ("file", $diff_status);
1908 sub md5sum {
1909 my $arg = shift;
1910 my $ref = ref $arg;
1911 my $md5 = Digest::MD5->new();
1912 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1913 $md5->addfile($arg) or croak $!;
1914 } elsif ($ref eq 'SCALAR') {
1915 $md5->add($$arg) or croak $!;
1916 } elsif (!$ref) {
1917 $md5->add($arg) or croak $!;
1918 } else {
1919 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1921 return $md5->hexdigest();
1924 sub gc_directory {
1925 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1926 my $out_filename = $_ . ".gz";
1927 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1928 binmode $in_fh;
1929 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1930 die "Unable to open $out_filename: $!\n";
1932 my $res;
1933 while ($res = sysread($in_fh, my $str, 1024)) {
1934 $gz->gzwrite($str) or
1935 die "Unable to write: ".$gz->gzerror()."!\n";
1937 unlink $_ or die "unlink $File::Find::name: $!\n";
1938 } elsif (-f $_ && basename($_) eq "index") {
1939 unlink $_ or die "unlink $_: $!\n";
1943 package Git::SVN;
1944 use strict;
1945 use warnings;
1946 use Fcntl qw/:DEFAULT :seek/;
1947 use constant rev_map_fmt => 'NH40';
1948 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1949 $_repack $_repack_flags $_use_svm_props $_head
1950 $_use_svnsync_props $no_reuse_existing $_minimize_url
1951 $_use_log_author $_add_author_from $_localtime/;
1952 use Carp qw/croak/;
1953 use File::Path qw/mkpath/;
1954 use File::Copy qw/copy/;
1955 use IPC::Open3;
1956 use Memoize; # core since 5.8.0, Jul 2002
1957 use Memoize::Storable;
1959 my ($_gc_nr, $_gc_period);
1961 # properties that we do not log:
1962 my %SKIP_PROP;
1963 BEGIN {
1964 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1965 svn:special svn:executable
1966 svn:entry:committed-rev
1967 svn:entry:last-author
1968 svn:entry:uuid
1969 svn:entry:committed-date/;
1971 # some options are read globally, but can be overridden locally
1972 # per [svn-remote "..."] section. Command-line options will *NOT*
1973 # override options set in an [svn-remote "..."] section
1974 no strict 'refs';
1975 for my $option (qw/follow_parent no_metadata use_svm_props
1976 use_svnsync_props/) {
1977 my $key = $option;
1978 $key =~ tr/_//d;
1979 my $prop = "-$option";
1980 *$option = sub {
1981 my ($self) = @_;
1982 return $self->{$prop} if exists $self->{$prop};
1983 my $k = "svn-remote.$self->{repo_id}.$key";
1984 eval { command_oneline(qw/config --get/, $k) };
1985 if ($@) {
1986 $self->{$prop} = ${"Git::SVN::_$option"};
1987 } else {
1988 my $v = command_oneline(qw/config --bool/,$k);
1989 $self->{$prop} = $v eq 'false' ? 0 : 1;
1991 return $self->{$prop};
1997 my (%LOCKFILES, %INDEX_FILES);
1998 END {
1999 unlink keys %LOCKFILES if %LOCKFILES;
2000 unlink keys %INDEX_FILES if %INDEX_FILES;
2003 sub resolve_local_globs {
2004 my ($url, $fetch, $glob_spec) = @_;
2005 return unless defined $glob_spec;
2006 my $ref = $glob_spec->{ref};
2007 my $path = $glob_spec->{path};
2008 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2009 next unless m#^$ref->{regex}$#;
2010 my $p = $1;
2011 my $pathname = desanitize_refname($path->full_path($p));
2012 my $refname = desanitize_refname($ref->full_path($p));
2013 if (my $existing = $fetch->{$pathname}) {
2014 if ($existing ne $refname) {
2015 die "Refspec conflict:\n",
2016 "existing: $existing\n",
2017 " globbed: $refname\n";
2019 my $u = (::cmt_metadata("$refname"))[0];
2020 $u =~ s!^\Q$url\E(/|$)!! or die
2021 "$refname: '$url' not found in '$u'\n";
2022 if ($pathname ne $u) {
2023 warn "W: Refspec glob conflict ",
2024 "(ref: $refname):\n",
2025 "expected path: $pathname\n",
2026 " real path: $u\n",
2027 "Continuing ahead with $u\n";
2028 next;
2030 } else {
2031 $fetch->{$pathname} = $refname;
2036 sub parse_revision_argument {
2037 my ($base, $head) = @_;
2038 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2039 return ($base, $head);
2041 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2042 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2043 return ($head, $head) if ($::_revision eq 'HEAD');
2044 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2045 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2046 die "revision argument: $::_revision not understood by git-svn\n";
2049 sub fetch_all {
2050 my ($repo_id, $remotes) = @_;
2051 if (ref $repo_id) {
2052 my $gs = $repo_id;
2053 $repo_id = undef;
2054 $repo_id = $gs->{repo_id};
2056 $remotes ||= read_all_remotes();
2057 my $remote = $remotes->{$repo_id} or
2058 die "[svn-remote \"$repo_id\"] unknown\n";
2059 my $fetch = $remote->{fetch};
2060 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2061 my (@gs, @globs);
2062 my $ra = Git::SVN::Ra->new($url);
2063 my $uuid = $ra->get_uuid;
2064 my $head = $ra->get_latest_revnum;
2066 # ignore errors, $head revision may not even exist anymore
2067 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2068 warn "W: $@\n" if $@;
2070 my $base = defined $fetch ? $head : 0;
2072 # read the max revs for wildcard expansion (branches/*, tags/*)
2073 foreach my $t (qw/branches tags/) {
2074 defined $remote->{$t} or next;
2075 push @globs, @{$remote->{$t}};
2077 my $max_rev = eval { tmp_config(qw/--int --get/,
2078 "svn-remote.$repo_id.${t}-maxRev") };
2079 if (defined $max_rev && ($max_rev < $base)) {
2080 $base = $max_rev;
2081 } elsif (!defined $max_rev) {
2082 $base = 0;
2086 if ($fetch) {
2087 foreach my $p (sort keys %$fetch) {
2088 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2089 my $lr = $gs->rev_map_max;
2090 if (defined $lr) {
2091 $base = $lr if ($lr < $base);
2093 push @gs, $gs;
2097 ($base, $head) = parse_revision_argument($base, $head);
2098 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2101 sub read_all_remotes {
2102 my $r = {};
2103 my $use_svm_props = eval { command_oneline(qw/config --bool
2104 svn.useSvmProps/) };
2105 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2106 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2107 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2108 if (m!^(.+)\.fetch=$svn_refspec$!) {
2109 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2110 die("svn-remote.$remote: remote ref '$remote_ref' "
2111 . "must start with 'refs/'\n")
2112 unless $remote_ref =~ m{^refs/};
2113 $local_ref = uri_decode($local_ref);
2114 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2115 $r->{$remote}->{svm} = {} if $use_svm_props;
2116 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2117 $r->{$1}->{svm} = {};
2118 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2119 $r->{$1}->{url} = $2;
2120 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2121 $r->{$1}->{pushurl} = $2;
2122 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2123 my ($remote, $t, $local_ref, $remote_ref) =
2124 ($1, $2, $3, $4);
2125 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2126 . "must start with 'refs/'\n")
2127 unless $remote_ref =~ m{^refs/};
2128 $local_ref = uri_decode($local_ref);
2129 my $rs = {
2130 t => $t,
2131 remote => $remote,
2132 path => Git::SVN::GlobSpec->new($local_ref, 1),
2133 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2134 if (length($rs->{ref}->{right}) != 0) {
2135 die "The '*' glob character must be the last ",
2136 "character of '$remote_ref'\n";
2138 push @{ $r->{$remote}->{$t} }, $rs;
2142 map {
2143 if (defined $r->{$_}->{svm}) {
2144 my $svm;
2145 eval {
2146 my $section = "svn-remote.$_";
2147 $svm = {
2148 source => tmp_config('--get',
2149 "$section.svm-source"),
2150 replace => tmp_config('--get',
2151 "$section.svm-replace"),
2154 $r->{$_}->{svm} = $svm;
2156 } keys %$r;
2161 sub init_vars {
2162 $_gc_nr = $_gc_period = 1000;
2163 if (defined $_repack || defined $_repack_flags) {
2164 warn "Repack options are obsolete; they have no effect.\n";
2168 sub verify_remotes_sanity {
2169 return unless -d $ENV{GIT_DIR};
2170 my %seen;
2171 foreach (command(qw/config -l/)) {
2172 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2173 if ($seen{$1}) {
2174 die "Remote ref refs/remote/$1 is tracked by",
2175 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2176 "Please resolve this ambiguity in ",
2177 "your git configuration file before ",
2178 "continuing\n";
2180 $seen{$1} = $_;
2185 sub find_existing_remote {
2186 my ($url, $remotes) = @_;
2187 return undef if $no_reuse_existing;
2188 my $existing;
2189 foreach my $repo_id (keys %$remotes) {
2190 my $u = $remotes->{$repo_id}->{url} or next;
2191 next if $u ne $url;
2192 $existing = $repo_id;
2193 last;
2195 $existing;
2198 sub init_remote_config {
2199 my ($self, $url, $no_write) = @_;
2200 $url =~ s!/+$!!; # strip trailing slash
2201 my $r = read_all_remotes();
2202 my $existing = find_existing_remote($url, $r);
2203 if ($existing) {
2204 unless ($no_write) {
2205 print STDERR "Using existing ",
2206 "[svn-remote \"$existing\"]\n";
2208 $self->{repo_id} = $existing;
2209 } elsif ($_minimize_url) {
2210 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2211 $existing = find_existing_remote($min_url, $r);
2212 if ($existing) {
2213 unless ($no_write) {
2214 print STDERR "Using existing ",
2215 "[svn-remote \"$existing\"]\n";
2217 $self->{repo_id} = $existing;
2219 if ($min_url ne $url) {
2220 unless ($no_write) {
2221 print STDERR "Using higher level of URL: ",
2222 "$url => $min_url\n";
2224 my $old_path = $self->{path};
2225 $self->{path} = $url;
2226 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2227 if (length $old_path) {
2228 $self->{path} .= "/$old_path";
2230 $url = $min_url;
2233 my $orig_url;
2234 if (!$existing) {
2235 # verify that we aren't overwriting anything:
2236 $orig_url = eval {
2237 command_oneline('config', '--get',
2238 "svn-remote.$self->{repo_id}.url")
2240 if ($orig_url && ($orig_url ne $url)) {
2241 die "svn-remote.$self->{repo_id}.url already set: ",
2242 "$orig_url\nwanted to set to: $url\n";
2245 my ($xrepo_id, $xpath) = find_ref($self->refname);
2246 if (!$no_write && defined $xpath) {
2247 die "svn-remote.$xrepo_id.fetch already set to track ",
2248 "$xpath:", $self->refname, "\n";
2250 unless ($no_write) {
2251 command_noisy('config',
2252 "svn-remote.$self->{repo_id}.url", $url);
2253 $self->{path} =~ s{^/}{};
2254 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2255 command_noisy('config', '--add',
2256 "svn-remote.$self->{repo_id}.fetch",
2257 "$self->{path}:".$self->refname);
2259 $self->{url} = $url;
2262 sub find_by_url { # repos_root and, path are optional
2263 my ($class, $full_url, $repos_root, $path) = @_;
2265 return undef unless defined $full_url;
2266 remove_username($full_url);
2267 remove_username($repos_root) if defined $repos_root;
2268 my $remotes = read_all_remotes();
2269 if (defined $full_url && defined $repos_root && !defined $path) {
2270 $path = $full_url;
2271 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2273 foreach my $repo_id (keys %$remotes) {
2274 my $u = $remotes->{$repo_id}->{url} or next;
2275 remove_username($u);
2276 next if defined $repos_root && $repos_root ne $u;
2278 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2279 foreach my $t (qw/branches tags/) {
2280 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2281 resolve_local_globs($u, $fetch, $globspec);
2284 my $p = $path;
2285 my $rwr = rewrite_root({repo_id => $repo_id});
2286 my $svm = $remotes->{$repo_id}->{svm}
2287 if defined $remotes->{$repo_id}->{svm};
2288 unless (defined $p) {
2289 $p = $full_url;
2290 my $z = $u;
2291 my $prefix = '';
2292 if ($rwr) {
2293 $z = $rwr;
2294 remove_username($z);
2295 } elsif (defined $svm) {
2296 $z = $svm->{source};
2297 $prefix = $svm->{replace};
2298 $prefix =~ s#^\Q$u\E(?:/|$)##;
2299 $prefix =~ s#/$##;
2301 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2303 foreach my $f (keys %$fetch) {
2304 next if $f ne $p;
2305 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2308 undef;
2311 sub init {
2312 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2313 my $self = _new($class, $repo_id, $ref_id, $path);
2314 if (defined $url) {
2315 $self->init_remote_config($url, $no_write);
2317 $self;
2320 sub find_ref {
2321 my ($ref_id) = @_;
2322 foreach (command(qw/config -l/)) {
2323 next unless m!^svn-remote\.(.+)\.fetch=
2324 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2325 my ($repo_id, $path, $ref) = ($1, $2, $3);
2326 if ($ref eq $ref_id) {
2327 $path = '' if ($path =~ m#^\./?#);
2328 return ($repo_id, $path);
2331 (undef, undef, undef);
2334 sub new {
2335 my ($class, $ref_id, $repo_id, $path) = @_;
2336 if (defined $ref_id && !defined $repo_id && !defined $path) {
2337 ($repo_id, $path) = find_ref($ref_id);
2338 if (!defined $repo_id) {
2339 die "Could not find a \"svn-remote.*.fetch\" key ",
2340 "in the repository configuration matching: ",
2341 "$ref_id\n";
2344 my $self = _new($class, $repo_id, $ref_id, $path);
2345 if (!defined $self->{path} || !length $self->{path}) {
2346 my $fetch = command_oneline('config', '--get',
2347 "svn-remote.$repo_id.fetch",
2348 ":$ref_id\$") or
2349 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2350 "\":$ref_id\$\" in config\n";
2351 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2353 $self->{path} =~ s{/+}{/}g;
2354 $self->{path} =~ s{\A/}{};
2355 $self->{path} =~ s{/\z}{};
2356 $self->{url} = command_oneline('config', '--get',
2357 "svn-remote.$repo_id.url") or
2358 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2359 $self->{pushurl} = eval { command_oneline('config', '--get',
2360 "svn-remote.$repo_id.pushurl") };
2361 $self->rebuild;
2362 $self;
2365 sub refname {
2366 my ($refname) = $_[0]->{ref_id} ;
2368 # It cannot end with a slash /, we'll throw up on this because
2369 # SVN can't have directories with a slash in their name, either:
2370 if ($refname =~ m{/$}) {
2371 die "ref: '$refname' ends with a trailing slash, this is ",
2372 "not permitted by git nor Subversion\n";
2375 # It cannot have ASCII control character space, tilde ~, caret ^,
2376 # colon :, question-mark ?, asterisk *, space, or open bracket [
2377 # anywhere.
2379 # Additionally, % must be escaped because it is used for escaping
2380 # and we want our escaped refname to be reversible
2381 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2383 # no slash-separated component can begin with a dot .
2384 # /.* becomes /%2E*
2385 $refname =~ s{/\.}{/%2E}g;
2387 # It cannot have two consecutive dots .. anywhere
2388 # .. becomes %2E%2E
2389 $refname =~ s{\.\.}{%2E%2E}g;
2391 # trailing dots and .lock are not allowed
2392 # .$ becomes %2E and .lock becomes %2Elock
2393 $refname =~ s{\.(?=$|lock$)}{%2E};
2395 # the sequence @{ is used to access the reflog
2396 # @{ becomes %40{
2397 $refname =~ s{\@\{}{%40\{}g;
2399 return $refname;
2402 sub desanitize_refname {
2403 my ($refname) = @_;
2404 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2405 return $refname;
2408 sub svm_uuid {
2409 my ($self) = @_;
2410 return $self->{svm}->{uuid} if $self->svm;
2411 $self->ra;
2412 unless ($self->{svm}) {
2413 die "SVM UUID not cached, and reading remotely failed\n";
2415 $self->{svm}->{uuid};
2418 sub svm {
2419 my ($self) = @_;
2420 return $self->{svm} if $self->{svm};
2421 my $svm;
2422 # see if we have it in our config, first:
2423 eval {
2424 my $section = "svn-remote.$self->{repo_id}";
2425 $svm = {
2426 source => tmp_config('--get', "$section.svm-source"),
2427 uuid => tmp_config('--get', "$section.svm-uuid"),
2428 replace => tmp_config('--get', "$section.svm-replace"),
2431 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2432 $self->{svm} = $svm;
2434 $self->{svm};
2437 sub _set_svm_vars {
2438 my ($self, $ra) = @_;
2439 return $ra if $self->svm;
2441 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2442 "(svm:source, svm:uuid) ",
2443 "from the following URLs:\n" );
2444 sub read_svm_props {
2445 my ($self, $ra, $path, $r) = @_;
2446 my $props = ($ra->get_dir($path, $r))[2];
2447 my $src = $props->{'svm:source'};
2448 my $uuid = $props->{'svm:uuid'};
2449 return undef if (!$src || !$uuid);
2451 chomp($src, $uuid);
2453 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2454 or die "doesn't look right - svm:uuid is '$uuid'\n";
2456 # the '!' is used to mark the repos_root!/relative/path
2457 $src =~ s{/?!/?}{/};
2458 $src =~ s{/+$}{}; # no trailing slashes please
2459 # username is of no interest
2460 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2462 my $replace = $ra->{url};
2463 $replace .= "/$path" if length $path;
2465 my $section = "svn-remote.$self->{repo_id}";
2466 tmp_config("$section.svm-source", $src);
2467 tmp_config("$section.svm-replace", $replace);
2468 tmp_config("$section.svm-uuid", $uuid);
2469 $self->{svm} = {
2470 source => $src,
2471 uuid => $uuid,
2472 replace => $replace
2476 my $r = $ra->get_latest_revnum;
2477 my $path = $self->{path};
2478 my %tried;
2479 while (length $path) {
2480 unless ($tried{"$self->{url}/$path"}) {
2481 return $ra if $self->read_svm_props($ra, $path, $r);
2482 $tried{"$self->{url}/$path"} = 1;
2484 $path =~ s#/?[^/]+$##;
2486 die "Path: '$path' should be ''\n" if $path ne '';
2487 return $ra if $self->read_svm_props($ra, $path, $r);
2488 $tried{"$self->{url}/$path"} = 1;
2490 if ($ra->{repos_root} eq $self->{url}) {
2491 die @err, (map { " $_\n" } keys %tried), "\n";
2494 # nope, make sure we're connected to the repository root:
2495 my $ok;
2496 my @tried_b;
2497 $path = $ra->{svn_path};
2498 $ra = Git::SVN::Ra->new($ra->{repos_root});
2499 while (length $path) {
2500 unless ($tried{"$ra->{url}/$path"}) {
2501 $ok = $self->read_svm_props($ra, $path, $r);
2502 last if $ok;
2503 $tried{"$ra->{url}/$path"} = 1;
2505 $path =~ s#/?[^/]+$##;
2507 die "Path: '$path' should be ''\n" if $path ne '';
2508 $ok ||= $self->read_svm_props($ra, $path, $r);
2509 $tried{"$ra->{url}/$path"} = 1;
2510 if (!$ok) {
2511 die @err, (map { " $_\n" } keys %tried), "\n";
2513 Git::SVN::Ra->new($self->{url});
2516 sub svnsync {
2517 my ($self) = @_;
2518 return $self->{svnsync} if $self->{svnsync};
2520 if ($self->no_metadata) {
2521 die "Can't have both 'noMetadata' and ",
2522 "'useSvnsyncProps' options set!\n";
2524 if ($self->rewrite_root) {
2525 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2526 "options set!\n";
2528 if ($self->rewrite_uuid) {
2529 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2530 "options set!\n";
2533 my $svnsync;
2534 # see if we have it in our config, first:
2535 eval {
2536 my $section = "svn-remote.$self->{repo_id}";
2538 my $url = tmp_config('--get', "$section.svnsync-url");
2539 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2540 die "doesn't look right - svn:sync-from-url is '$url'\n";
2542 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2543 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2544 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2546 $svnsync = { url => $url, uuid => $uuid }
2548 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2549 return $self->{svnsync} = $svnsync;
2552 my $err = "useSvnsyncProps set, but failed to read " .
2553 "svnsync property: svn:sync-from-";
2554 my $rp = $self->ra->rev_proplist(0);
2556 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2557 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2558 die "doesn't look right - svn:sync-from-url is '$url'\n";
2560 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2561 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2562 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2564 my $section = "svn-remote.$self->{repo_id}";
2565 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2566 tmp_config('--add', "$section.svnsync-url", $url);
2567 return $self->{svnsync} = { url => $url, uuid => $uuid };
2570 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2571 # remote lookup (useful for 'git svn log').
2572 sub ra_uuid {
2573 my ($self) = @_;
2574 unless ($self->{ra_uuid}) {
2575 my $key = "svn-remote.$self->{repo_id}.uuid";
2576 my $uuid = eval { tmp_config('--get', $key) };
2577 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2578 $self->{ra_uuid} = $uuid;
2579 } else {
2580 die "ra_uuid called without URL\n" unless $self->{url};
2581 $self->{ra_uuid} = $self->ra->get_uuid;
2582 tmp_config('--add', $key, $self->{ra_uuid});
2585 $self->{ra_uuid};
2588 sub _set_repos_root {
2589 my ($self, $repos_root) = @_;
2590 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2591 $repos_root ||= $self->ra->{repos_root};
2592 tmp_config($k, $repos_root);
2593 $repos_root;
2596 sub repos_root {
2597 my ($self) = @_;
2598 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2599 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2602 sub ra {
2603 my ($self) = shift;
2604 my $ra = Git::SVN::Ra->new($self->{url});
2605 $self->_set_repos_root($ra->{repos_root});
2606 if ($self->use_svm_props && !$self->{svm}) {
2607 if ($self->no_metadata) {
2608 die "Can't have both 'noMetadata' and ",
2609 "'useSvmProps' options set!\n";
2610 } elsif ($self->use_svnsync_props) {
2611 die "Can't have both 'useSvnsyncProps' and ",
2612 "'useSvmProps' options set!\n";
2614 $ra = $self->_set_svm_vars($ra);
2615 $self->{-want_revprops} = 1;
2617 $ra;
2620 # prop_walk(PATH, REV, SUB)
2621 # -------------------------
2622 # Recursively traverse PATH at revision REV and invoke SUB for each
2623 # directory that contains a SVN property. SUB will be invoked as
2624 # follows: &SUB(gs, path, props); where `gs' is this instance of
2625 # Git::SVN, `path' the path to the directory where the properties
2626 # `props' were found. The `path' will be relative to point of checkout,
2627 # that is, if url://repo/trunk is the current Git branch, and that
2628 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2629 # as `path' (note the trailing `/').
2630 sub prop_walk {
2631 my ($self, $path, $rev, $sub) = @_;
2633 $path =~ s#^/##;
2634 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2635 $path =~ s#^/*#/#g;
2636 my $p = $path;
2637 # Strip the irrelevant part of the path.
2638 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2639 # Ensure the path is terminated by a `/'.
2640 $p =~ s#/*$#/#;
2642 # The properties contain all the internal SVN stuff nobody
2643 # (usually) cares about.
2644 my $interesting_props = 0;
2645 foreach (keys %{$props}) {
2646 # If it doesn't start with `svn:', it must be a
2647 # user-defined property.
2648 ++$interesting_props and next if $_ !~ /^svn:/;
2649 # FIXME: Fragile, if SVN adds new public properties,
2650 # this needs to be updated.
2651 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2652 |eol-style|mime-type
2653 |externals|needs-lock)$/x;
2655 &$sub($self, $p, $props) if $interesting_props;
2657 foreach (sort keys %$dirent) {
2658 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2659 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2663 sub last_rev { ($_[0]->last_rev_commit)[0] }
2664 sub last_commit { ($_[0]->last_rev_commit)[1] }
2666 # returns the newest SVN revision number and newest commit SHA1
2667 sub last_rev_commit {
2668 my ($self) = @_;
2669 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2670 return ($self->{last_rev}, $self->{last_commit});
2672 my $c = ::verify_ref($self->refname.'^0');
2673 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2674 my $rev = (::cmt_metadata($c))[1];
2675 if (defined $rev) {
2676 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2677 return ($rev, $c);
2680 my $map_path = $self->map_path;
2681 unless (-e $map_path) {
2682 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2683 return (undef, undef);
2685 my ($rev, $commit) = $self->rev_map_max(1);
2686 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2687 return ($rev, $commit);
2690 sub get_fetch_range {
2691 my ($self, $min, $max) = @_;
2692 $max ||= $self->ra->get_latest_revnum;
2693 $min ||= $self->rev_map_max;
2694 (++$min, $max);
2697 sub tmp_config {
2698 my (@args) = @_;
2699 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2700 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2701 if (! -f $config && -f $old_def_config) {
2702 rename $old_def_config, $config or
2703 die "Failed rename $old_def_config => $config: $!\n";
2705 my $old_config = $ENV{GIT_CONFIG};
2706 $ENV{GIT_CONFIG} = $config;
2707 $@ = undef;
2708 my @ret = eval {
2709 unless (-f $config) {
2710 mkfile($config);
2711 open my $fh, '>', $config or
2712 die "Can't open $config: $!\n";
2713 print $fh "; This file is used internally by ",
2714 "git-svn\n" or die
2715 "Couldn't write to $config: $!\n";
2716 print $fh "; You should not have to edit it\n" or
2717 die "Couldn't write to $config: $!\n";
2718 close $fh or die "Couldn't close $config: $!\n";
2720 command('config', @args);
2722 my $err = $@;
2723 if (defined $old_config) {
2724 $ENV{GIT_CONFIG} = $old_config;
2725 } else {
2726 delete $ENV{GIT_CONFIG};
2728 die $err if $err;
2729 wantarray ? @ret : $ret[0];
2732 sub tmp_index_do {
2733 my ($self, $sub) = @_;
2734 my $old_index = $ENV{GIT_INDEX_FILE};
2735 $ENV{GIT_INDEX_FILE} = $self->{index};
2736 $@ = undef;
2737 my @ret = eval {
2738 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2739 mkpath([$dir]) unless -d $dir;
2740 &$sub;
2742 my $err = $@;
2743 if (defined $old_index) {
2744 $ENV{GIT_INDEX_FILE} = $old_index;
2745 } else {
2746 delete $ENV{GIT_INDEX_FILE};
2748 die $err if $err;
2749 wantarray ? @ret : $ret[0];
2752 sub assert_index_clean {
2753 my ($self, $treeish) = @_;
2755 $self->tmp_index_do(sub {
2756 command_noisy('read-tree', $treeish) unless -e $self->{index};
2757 my $x = command_oneline('write-tree');
2758 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2759 /^tree ($::sha1)/mo);
2760 return if $y eq $x;
2762 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2763 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2764 command_noisy('read-tree', $treeish);
2765 $x = command_oneline('write-tree');
2766 if ($y ne $x) {
2767 ::fatal "trees ($treeish) $y != $x\n",
2768 "Something is seriously wrong...";
2773 sub get_commit_parents {
2774 my ($self, $log_entry) = @_;
2775 my (%seen, @ret, @tmp);
2776 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2777 if (my $ip = $self->{inject_parents}) {
2778 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2779 push @tmp, $commit;
2782 if (my $cur = ::verify_ref($self->refname.'^0')) {
2783 push @tmp, $cur;
2785 if (my $ipd = $self->{inject_parents_dcommit}) {
2786 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2787 push @tmp, @$commit;
2790 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2791 while (my $p = shift @tmp) {
2792 next if $seen{$p};
2793 $seen{$p} = 1;
2794 push @ret, $p;
2796 @ret;
2799 sub rewrite_root {
2800 my ($self) = @_;
2801 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2802 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2803 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2804 if ($rwr) {
2805 $rwr =~ s#/+$##;
2806 if ($rwr !~ m#^[a-z\+]+://#) {
2807 die "$rwr is not a valid URL (key: $k)\n";
2810 $self->{-rewrite_root} = $rwr;
2813 sub rewrite_uuid {
2814 my ($self) = @_;
2815 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2816 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2817 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2818 if ($rwid) {
2819 $rwid =~ s#/+$##;
2820 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2821 die "$rwid is not a valid UUID (key: $k)\n";
2824 $self->{-rewrite_uuid} = $rwid;
2827 sub metadata_url {
2828 my ($self) = @_;
2829 ($self->rewrite_root || $self->{url}) .
2830 (length $self->{path} ? '/' . $self->{path} : '');
2833 sub full_url {
2834 my ($self) = @_;
2835 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2838 sub full_pushurl {
2839 my ($self) = @_;
2840 if ($self->{pushurl}) {
2841 return $self->{pushurl} . (length $self->{path} ? '/' .
2842 $self->{path} : '');
2843 } else {
2844 return $self->full_url;
2848 sub set_commit_header_env {
2849 my ($log_entry) = @_;
2850 my %env;
2851 foreach my $ned (qw/NAME EMAIL DATE/) {
2852 foreach my $ac (qw/AUTHOR COMMITTER/) {
2853 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2857 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2858 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2859 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2861 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2862 ? $log_entry->{commit_name}
2863 : $log_entry->{name};
2864 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2865 ? $log_entry->{commit_email}
2866 : $log_entry->{email};
2867 \%env;
2870 sub restore_commit_header_env {
2871 my ($env) = @_;
2872 foreach my $ned (qw/NAME EMAIL DATE/) {
2873 foreach my $ac (qw/AUTHOR COMMITTER/) {
2874 my $k = "GIT_${ac}_${ned}";
2875 if (defined $env->{$k}) {
2876 $ENV{$k} = $env->{$k};
2877 } else {
2878 delete $ENV{$k};
2884 sub gc {
2885 command_noisy('gc', '--auto');
2888 sub do_git_commit {
2889 my ($self, $log_entry) = @_;
2890 my $lr = $self->last_rev;
2891 if (defined $lr && $lr >= $log_entry->{revision}) {
2892 die "Last fetched revision of ", $self->refname,
2893 " was r$lr, but we are about to fetch: ",
2894 "r$log_entry->{revision}!\n";
2896 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2897 croak "$log_entry->{revision} = $c already exists! ",
2898 "Why are we refetching it?\n";
2900 my $old_env = set_commit_header_env($log_entry);
2901 my $tree = $log_entry->{tree};
2902 if (!defined $tree) {
2903 $tree = $self->tmp_index_do(sub {
2904 command_oneline('write-tree') });
2906 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2908 my @exec = ('git', 'commit-tree', $tree);
2909 foreach ($self->get_commit_parents($log_entry)) {
2910 push @exec, '-p', $_;
2912 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2913 or croak $!;
2914 binmode $msg_fh;
2916 # we always get UTF-8 from SVN, but we may want our commits in
2917 # a different encoding.
2918 if (my $enc = Git::config('i18n.commitencoding')) {
2919 require Encode;
2920 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2922 print $msg_fh $log_entry->{log} or croak $!;
2923 restore_commit_header_env($old_env);
2924 unless ($self->no_metadata) {
2925 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2926 or croak $!;
2928 $msg_fh->flush == 0 or croak $!;
2929 close $msg_fh or croak $!;
2930 chomp(my $commit = do { local $/; <$out_fh> });
2931 close $out_fh or croak $!;
2932 waitpid $pid, 0;
2933 croak $? if $?;
2934 if ($commit !~ /^$::sha1$/o) {
2935 die "Failed to commit, invalid sha1: $commit\n";
2938 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2940 $self->{last_rev} = $log_entry->{revision};
2941 $self->{last_commit} = $commit;
2942 print "r$log_entry->{revision}" unless $::_q > 1;
2943 if (defined $log_entry->{svm_revision}) {
2944 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2945 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2946 0, $self->svm_uuid);
2948 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2949 if (--$_gc_nr == 0) {
2950 $_gc_nr = $_gc_period;
2951 gc();
2953 return $commit;
2956 sub match_paths {
2957 my ($self, $paths, $r) = @_;
2958 return 1 if $self->{path} eq '';
2959 if (my $path = $paths->{"/$self->{path}"}) {
2960 return ($path->{action} eq 'D') ? 0 : 1;
2962 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2963 if (grep /$self->{path_regex}/, keys %$paths) {
2964 return 1;
2966 my $c = '';
2967 foreach (split m#/#, $self->{path}) {
2968 $c .= "/$_";
2969 next unless ($paths->{$c} &&
2970 ($paths->{$c}->{action} =~ /^[AR]$/));
2971 if ($self->ra->check_path($self->{path}, $r) ==
2972 $SVN::Node::dir) {
2973 return 1;
2976 return 0;
2979 sub find_parent_branch {
2980 my ($self, $paths, $rev) = @_;
2981 return undef unless $self->follow_parent;
2982 unless (defined $paths) {
2983 my $err_handler = $SVN::Error::handler;
2984 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2985 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2986 sub { $paths = $_[0] });
2987 $SVN::Error::handler = $err_handler;
2989 return undef unless defined $paths;
2991 # look for a parent from another branch:
2992 my @b_path_components = split m#/#, $self->{path};
2993 my @a_path_components;
2994 my $i;
2995 while (@b_path_components) {
2996 $i = $paths->{'/'.join('/', @b_path_components)};
2997 last if $i && defined $i->{copyfrom_path};
2998 unshift(@a_path_components, pop(@b_path_components));
3000 return undef unless defined $i && defined $i->{copyfrom_path};
3001 my $branch_from = $i->{copyfrom_path};
3002 if (@a_path_components) {
3003 print STDERR "branch_from: $branch_from => ";
3004 $branch_from .= '/'.join('/', @a_path_components);
3005 print STDERR $branch_from, "\n";
3007 my $r = $i->{copyfrom_rev};
3008 my $repos_root = $self->ra->{repos_root};
3009 my $url = $self->ra->{url};
3010 my $new_url = $url . $branch_from;
3011 print STDERR "Found possible branch point: ",
3012 "$new_url => ", $self->full_url, ", $r\n"
3013 unless $::_q > 1;
3014 $branch_from =~ s#^/##;
3015 my $gs = $self->other_gs($new_url, $url,
3016 $branch_from, $r, $self->{ref_id});
3017 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3019 my ($base, $head);
3020 if (!defined $r0 || !defined $parent) {
3021 ($base, $head) = parse_revision_argument(0, $r);
3022 } else {
3023 if ($r0 < $r) {
3024 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3025 0, 1, sub { $base = $_[1] - 1 });
3028 if (defined $base && $base <= $r) {
3029 $gs->fetch($base, $r);
3031 ($r0, $parent) = $gs->find_rev_before($r, 1);
3033 if (defined $r0 && defined $parent) {
3034 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3035 unless $::_q > 1;
3036 my $ed;
3037 if ($self->ra->can_do_switch) {
3038 $self->assert_index_clean($parent);
3039 print STDERR "Following parent with do_switch\n"
3040 unless $::_q > 1;
3041 # do_switch works with svn/trunk >= r22312, but that
3042 # is not included with SVN 1.4.3 (the latest version
3043 # at the moment), so we can't rely on it
3044 $self->{last_rev} = $r0;
3045 $self->{last_commit} = $parent;
3046 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3047 $gs->ra->gs_do_switch($r0, $rev, $gs,
3048 $self->full_url, $ed)
3049 or die "SVN connection failed somewhere...\n";
3050 } elsif ($self->ra->trees_match($new_url, $r0,
3051 $self->full_url, $rev)) {
3052 print STDERR "Trees match:\n",
3053 " $new_url\@$r0\n",
3054 " ${\$self->full_url}\@$rev\n",
3055 "Following parent with no changes\n"
3056 unless $::_q > 1;
3057 $self->tmp_index_do(sub {
3058 command_noisy('read-tree', $parent);
3060 $self->{last_commit} = $parent;
3061 } else {
3062 print STDERR "Following parent with do_update\n"
3063 unless $::_q > 1;
3064 $ed = SVN::Git::Fetcher->new($self);
3065 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3066 or die "SVN connection failed somewhere...\n";
3068 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3069 return $self->make_log_entry($rev, [$parent], $ed);
3071 return undef;
3074 sub do_fetch {
3075 my ($self, $paths, $rev) = @_;
3076 my $ed;
3077 my ($last_rev, @parents);
3078 if (my $lc = $self->last_commit) {
3079 # we can have a branch that was deleted, then re-added
3080 # under the same name but copied from another path, in
3081 # which case we'll have multiple parents (we don't
3082 # want to break the original ref, nor lose copypath info):
3083 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3084 push @{$log_entry->{parents}}, $lc;
3085 return $log_entry;
3087 $ed = SVN::Git::Fetcher->new($self);
3088 $last_rev = $self->{last_rev};
3089 $ed->{c} = $lc;
3090 @parents = ($lc);
3091 } else {
3092 $last_rev = $rev;
3093 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3094 return $log_entry;
3096 $ed = SVN::Git::Fetcher->new($self);
3098 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3099 die "SVN connection failed somewhere...\n";
3101 $self->make_log_entry($rev, \@parents, $ed);
3104 sub mkemptydirs {
3105 my ($self, $r) = @_;
3107 sub scan {
3108 my ($r, $empty_dirs, $line) = @_;
3109 if (defined $r && $line =~ /^r(\d+)$/) {
3110 return 0 if $1 > $r;
3111 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3112 $empty_dirs->{$1} = 1;
3113 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3114 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3115 delete @$empty_dirs{@d};
3117 1; # continue
3120 my %empty_dirs = ();
3121 my $gz_file = "$self->{dir}/unhandled.log.gz";
3122 if (-f $gz_file) {
3123 if (!$can_compress) {
3124 warn "Compress::Zlib could not be found; ",
3125 "empty directories in $gz_file will not be read\n";
3126 } else {
3127 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3128 die "Unable to open $gz_file: $!\n";
3129 my $line;
3130 while ($gz->gzreadline($line) > 0) {
3131 scan($r, \%empty_dirs, $line) or last;
3133 $gz->gzclose;
3137 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3138 binmode $fh or croak "binmode: $!";
3139 while (<$fh>) {
3140 scan($r, \%empty_dirs, $_) or last;
3142 close $fh;
3145 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3146 foreach my $d (sort keys %empty_dirs) {
3147 $d = uri_decode($d);
3148 $d =~ s/$strip//;
3149 next unless length($d);
3150 next if -d $d;
3151 if (-e $d) {
3152 warn "$d exists but is not a directory\n";
3153 } else {
3154 print "creating empty directory: $d\n";
3155 mkpath([$d]);
3160 sub get_untracked {
3161 my ($self, $ed) = @_;
3162 my @out;
3163 my $h = $ed->{empty};
3164 foreach (sort keys %$h) {
3165 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3166 push @out, " $act: " . uri_encode($_);
3167 warn "W: $act: $_\n";
3169 foreach my $t (qw/dir_prop file_prop/) {
3170 $h = $ed->{$t} or next;
3171 foreach my $path (sort keys %$h) {
3172 my $ppath = $path eq '' ? '.' : $path;
3173 foreach my $prop (sort keys %{$h->{$path}}) {
3174 next if $SKIP_PROP{$prop};
3175 my $v = $h->{$path}->{$prop};
3176 my $t_ppath_prop = "$t: " .
3177 uri_encode($ppath) . ' ' .
3178 uri_encode($prop);
3179 if (defined $v) {
3180 push @out, " +$t_ppath_prop " .
3181 uri_encode($v);
3182 } else {
3183 push @out, " -$t_ppath_prop";
3188 foreach my $t (qw/absent_file absent_directory/) {
3189 $h = $ed->{$t} or next;
3190 foreach my $parent (sort keys %$h) {
3191 foreach my $path (sort @{$h->{$parent}}) {
3192 push @out, " $t: " .
3193 uri_encode("$parent/$path");
3194 warn "W: $t: $parent/$path ",
3195 "Insufficient permissions?\n";
3199 \@out;
3202 # parse_svn_date(DATE)
3203 # --------------------
3204 # Given a date (in UTC) from Subversion, return a string in the format
3205 # "<TZ Offset> <local date/time>" that Git will use.
3207 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3208 # is true we'll convert it to the local timezone instead.
3209 sub parse_svn_date {
3210 my $date = shift || return '+0000 1970-01-01 00:00:00';
3211 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3212 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3213 croak "Unable to parse date: $date\n";
3214 my $parsed_date; # Set next.
3216 if ($Git::SVN::_localtime) {
3217 # Translate the Subversion datetime to an epoch time.
3218 # Begin by switching ourselves to $date's timezone, UTC.
3219 my $old_env_TZ = $ENV{TZ};
3220 $ENV{TZ} = 'UTC';
3222 my $epoch_in_UTC =
3223 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3225 # Determine our local timezone (including DST) at the
3226 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3227 # value of TZ, if any, at the time we were run.
3228 if (defined $Git::SVN::Log::TZ) {
3229 $ENV{TZ} = $Git::SVN::Log::TZ;
3230 } else {
3231 delete $ENV{TZ};
3234 my $our_TZ =
3235 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
3237 # This converts $epoch_in_UTC into our local timezone.
3238 my ($sec, $min, $hour, $mday, $mon, $year,
3239 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3241 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3242 $our_TZ, $year + 1900, $mon + 1,
3243 $mday, $hour, $min, $sec);
3245 # Reset us to the timezone in effect when we entered
3246 # this routine.
3247 if (defined $old_env_TZ) {
3248 $ENV{TZ} = $old_env_TZ;
3249 } else {
3250 delete $ENV{TZ};
3252 } else {
3253 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3256 return $parsed_date;
3259 sub other_gs {
3260 my ($self, $new_url, $url,
3261 $branch_from, $r, $old_ref_id) = @_;
3262 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3263 unless ($gs) {
3264 my $ref_id = $old_ref_id;
3265 $ref_id =~ s/\@\d+-*$//;
3266 $ref_id .= "\@$r";
3267 # just grow a tail if we're not unique enough :x
3268 $ref_id .= '-' while find_ref($ref_id);
3269 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3270 if ($u =~ s#^\Q$url\E(/|$)##) {
3271 $p = $u;
3272 $u = $url;
3273 $repo_id = $self->{repo_id};
3275 while (1) {
3276 # It is possible to tag two different subdirectories at
3277 # the same revision. If the url for an existing ref
3278 # does not match, we must either find a ref with a
3279 # matching url or create a new ref by growing a tail.
3280 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3281 my (undef, $max_commit) = $gs->rev_map_max(1);
3282 last if (!$max_commit);
3283 my ($url) = ::cmt_metadata($max_commit);
3284 last if ($url eq $gs->metadata_url);
3285 $ref_id .= '-';
3287 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3292 sub call_authors_prog {
3293 my ($orig_author) = @_;
3294 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3295 my $author = `$::_authors_prog $orig_author`;
3296 if ($? != 0) {
3297 die "$::_authors_prog failed with exit code $?\n"
3299 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3300 my ($name, $email) = ($1, $2);
3301 $email = undef if length $2 == 0;
3302 return [$name, $email];
3303 } else {
3304 die "Author: $orig_author: $::_authors_prog returned "
3305 . "invalid author format: $author\n";
3309 sub check_author {
3310 my ($author) = @_;
3311 if (!defined $author || length $author == 0) {
3312 $author = '(no author)';
3314 if (!defined $::users{$author}) {
3315 if (defined $::_authors_prog) {
3316 $::users{$author} = call_authors_prog($author);
3317 } elsif (defined $::_authors) {
3318 die "Author: $author not defined in $::_authors file\n";
3321 $author;
3324 sub find_extra_svk_parents {
3325 my ($self, $ed, $tickets, $parents) = @_;
3326 # aha! svk:merge property changed...
3327 my @tickets = split "\n", $tickets;
3328 my @known_parents;
3329 for my $ticket ( @tickets ) {
3330 my ($uuid, $path, $rev) = split /:/, $ticket;
3331 if ( $uuid eq $self->ra_uuid ) {
3332 my $url = $self->{url};
3333 my $repos_root = $url;
3334 my $branch_from = $path;
3335 $branch_from =~ s{^/}{};
3336 my $gs = $self->other_gs($repos_root."/".$branch_from,
3337 $url,
3338 $branch_from,
3339 $rev,
3340 $self->{ref_id});
3341 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3342 # wahey! we found it, but it might be
3343 # an old one (!)
3344 push @known_parents, [ $rev, $commit ];
3348 # Ordering matters; highest-numbered commit merge tickets
3349 # first, as they may account for later merge ticket additions
3350 # or changes.
3351 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3352 for my $parent ( @known_parents ) {
3353 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3354 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3355 my $new;
3356 while ( <$msg_fh> ) {
3357 $new=1;last;
3359 command_close_pipe($msg_fh, $ctx);
3360 if ( $new ) {
3361 print STDERR
3362 "Found merge parent (svk:merge ticket): $parent\n";
3363 push @$parents, $parent;
3368 sub lookup_svn_merge {
3369 my $uuid = shift;
3370 my $url = shift;
3371 my $merge = shift;
3373 my ($source, $revs) = split ":", $merge;
3374 my $path = $source;
3375 $path =~ s{^/}{};
3376 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3377 if ( !$gs ) {
3378 warn "Couldn't find revmap for $url$source\n";
3379 return;
3381 my @ranges = split ",", $revs;
3382 my ($tip, $tip_commit);
3383 my @merged_commit_ranges;
3384 # find the tip
3385 for my $range ( @ranges ) {
3386 my ($bottom, $top) = split "-", $range;
3387 $top ||= $bottom;
3388 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3389 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3391 unless ($top_commit and $bottom_commit) {
3392 warn "W:unknown path/rev in svn:mergeinfo "
3393 ."dirprop: $source:$range\n";
3394 next;
3397 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3398 push @merged_commit_ranges,
3399 "$bottom_commit^..$top_commit";
3400 } else {
3401 push @merged_commit_ranges, "$top_commit";
3404 if ( !defined $tip or $top > $tip ) {
3405 $tip = $top;
3406 $tip_commit = $top_commit;
3409 return ($tip_commit, @merged_commit_ranges);
3412 sub _rev_list {
3413 my ($msg_fh, $ctx) = command_output_pipe(
3414 "rev-list", @_,
3416 my @rv;
3417 while ( <$msg_fh> ) {
3418 chomp;
3419 push @rv, $_;
3421 command_close_pipe($msg_fh, $ctx);
3422 @rv;
3425 sub check_cherry_pick {
3426 my $base = shift;
3427 my $tip = shift;
3428 my $parents = shift;
3429 my @ranges = @_;
3430 my %commits = map { $_ => 1 }
3431 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3432 for my $range ( @ranges ) {
3433 delete @commits{_rev_list($range, "--")};
3435 for my $commit (keys %commits) {
3436 if (has_no_changes($commit)) {
3437 delete $commits{$commit};
3440 return (keys %commits);
3443 sub has_no_changes {
3444 my $commit = shift;
3446 my @revs = split / /, command_oneline(
3447 qw(rev-list --parents -1 -m), $commit);
3449 # Commits with no parents, e.g. the start of a partial branch,
3450 # have changes by definition.
3451 return 1 if (@revs < 2);
3453 # Commits with multiple parents, e.g a merge, have no changes
3454 # by definition.
3455 return 0 if (@revs > 2);
3457 return (command_oneline("rev-parse", "$commit^{tree}") eq
3458 command_oneline("rev-parse", "$commit~1^{tree}"));
3461 # The GIT_DIR environment variable is not always set until after the command
3462 # line arguments are processed, so we can't memoize in a BEGIN block.
3464 my $memoized = 0;
3466 sub memoize_svn_mergeinfo_functions {
3467 return if $memoized;
3468 $memoized = 1;
3470 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3471 mkpath([$cache_path]) unless -d $cache_path;
3473 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3474 "$cache_path/lookup_svn_merge.db", 'nstore';
3475 memoize 'lookup_svn_merge',
3476 SCALAR_CACHE => 'FAULT',
3477 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3480 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3481 "$cache_path/check_cherry_pick.db", 'nstore';
3482 memoize 'check_cherry_pick',
3483 SCALAR_CACHE => 'FAULT',
3484 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3487 tie my %has_no_changes_cache => 'Memoize::Storable',
3488 "$cache_path/has_no_changes.db", 'nstore';
3489 memoize 'has_no_changes',
3490 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3491 LIST_CACHE => 'FAULT',
3495 sub unmemoize_svn_mergeinfo_functions {
3496 return if not $memoized;
3497 $memoized = 0;
3499 Memoize::unmemoize 'lookup_svn_merge';
3500 Memoize::unmemoize 'check_cherry_pick';
3501 Memoize::unmemoize 'has_no_changes';
3504 Memoize::memoize 'Git::SVN::repos_root';
3507 END {
3508 # Force cache writeout explicitly instead of waiting for
3509 # global destruction to avoid segfault in Storable:
3510 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3511 unmemoize_svn_mergeinfo_functions();
3514 sub parents_exclude {
3515 my $parents = shift;
3516 my @commits = @_;
3517 return unless @commits;
3519 my @excluded;
3520 my $excluded;
3521 do {
3522 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3523 $excluded = command_oneline(@cmd);
3524 if ( $excluded ) {
3525 my @new;
3526 my $found;
3527 for my $commit ( @commits ) {
3528 if ( $commit eq $excluded ) {
3529 push @excluded, $commit;
3530 $found++;
3531 last;
3533 else {
3534 push @new, $commit;
3537 die "saw commit '$excluded' in rev-list output, "
3538 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3539 unless $found;
3540 @commits = @new;
3543 while ($excluded and @commits);
3545 return @excluded;
3549 # note: this function should only be called if the various dirprops
3550 # have actually changed
3551 sub find_extra_svn_parents {
3552 my ($self, $ed, $mergeinfo, $parents) = @_;
3553 # aha! svk:merge property changed...
3555 memoize_svn_mergeinfo_functions();
3557 # We first search for merged tips which are not in our
3558 # history. Then, we figure out which git revisions are in
3559 # that tip, but not this revision. If all of those revisions
3560 # are now marked as merge, we can add the tip as a parent.
3561 my @merges = split "\n", $mergeinfo;
3562 my @merge_tips;
3563 my $url = $self->{url};
3564 my $uuid = $self->ra_uuid;
3565 my %ranges;
3566 for my $merge ( @merges ) {
3567 my ($tip_commit, @ranges) =
3568 lookup_svn_merge( $uuid, $url, $merge );
3569 unless (!$tip_commit or
3570 grep { $_ eq $tip_commit } @$parents ) {
3571 push @merge_tips, $tip_commit;
3572 $ranges{$tip_commit} = \@ranges;
3573 } else {
3574 push @merge_tips, undef;
3578 my %excluded = map { $_ => 1 }
3579 parents_exclude($parents, grep { defined } @merge_tips);
3581 # check merge tips for new parents
3582 my @new_parents;
3583 for my $merge_tip ( @merge_tips ) {
3584 my $spec = shift @merges;
3585 next unless $merge_tip and $excluded{$merge_tip};
3587 my $ranges = $ranges{$merge_tip};
3589 # check out 'new' tips
3590 my $merge_base;
3591 eval {
3592 $merge_base = command_oneline(
3593 "merge-base",
3594 @$parents, $merge_tip,
3597 if ($@) {
3598 die "An error occurred during merge-base"
3599 unless $@->isa("Git::Error::Command");
3601 warn "W: Cannot find common ancestor between ".
3602 "@$parents and $merge_tip. Ignoring merge info.\n";
3603 next;
3606 # double check that there are no missing non-merge commits
3607 my (@incomplete) = check_cherry_pick(
3608 $merge_base, $merge_tip,
3609 $parents,
3610 @$ranges,
3613 if ( @incomplete ) {
3614 warn "W:svn cherry-pick ignored ($spec) - missing "
3615 .@incomplete." commit(s) (eg $incomplete[0])\n";
3616 } else {
3617 warn
3618 "Found merge parent (svn:mergeinfo prop): ",
3619 $merge_tip, "\n";
3620 push @new_parents, $merge_tip;
3624 # cater for merges which merge commits from multiple branches
3625 if ( @new_parents > 1 ) {
3626 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3627 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3628 next if $i == $j;
3629 next unless $new_parents[$i];
3630 next unless $new_parents[$j];
3631 my $revs = command_oneline(
3632 "rev-list", "-1",
3633 "$new_parents[$i]..$new_parents[$j]",
3635 if ( !$revs ) {
3636 undef($new_parents[$j]);
3641 push @$parents, grep { defined } @new_parents;
3644 sub make_log_entry {
3645 my ($self, $rev, $parents, $ed) = @_;
3646 my $untracked = $self->get_untracked($ed);
3648 my @parents = @$parents;
3649 my $ps = $ed->{path_strip} || "";
3650 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3651 my $props = $ed->{dir_prop}{$path};
3652 if ( $props->{"svk:merge"} ) {
3653 $self->find_extra_svk_parents
3654 ($ed, $props->{"svk:merge"}, \@parents);
3656 if ( $props->{"svn:mergeinfo"} ) {
3657 $self->find_extra_svn_parents
3658 ($ed,
3659 $props->{"svn:mergeinfo"},
3660 \@parents);
3664 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3665 print $un "r$rev\n" or croak $!;
3666 print $un $_, "\n" foreach @$untracked;
3667 my %log_entry = ( parents => \@parents, revision => $rev,
3668 log => '');
3670 my $headrev;
3671 my $logged = delete $self->{logged_rev_props};
3672 if (!$logged || $self->{-want_revprops}) {
3673 my $rp = $self->ra->rev_proplist($rev);
3674 foreach (sort keys %$rp) {
3675 my $v = $rp->{$_};
3676 if (/^svn:(author|date|log)$/) {
3677 $log_entry{$1} = $v;
3678 } elsif ($_ eq 'svm:headrev') {
3679 $headrev = $v;
3680 } else {
3681 print $un " rev_prop: ", uri_encode($_), ' ',
3682 uri_encode($v), "\n";
3685 } else {
3686 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3688 close $un or croak $!;
3690 $log_entry{date} = parse_svn_date($log_entry{date});
3691 $log_entry{log} .= "\n";
3692 my $author = $log_entry{author} = check_author($log_entry{author});
3693 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3694 : ($author, undef);
3696 my ($commit_name, $commit_email) = ($name, $email);
3697 if ($_use_log_author) {
3698 my $name_field;
3699 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3700 $name_field = $1;
3701 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3702 $name_field = $1;
3704 if (!defined $name_field) {
3705 if (!defined $email) {
3706 $email = $name;
3708 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3709 ($name, $email) = ($1, $2);
3710 } elsif ($name_field =~ /(.*)@/) {
3711 ($name, $email) = ($1, $name_field);
3712 } else {
3713 ($name, $email) = ($name_field, $name_field);
3716 if (defined $headrev && $self->use_svm_props) {
3717 if ($self->rewrite_root) {
3718 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3719 "options set!\n";
3721 if ($self->rewrite_uuid) {
3722 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3723 "options set!\n";
3725 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3726 # we don't want "SVM: initializing mirror for junk" ...
3727 return undef if $r == 0;
3728 my $svm = $self->svm;
3729 if ($uuid ne $svm->{uuid}) {
3730 die "UUID mismatch on SVM path:\n",
3731 "expected: $svm->{uuid}\n",
3732 " got: $uuid\n";
3734 my $full_url = $self->full_url;
3735 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3736 die "Failed to replace '$svm->{replace}' with ",
3737 "'$svm->{source}' in $full_url\n";
3738 # throw away username for storing in records
3739 remove_username($full_url);
3740 $log_entry{metadata} = "$full_url\@$r $uuid";
3741 $log_entry{svm_revision} = $r;
3742 $email ||= "$author\@$uuid";
3743 $commit_email ||= "$author\@$uuid";
3744 } elsif ($self->use_svnsync_props) {
3745 my $full_url = $self->svnsync->{url};
3746 $full_url .= "/$self->{path}" if length $self->{path};
3747 remove_username($full_url);
3748 my $uuid = $self->svnsync->{uuid};
3749 $log_entry{metadata} = "$full_url\@$rev $uuid";
3750 $email ||= "$author\@$uuid";
3751 $commit_email ||= "$author\@$uuid";
3752 } else {
3753 my $url = $self->metadata_url;
3754 remove_username($url);
3755 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3756 $log_entry{metadata} = "$url\@$rev " . $uuid;
3757 $email ||= "$author\@" . $uuid;
3758 $commit_email ||= "$author\@" . $uuid;
3760 $log_entry{name} = $name;
3761 $log_entry{email} = $email;
3762 $log_entry{commit_name} = $commit_name;
3763 $log_entry{commit_email} = $commit_email;
3764 \%log_entry;
3767 sub fetch {