Thread-safe xmalloc and xrealloc needs a recursive mutex
[git/dscho.git] / git-svn.perl
blob473a0b9d556fc7ead7088c4cb6c6f14c4a70995b
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
22 $Git::SVN::_minimize_url = 'unset';
24 if (! exists $ENV{SVN_SSH}) {
25 if (exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27 if ($^O eq 'msys') {
28 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
29 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
34 $Git::SVN::Log::TZ = $ENV{TZ};
35 $ENV{TZ} = 'UTC';
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
39 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
40 require SVN::Ra;
41 require SVN::Delta;
42 if ($SVN::Core::VERSION lt '1.1.0') {
43 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
45 my $can_compress = eval { require Compress::Zlib; 1};
46 push @Git::SVN::Ra::ISA, 'SVN::Ra';
47 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
48 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
49 use Carp qw/croak/;
50 use Digest::MD5;
51 use IO::File qw//;
52 use File::Basename qw/dirname basename/;
53 use File::Path qw/mkpath/;
54 use File::Spec;
55 use File::Find;
56 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
57 use IPC::Open3;
58 use Git;
60 BEGIN {
61 # import functions from Git into our packages, en masse
62 no strict 'refs';
63 foreach (qw/command command_oneline command_noisy command_output_pipe
64 command_input_pipe command_close_pipe
65 command_bidi_pipe command_close_bidi_pipe/) {
66 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
67 Git::SVN::Migration Git::SVN::Log Git::SVN),
68 __PACKAGE__) {
69 *{"${package}::$_"} = \&{"Git::$_"};
74 my ($SVN);
76 $sha1 = qr/[a-f\d]{40}/;
77 $sha1_short = qr/[a-f\d]{4,40}/;
78 my ($_stdin, $_help, $_edit,
79 $_message, $_file, $_branch_dest,
80 $_template, $_shared,
81 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
82 $_merge, $_strategy, $_dry_run, $_local,
83 $_prefix, $_no_checkout, $_url, $_verbose,
84 $_git_format, $_commit_url, $_tag);
85 $Git::SVN::_follow_parent = 1;
86 $_q ||= 0;
87 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
88 'config-dir=s' => \$Git::SVN::Ra::config_dir,
89 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
90 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
91 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
92 'authors-file|A=s' => \$_authors,
93 'authors-prog=s' => \$_authors_prog,
94 'repack:i' => \$Git::SVN::_repack,
95 'noMetadata' => \$Git::SVN::_no_metadata,
96 'useSvmProps' => \$Git::SVN::_use_svm_props,
97 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
98 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
99 'no-checkout' => \$_no_checkout,
100 'quiet|q+' => \$_q,
101 'repack-flags|repack-args|repack-opts=s' =>
102 \$Git::SVN::_repack_flags,
103 'use-log-author' => \$Git::SVN::_use_log_author,
104 'add-author-from' => \$Git::SVN::_add_author_from,
105 'localtime' => \$Git::SVN::_localtime,
106 %remote_opts );
108 my ($_trunk, @_tags, @_branches, $_stdlayout);
109 my %icv;
110 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
111 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
112 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
113 'stdlayout|s' => \$_stdlayout,
114 'minimize-url|m!' => \$Git::SVN::_minimize_url,
115 'no-metadata' => sub { $icv{noMetadata} = 1 },
116 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
117 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
118 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
119 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
120 %remote_opts );
121 my %cmt_opts = ( 'edit|e' => \$_edit,
122 'rmdir' => \$SVN::Git::Editor::_rmdir,
123 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
124 'l=i' => \$SVN::Git::Editor::_rename_limit,
125 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
128 my %cmd = (
129 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
130 { 'revision|r=s' => \$_revision,
131 'fetch-all|all' => \$_fetch_all,
132 'parent|p' => \$_fetch_parent,
133 %fc_opts } ],
134 clone => [ \&cmd_clone, "Initialize and fetch revisions",
135 { 'revision|r=s' => \$_revision,
136 %fc_opts, %init_opts } ],
137 init => [ \&cmd_init, "Initialize a repo for tracking" .
138 " (requires URL argument)",
139 \%init_opts ],
140 'multi-init' => [ \&cmd_multi_init,
141 "Deprecated alias for ".
142 "'$0 init -T<trunk> -b<branches> -t<tags>'",
143 \%init_opts ],
144 dcommit => [ \&cmd_dcommit,
145 'Commit several diffs to merge with upstream',
146 { 'merge|m|M' => \$_merge,
147 'strategy|s=s' => \$_strategy,
148 'verbose|v' => \$_verbose,
149 'dry-run|n' => \$_dry_run,
150 'fetch-all|all' => \$_fetch_all,
151 'commit-url=s' => \$_commit_url,
152 'revision|r=i' => \$_revision,
153 'no-rebase' => \$_no_rebase,
154 %cmt_opts, %fc_opts } ],
155 branch => [ \&cmd_branch,
156 'Create a branch in the SVN repository',
157 { 'message|m=s' => \$_message,
158 'destination|d=s' => \$_branch_dest,
159 'dry-run|n' => \$_dry_run,
160 'tag|t' => \$_tag,
161 'username=s' => \$Git::SVN::Prompt::_username,
162 'commit-url=s' => \$_commit_url } ],
163 tag => [ sub { $_tag = 1; cmd_branch(@_) },
164 'Create a tag in the SVN repository',
165 { 'message|m=s' => \$_message,
166 'destination|d=s' => \$_branch_dest,
167 'dry-run|n' => \$_dry_run,
168 'username=s' => \$Git::SVN::Prompt::_username,
169 'commit-url=s' => \$_commit_url } ],
170 'set-tree' => [ \&cmd_set_tree,
171 "Set an SVN repository to a git tree-ish",
172 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
173 'create-ignore' => [ \&cmd_create_ignore,
174 'Create a .gitignore per svn:ignore',
175 { 'revision|r=i' => \$_revision
176 } ],
177 'mkdirs' => [ \&cmd_mkdirs ,
178 "recreate empty directories after a checkout",
179 { 'revision|r=i' => \$_revision } ],
180 'propget' => [ \&cmd_propget,
181 'Print the value of a property on a file or directory',
182 { 'revision|r=i' => \$_revision } ],
183 'proplist' => [ \&cmd_proplist,
184 'List all properties of a file or directory',
185 { 'revision|r=i' => \$_revision } ],
186 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
187 { 'revision|r=i' => \$_revision
188 } ],
189 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
190 { 'revision|r=i' => \$_revision
191 } ],
192 'multi-fetch' => [ \&cmd_multi_fetch,
193 "Deprecated alias for $0 fetch --all",
194 { 'revision|r=s' => \$_revision, %fc_opts } ],
195 'migrate' => [ sub { },
196 # no-op, we automatically run this anyways,
197 'Migrate configuration/metadata/layout from
198 previous versions of git-svn',
199 { 'minimize' => \$Git::SVN::Migration::_minimize,
200 %remote_opts } ],
201 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
202 { 'limit=i' => \$Git::SVN::Log::limit,
203 'revision|r=s' => \$_revision,
204 'verbose|v' => \$Git::SVN::Log::verbose,
205 'incremental' => \$Git::SVN::Log::incremental,
206 'oneline' => \$Git::SVN::Log::oneline,
207 'show-commit' => \$Git::SVN::Log::show_commit,
208 'non-recursive' => \$Git::SVN::Log::non_recursive,
209 'authors-file|A=s' => \$_authors,
210 'color' => \$Git::SVN::Log::color,
211 'pager=s' => \$Git::SVN::Log::pager
212 } ],
213 'find-rev' => [ \&cmd_find_rev,
214 "Translate between SVN revision numbers and tree-ish",
215 {} ],
216 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
217 { 'merge|m|M' => \$_merge,
218 'verbose|v' => \$_verbose,
219 'strategy|s=s' => \$_strategy,
220 'local|l' => \$_local,
221 'fetch-all|all' => \$_fetch_all,
222 'dry-run|n' => \$_dry_run,
223 %fc_opts } ],
224 'commit-diff' => [ \&cmd_commit_diff,
225 'Commit a diff between two trees',
226 { 'message|m=s' => \$_message,
227 'file|F=s' => \$_file,
228 'revision|r=s' => \$_revision,
229 %cmt_opts } ],
230 'info' => [ \&cmd_info,
231 "Show info about the latest SVN revision
232 on the current branch",
233 { 'url' => \$_url, } ],
234 'blame' => [ \&Git::SVN::Log::cmd_blame,
235 "Show what revision and author last modified each line of a file",
236 { 'git-format' => \$_git_format } ],
237 'reset' => [ \&cmd_reset,
238 "Undo fetches back to the specified SVN revision",
239 { 'revision|r=s' => \$_revision,
240 'parent|p' => \$_fetch_parent } ],
241 'gc' => [ \&cmd_gc,
242 "Compress unhandled.log files in .git/svn and remove " .
243 "index files in .git/svn",
244 {} ],
247 my $cmd;
248 for (my $i = 0; $i < @ARGV; $i++) {
249 if (defined $cmd{$ARGV[$i]}) {
250 $cmd = $ARGV[$i];
251 splice @ARGV, $i, 1;
252 last;
253 } elsif ($ARGV[$i] eq 'help') {
254 $cmd = $ARGV[$i+1];
255 usage(0);
259 # make sure we're always running at the top-level working directory
260 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
261 unless (-d $ENV{GIT_DIR}) {
262 if ($git_dir_user_set) {
263 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
264 "but it is not a directory\n";
266 my $git_dir = delete $ENV{GIT_DIR};
267 my $cdup = undef;
268 git_cmd_try {
269 $cdup = command_oneline(qw/rev-parse --show-cdup/);
270 $git_dir = '.' unless ($cdup);
271 chomp $cdup if ($cdup);
272 $cdup = "." unless ($cdup && length $cdup);
273 } "Already at toplevel, but $git_dir not found\n";
274 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
275 unless (-d $git_dir) {
276 die "$git_dir still not found after going to ",
277 "'$cdup'\n";
279 $ENV{GIT_DIR} = $git_dir;
281 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
284 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
286 read_git_config(\%opts);
287 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
288 Getopt::Long::Configure('pass_through');
290 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
291 'minimize-connections' => \$Git::SVN::Migration::_minimize,
292 'id|i=s' => \$Git::SVN::default_ref_id,
293 'svn-remote|remote|R=s' => sub {
294 $Git::SVN::no_reuse_existing = 1;
295 $Git::SVN::default_repo_id = $_[1] });
296 exit 1 if (!$rv && $cmd && $cmd ne 'log');
298 usage(0) if $_help;
299 version() if $_version;
300 usage(1) unless defined $cmd;
301 load_authors() if $_authors;
302 if (defined $_authors_prog) {
303 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
306 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
307 Git::SVN::Migration::migration_check();
309 Git::SVN::init_vars();
310 eval {
311 Git::SVN::verify_remotes_sanity();
312 $cmd{$cmd}->[0]->(@ARGV);
314 fatal $@ if $@;
315 post_fetch_checkout();
316 exit 0;
318 ####################### primary functions ######################
319 sub usage {
320 my $exit = shift || 0;
321 my $fd = $exit ? \*STDERR : \*STDOUT;
322 print $fd <<"";
323 git-svn - bidirectional operations between a single Subversion tree and git
324 Usage: git svn <command> [options] [arguments]\n
326 print $fd "Available commands:\n" unless $cmd;
328 foreach (sort keys %cmd) {
329 next if $cmd && $cmd ne $_;
330 next if /^multi-/; # don't show deprecated commands
331 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
332 foreach (sort keys %{$cmd{$_}->[2]}) {
333 # mixed-case options are for .git/config only
334 next if /[A-Z]/ && /^[a-z]+$/i;
335 # prints out arguments as they should be passed:
336 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
337 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
338 "--$_" : "-$_" }
339 split /\|/,$_)," $x\n";
342 print $fd <<"";
343 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
344 arbitrary identifier if you're tracking multiple SVN branches/repositories in
345 one git repository and want to keep them separate. See git-svn(1) for more
346 information.
348 exit $exit;
351 sub version {
352 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
353 exit 0;
356 sub do_git_init_db {
357 unless (-d $ENV{GIT_DIR}) {
358 my @init_db = ('init');
359 push @init_db, "--template=$_template" if defined $_template;
360 if (defined $_shared) {
361 if ($_shared =~ /[a-z]/) {
362 push @init_db, "--shared=$_shared";
363 } else {
364 push @init_db, "--shared";
367 command_noisy(@init_db);
368 $_repository = Git->repository(Repository => ".git");
370 command_noisy('config', 'core.autocrlf', 'false');
371 my $set;
372 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
373 foreach my $i (keys %icv) {
374 die "'$set' and '$i' cannot both be set\n" if $set;
375 next unless defined $icv{$i};
376 command_noisy('config', "$pfx.$i", $icv{$i});
377 $set = $i;
379 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
380 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
381 if defined $$ignore_regex;
384 sub init_subdir {
385 my $repo_path = shift or return;
386 mkpath([$repo_path]) unless -d $repo_path;
387 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
388 $ENV{GIT_DIR} = '.git';
389 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
392 sub cmd_clone {
393 my ($url, $path) = @_;
394 if (!defined $path &&
395 (defined $_trunk || @_branches || @_tags ||
396 defined $_stdlayout) &&
397 $url !~ m#^[a-z\+]+://#) {
398 $path = $url;
400 $path = basename($url) if !defined $path || !length $path;
401 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
402 cmd_init($url, $path);
403 command_oneline('config', 'svn.authorsfile', $authors_absolute)
404 if $_authors;
405 Git::SVN::fetch_all($Git::SVN::default_repo_id);
408 sub cmd_init {
409 if (defined $_stdlayout) {
410 $_trunk = 'trunk' if (!defined $_trunk);
411 @_tags = 'tags' if (! @_tags);
412 @_branches = 'branches' if (! @_branches);
414 if (defined $_trunk || @_branches || @_tags) {
415 return cmd_multi_init(@_);
417 my $url = shift or die "SVN repository location required ",
418 "as a command-line argument\n";
419 $url = canonicalize_url($url);
420 init_subdir(@_);
421 do_git_init_db();
423 if ($Git::SVN::_minimize_url eq 'unset') {
424 $Git::SVN::_minimize_url = 0;
427 Git::SVN->init($url);
430 sub cmd_fetch {
431 if (grep /^\d+=./, @_) {
432 die "'<rev>=<commit>' fetch arguments are ",
433 "no longer supported.\n";
435 my ($remote) = @_;
436 if (@_ > 1) {
437 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
439 $Git::SVN::no_reuse_existing = undef;
440 if ($_fetch_parent) {
441 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
442 unless ($gs) {
443 die "Unable to determine upstream SVN information from ",
444 "working tree history\n";
446 # just fetch, don't checkout.
447 $_no_checkout = 'true';
448 $_fetch_all ? $gs->fetch_all : $gs->fetch;
449 } elsif ($_fetch_all) {
450 cmd_multi_fetch();
451 } else {
452 $remote ||= $Git::SVN::default_repo_id;
453 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
457 sub cmd_set_tree {
458 my (@commits) = @_;
459 if ($_stdin || !@commits) {
460 print "Reading from stdin...\n";
461 @commits = ();
462 while (<STDIN>) {
463 if (/\b($sha1_short)\b/o) {
464 unshift @commits, $1;
468 my @revs;
469 foreach my $c (@commits) {
470 my @tmp = command('rev-parse',$c);
471 if (scalar @tmp == 1) {
472 push @revs, $tmp[0];
473 } elsif (scalar @tmp > 1) {
474 push @revs, reverse(command('rev-list',@tmp));
475 } else {
476 fatal "Failed to rev-parse $c";
479 my $gs = Git::SVN->new;
480 my ($r_last, $cmt_last) = $gs->last_rev_commit;
481 $gs->fetch;
482 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
483 fatal "There are new revisions that were fetched ",
484 "and need to be merged (or acknowledged) ",
485 "before committing.\nlast rev: $r_last\n",
486 " current: $gs->{last_rev}";
488 $gs->set_tree($_) foreach @revs;
489 print "Done committing ",scalar @revs," revisions to SVN\n";
490 unlink $gs->{index};
493 sub cmd_dcommit {
494 my $head = shift;
495 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
496 'Cannot dcommit with a dirty index. Commit your changes first, '
497 . "or stash them with `git stash'.\n";
498 $head ||= 'HEAD';
500 my $old_head;
501 if ($head ne 'HEAD') {
502 $old_head = eval {
503 command_oneline([qw/symbolic-ref -q HEAD/])
505 if ($old_head) {
506 $old_head =~ s{^refs/heads/}{};
507 } else {
508 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
510 command(['checkout', $head], STDERR => 0);
513 my @refs;
514 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
515 unless ($gs) {
516 die "Unable to determine upstream SVN information from ",
517 "$head history.\nPerhaps the repository is empty.";
520 if (defined $_commit_url) {
521 $url = $_commit_url;
522 } else {
523 $url = eval { command_oneline('config', '--get',
524 "svn-remote.$gs->{repo_id}.commiturl") };
525 if (!$url) {
526 $url = $gs->full_url
530 my $last_rev = $_revision if defined $_revision;
531 if ($url) {
532 print "Committing to $url ...\n";
534 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
535 if ($_no_rebase && scalar(@$linear_refs) > 1) {
536 warn "Attempting to commit more than one change while ",
537 "--no-rebase is enabled.\n",
538 "If these changes depend on each other, re-running ",
539 "without --no-rebase may be required."
541 my $expect_url = $url;
542 Git::SVN::remove_username($expect_url);
543 while (1) {
544 my $d = shift @$linear_refs or last;
545 unless (defined $last_rev) {
546 (undef, $last_rev, undef) = cmt_metadata("$d~1");
547 unless (defined $last_rev) {
548 fatal "Unable to extract revision information ",
549 "from commit $d~1";
552 if ($_dry_run) {
553 print "diff-tree $d~1 $d\n";
554 } else {
555 my $cmt_rev;
556 my %ed_opts = ( r => $last_rev,
557 log => get_commit_entry($d)->{log},
558 ra => Git::SVN::Ra->new($url),
559 config => SVN::Core::config_get_config(
560 $Git::SVN::Ra::config_dir
562 tree_a => "$d~1",
563 tree_b => $d,
564 editor_cb => sub {
565 print "Committed r$_[0]\n";
566 $cmt_rev = $_[0];
568 svn_path => '');
569 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
570 print "No changes\n$d~1 == $d\n";
571 } elsif ($parents->{$d} && @{$parents->{$d}}) {
572 $gs->{inject_parents_dcommit}->{$cmt_rev} =
573 $parents->{$d};
575 $_fetch_all ? $gs->fetch_all : $gs->fetch;
576 $last_rev = $cmt_rev;
577 next if $_no_rebase;
579 # we always want to rebase against the current HEAD,
580 # not any head that was passed to us
581 my @diff = command('diff-tree', $d,
582 $gs->refname, '--');
583 my @finish;
584 if (@diff) {
585 @finish = rebase_cmd();
586 print STDERR "W: $d and ", $gs->refname,
587 " differ, using @finish:\n",
588 join("\n", @diff), "\n";
589 } else {
590 print "No changes between current HEAD and ",
591 $gs->refname,
592 "\nResetting to the latest ",
593 $gs->refname, "\n";
594 @finish = qw/reset --mixed/;
596 command_noisy(@finish, $gs->refname);
597 if (@diff) {
598 @refs = ();
599 my ($url_, $rev_, $uuid_, $gs_) =
600 working_head_info('HEAD', \@refs);
601 my ($linear_refs_, $parents_) =
602 linearize_history($gs_, \@refs);
603 if (scalar(@$linear_refs) !=
604 scalar(@$linear_refs_)) {
605 fatal "# of revisions changed ",
606 "\nbefore:\n",
607 join("\n", @$linear_refs),
608 "\n\nafter:\n",
609 join("\n", @$linear_refs_), "\n",
610 'If you are attempting to commit ',
611 "merges, try running:\n\t",
612 'git rebase --interactive',
613 '--preserve-merges ',
614 $gs->refname,
615 "\nBefore dcommitting";
617 if ($url_ ne $expect_url) {
618 if ($url_ eq $gs->metadata_url) {
619 print
620 "Accepting rewritten URL:",
621 " $url_\n";
622 } else {
623 fatal
624 "URL mismatch after rebase:",
625 " $url_ != $expect_url";
628 if ($uuid_ ne $uuid) {
629 fatal "uuid mismatch after rebase: ",
630 "$uuid_ != $uuid";
632 # remap parents
633 my (%p, @l, $i);
634 for ($i = 0; $i < scalar @$linear_refs; $i++) {
635 my $new = $linear_refs_->[$i] or next;
636 $p{$new} =
637 $parents->{$linear_refs->[$i]};
638 push @l, $new;
640 $parents = \%p;
641 $linear_refs = \@l;
646 if ($old_head) {
647 my $new_head = command_oneline(qw/rev-parse HEAD/);
648 my $new_is_symbolic = eval {
649 command_oneline(qw/symbolic-ref -q HEAD/);
651 if ($new_is_symbolic) {
652 print "dcommitted the branch ", $head, "\n";
653 } else {
654 print "dcommitted on a detached HEAD because you gave ",
655 "a revision argument.\n",
656 "The rewritten commit is: ", $new_head, "\n";
658 command(['checkout', $old_head], STDERR => 0);
661 unlink $gs->{index};
664 sub cmd_branch {
665 my ($branch_name, $head) = @_;
667 unless (defined $branch_name && length $branch_name) {
668 die(($_tag ? "tag" : "branch") . " name required\n");
670 $head ||= 'HEAD';
672 my (undef, $rev, undef, $gs) = working_head_info($head);
673 my $src = $gs->full_url;
675 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
676 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
677 my $glob;
678 if ($#{$allglobs} == 0) {
679 $glob = $allglobs->[0];
680 } else {
681 unless(defined $_branch_dest) {
682 die "Multiple ",
683 $_tag ? "tag" : "branch",
684 " paths defined for Subversion repository.\n",
685 "You must specify where you want to create the ",
686 $_tag ? "tag" : "branch",
687 " with the --destination argument.\n";
689 foreach my $g (@{$allglobs}) {
690 # SVN::Git::Editor could probably be moved to Git.pm..
691 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
692 if ($_branch_dest =~ /$re/) {
693 $glob = $g;
694 last;
697 unless (defined $glob) {
698 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
699 foreach my $g (@{$allglobs}) {
700 $g->{path}->{left} =~ /$dest_re/ or next;
701 if (defined $glob) {
702 die "Ambiguous destination: ",
703 $_branch_dest, "\nmatches both '",
704 $glob->{path}->{left}, "' and '",
705 $g->{path}->{left}, "'\n";
707 $glob = $g;
709 unless (defined $glob) {
710 die "Unknown ",
711 $_tag ? "tag" : "branch",
712 " destination $_branch_dest\n";
716 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
717 my $url;
718 if (defined $_commit_url) {
719 $url = $_commit_url;
720 } else {
721 $url = eval { command_oneline('config', '--get',
722 "svn-remote.$gs->{repo_id}.commiturl") };
723 if (!$url) {
724 $url = $remote->{url};
727 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
729 if ($dst =~ /^https:/ && $src =~ /^http:/) {
730 $src=~s/^http:/https:/;
733 my $ctx = SVN::Client->new(
734 auth => Git::SVN::Ra::_auth_providers(),
735 log_msg => sub {
736 ${ $_[0] } = defined $_message
737 ? $_message
738 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
739 . $branch_name;
743 eval {
744 $ctx->ls($dst, 'HEAD', 0);
745 } and die "branch ${branch_name} already exists\n";
747 print "Copying ${src} at r${rev} to ${dst}...\n";
748 $ctx->copy($src, $rev, $dst)
749 unless $_dry_run;
751 $gs->fetch_all;
754 sub cmd_find_rev {
755 my $revision_or_hash = shift or die "SVN or git revision required ",
756 "as a command-line argument\n";
757 my $result;
758 if ($revision_or_hash =~ /^r\d+$/) {
759 my $head = shift;
760 $head ||= 'HEAD';
761 my @refs;
762 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
763 unless ($gs) {
764 die "Unable to determine upstream SVN information from ",
765 "$head history\n";
767 my $desired_revision = substr($revision_or_hash, 1);
768 $result = $gs->rev_map_get($desired_revision, $uuid);
769 } else {
770 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
771 $result = $rev;
773 print "$result\n" if $result;
776 sub cmd_rebase {
777 command_noisy(qw/update-index --refresh/);
778 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
779 unless ($gs) {
780 die "Unable to determine upstream SVN information from ",
781 "working tree history\n";
783 if ($_dry_run) {
784 print "Remote Branch: " . $gs->refname . "\n";
785 print "SVN URL: " . $url . "\n";
786 return;
788 if (command(qw/diff-index HEAD --/)) {
789 print STDERR "Cannot rebase with uncommited changes:\n";
790 command_noisy('status');
791 exit 1;
793 unless ($_local) {
794 # rebase will checkout for us, so no need to do it explicitly
795 $_no_checkout = 'true';
796 $_fetch_all ? $gs->fetch_all : $gs->fetch;
798 command_noisy(rebase_cmd(), $gs->refname);
799 $gs->mkemptydirs;
802 sub cmd_show_ignore {
803 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
804 $gs ||= Git::SVN->new;
805 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
806 $gs->prop_walk($gs->{path}, $r, sub {
807 my ($gs, $path, $props) = @_;
808 print STDOUT "\n# $path\n";
809 my $s = $props->{'svn:ignore'} or return;
810 $s =~ s/[\r\n]+/\n/g;
811 $s =~ s/^\n+//;
812 chomp $s;
813 $s =~ s#^#$path#gm;
814 print STDOUT "$s\n";
818 sub cmd_show_externals {
819 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
820 $gs ||= Git::SVN->new;
821 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
822 $gs->prop_walk($gs->{path}, $r, sub {
823 my ($gs, $path, $props) = @_;
824 print STDOUT "\n# $path\n";
825 my $s = $props->{'svn:externals'} or return;
826 $s =~ s/[\r\n]+/\n/g;
827 chomp $s;
828 $s =~ s#^#$path#gm;
829 print STDOUT "$s\n";
833 sub cmd_create_ignore {
834 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
835 $gs ||= Git::SVN->new;
836 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
837 $gs->prop_walk($gs->{path}, $r, sub {
838 my ($gs, $path, $props) = @_;
839 # $path is of the form /path/to/dir/
840 $path = '.' . $path;
841 # SVN can have attributes on empty directories,
842 # which git won't track
843 mkpath([$path]) unless -d $path;
844 my $ignore = $path . '.gitignore';
845 my $s = $props->{'svn:ignore'} or return;
846 open(GITIGNORE, '>', $ignore)
847 or fatal("Failed to open `$ignore' for writing: $!");
848 $s =~ s/[\r\n]+/\n/g;
849 $s =~ s/^\n+//;
850 chomp $s;
851 # Prefix all patterns so that the ignore doesn't apply
852 # to sub-directories.
853 $s =~ s#^#/#gm;
854 print GITIGNORE "$s\n";
855 close(GITIGNORE)
856 or fatal("Failed to close `$ignore': $!");
857 command_noisy('add', '-f', $ignore);
861 sub cmd_mkdirs {
862 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
863 $gs ||= Git::SVN->new;
864 $gs->mkemptydirs($_revision);
867 sub canonicalize_path {
868 my ($path) = @_;
869 my $dot_slash_added = 0;
870 if (substr($path, 0, 1) ne "/") {
871 $path = "./" . $path;
872 $dot_slash_added = 1;
874 # File::Spec->canonpath doesn't collapse x/../y into y (for a
875 # good reason), so let's do this manually.
876 $path =~ s#/+#/#g;
877 $path =~ s#/\.(?:/|$)#/#g;
878 $path =~ s#/[^/]+/\.\.##g;
879 $path =~ s#/$##g;
880 $path =~ s#^\./## if $dot_slash_added;
881 $path =~ s#^/##;
882 $path =~ s#^\.$##;
883 return $path;
886 sub canonicalize_url {
887 my ($url) = @_;
888 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
889 return $url;
892 # get_svnprops(PATH)
893 # ------------------
894 # Helper for cmd_propget and cmd_proplist below.
895 sub get_svnprops {
896 my $path = shift;
897 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
898 $gs ||= Git::SVN->new;
900 # prefix THE PATH by the sub-directory from which the user
901 # invoked us.
902 $path = $cmd_dir_prefix . $path;
903 fatal("No such file or directory: $path") unless -e $path;
904 my $is_dir = -d $path ? 1 : 0;
905 $path = $gs->{path} . '/' . $path;
907 # canonicalize the path (otherwise libsvn will abort or fail to
908 # find the file)
909 $path = canonicalize_path($path);
911 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
912 my $props;
913 if ($is_dir) {
914 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
916 else {
917 (undef, $props) = $gs->ra->get_file($path, $r, undef);
919 return $props;
922 # cmd_propget (PROP, PATH)
923 # ------------------------
924 # Print the SVN property PROP for PATH.
925 sub cmd_propget {
926 my ($prop, $path) = @_;
927 $path = '.' if not defined $path;
928 usage(1) if not defined $prop;
929 my $props = get_svnprops($path);
930 if (not defined $props->{$prop}) {
931 fatal("`$path' does not have a `$prop' SVN property.");
933 print $props->{$prop} . "\n";
936 # cmd_proplist (PATH)
937 # -------------------
938 # Print the list of SVN properties for PATH.
939 sub cmd_proplist {
940 my $path = shift;
941 $path = '.' if not defined $path;
942 my $props = get_svnprops($path);
943 print "Properties on '$path':\n";
944 foreach (sort keys %{$props}) {
945 print " $_\n";
949 sub cmd_multi_init {
950 my $url = shift;
951 unless (defined $_trunk || @_branches || @_tags) {
952 usage(1);
955 $_prefix = '' unless defined $_prefix;
956 if (defined $url) {
957 $url = canonicalize_url($url);
958 init_subdir(@_);
960 do_git_init_db();
961 if (defined $_trunk) {
962 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
963 # try both old-style and new-style lookups:
964 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
965 unless ($gs_trunk) {
966 my ($trunk_url, $trunk_path) =
967 complete_svn_url($url, $_trunk);
968 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
969 undef, $trunk_ref);
972 return unless @_branches || @_tags;
973 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
974 foreach my $path (@_branches) {
975 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
977 foreach my $path (@_tags) {
978 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
982 sub cmd_multi_fetch {
983 $Git::SVN::no_reuse_existing = undef;
984 my $remotes = Git::SVN::read_all_remotes();
985 foreach my $repo_id (sort keys %$remotes) {
986 if ($remotes->{$repo_id}->{url}) {
987 Git::SVN::fetch_all($repo_id, $remotes);
992 # this command is special because it requires no metadata
993 sub cmd_commit_diff {
994 my ($ta, $tb, $url) = @_;
995 my $usage = "Usage: $0 commit-diff -r<revision> ".
996 "<tree-ish> <tree-ish> [<URL>]";
997 fatal($usage) if (!defined $ta || !defined $tb);
998 my $svn_path = '';
999 if (!defined $url) {
1000 my $gs = eval { Git::SVN->new };
1001 if (!$gs) {
1002 fatal("Needed URL or usable git-svn --id in ",
1003 "the command-line\n", $usage);
1005 $url = $gs->{url};
1006 $svn_path = $gs->{path};
1008 unless (defined $_revision) {
1009 fatal("-r|--revision is a required argument\n", $usage);
1011 if (defined $_message && defined $_file) {
1012 fatal("Both --message/-m and --file/-F specified ",
1013 "for the commit message.\n",
1014 "I have no idea what you mean");
1016 if (defined $_file) {
1017 $_message = file_to_s($_file);
1018 } else {
1019 $_message ||= get_commit_entry($tb)->{log};
1021 my $ra ||= Git::SVN::Ra->new($url);
1022 my $r = $_revision;
1023 if ($r eq 'HEAD') {
1024 $r = $ra->get_latest_revnum;
1025 } elsif ($r !~ /^\d+$/) {
1026 die "revision argument: $r not understood by git-svn\n";
1028 my %ed_opts = ( r => $r,
1029 log => $_message,
1030 ra => $ra,
1031 tree_a => $ta,
1032 tree_b => $tb,
1033 editor_cb => sub { print "Committed r$_[0]\n" },
1034 svn_path => $svn_path );
1035 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1036 print "No changes\n$ta == $tb\n";
1040 sub escape_uri_only {
1041 my ($uri) = @_;
1042 my @tmp;
1043 foreach (split m{/}, $uri) {
1044 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1045 push @tmp, $_;
1047 join('/', @tmp);
1050 sub escape_url {
1051 my ($url) = @_;
1052 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1053 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1054 $url = "$scheme://$domain$uri";
1056 $url;
1059 sub cmd_info {
1060 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1061 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1062 if (exists $_[1]) {
1063 die "Too many arguments specified\n";
1066 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1068 if (!$file_type && !$diff_status) {
1069 print STDERR "svn: '$path' is not under version control\n";
1070 exit 1;
1073 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1074 unless ($gs) {
1075 die "Unable to determine upstream SVN information from ",
1076 "working tree history\n";
1079 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1080 $path = "." if $path eq "";
1082 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1084 if ($_url) {
1085 print escape_url($full_url), "\n";
1086 return;
1089 my $result = "Path: $path\n";
1090 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1091 $result .= "URL: " . escape_url($full_url) . "\n";
1093 eval {
1094 my $repos_root = $gs->repos_root;
1095 Git::SVN::remove_username($repos_root);
1096 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1098 if ($@) {
1099 $result .= "Repository Root: (offline)\n";
1101 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1102 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1103 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1105 $result .= "Node Kind: " .
1106 ($file_type eq "dir" ? "directory" : "file") . "\n";
1108 my $schedule = $diff_status eq "A"
1109 ? "add"
1110 : ($diff_status eq "D" ? "delete" : "normal");
1111 $result .= "Schedule: $schedule\n";
1113 if ($diff_status eq "A") {
1114 print $result, "\n";
1115 return;
1118 my ($lc_author, $lc_rev, $lc_date_utc);
1119 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1120 my $log = command_output_pipe(@args);
1121 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1122 while (<$log>) {
1123 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1124 $lc_author = $1;
1125 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1126 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1127 (undef, $lc_rev, undef) = ::extract_metadata($1);
1130 close $log;
1132 Git::SVN::Log::set_local_timezone();
1134 $result .= "Last Changed Author: $lc_author\n";
1135 $result .= "Last Changed Rev: $lc_rev\n";
1136 $result .= "Last Changed Date: " .
1137 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1139 if ($file_type ne "dir") {
1140 my $text_last_updated_date =
1141 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1142 $result .=
1143 "Text Last Updated: " .
1144 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1145 "\n";
1146 my $checksum;
1147 if ($diff_status eq "D") {
1148 my ($fh, $ctx) =
1149 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1150 if ($file_type eq "link") {
1151 my $file_name = <$fh>;
1152 $checksum = md5sum("link $file_name");
1153 } else {
1154 $checksum = md5sum($fh);
1156 command_close_pipe($fh, $ctx);
1157 } elsif ($file_type eq "link") {
1158 my $file_name =
1159 command(qw(cat-file blob), "HEAD:$path");
1160 $checksum =
1161 md5sum("link " . $file_name);
1162 } else {
1163 open FILE, "<", $path or die $!;
1164 $checksum = md5sum(\*FILE);
1165 close FILE or die $!;
1167 $result .= "Checksum: " . $checksum . "\n";
1170 print $result, "\n";
1173 sub cmd_reset {
1174 my $target = shift || $_revision or die "SVN revision required\n";
1175 $target = $1 if $target =~ /^r(\d+)$/;
1176 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1177 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1178 unless ($gs) {
1179 die "Unable to determine upstream SVN information from ".
1180 "history\n";
1182 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1183 $gs->rev_map_set($r, $c, 'reset', $uuid);
1184 print "r$r = $c ($gs->{ref_id})\n";
1187 sub cmd_gc {
1188 if (!$can_compress) {
1189 warn "Compress::Zlib could not be found; unhandled.log " .
1190 "files will not be compressed.\n";
1192 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1195 ########################### utility functions #########################
1197 sub rebase_cmd {
1198 my @cmd = qw/rebase/;
1199 push @cmd, '-v' if $_verbose;
1200 push @cmd, qw/--merge/ if $_merge;
1201 push @cmd, "--strategy=$_strategy" if $_strategy;
1202 @cmd;
1205 sub post_fetch_checkout {
1206 return if $_no_checkout;
1207 my $gs = $Git::SVN::_head or return;
1208 return if verify_ref('refs/heads/master^0');
1210 # look for "trunk" ref if it exists
1211 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1212 my $fetch = $remote->{fetch};
1213 if ($fetch) {
1214 foreach my $p (keys %$fetch) {
1215 basename($fetch->{$p}) eq 'trunk' or next;
1216 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1217 last;
1221 my $valid_head = verify_ref('HEAD^0');
1222 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1223 return if ($valid_head || !verify_ref('HEAD^0'));
1225 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1226 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1227 return if -f $index;
1229 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1230 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1231 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1232 print STDERR "Checked out HEAD:\n ",
1233 $gs->full_url, " r", $gs->last_rev, "\n";
1234 $gs->mkemptydirs($gs->last_rev);
1237 sub complete_svn_url {
1238 my ($url, $path) = @_;
1239 $path =~ s#/+$##;
1240 if ($path !~ m#^[a-z\+]+://#) {
1241 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1242 fatal("E: '$path' is not a complete URL ",
1243 "and a separate URL is not specified");
1245 return ($url, $path);
1247 return ($path, '');
1250 sub complete_url_ls_init {
1251 my ($ra, $repo_path, $switch, $pfx) = @_;
1252 unless ($repo_path) {
1253 print STDERR "W: $switch not specified\n";
1254 return;
1256 $repo_path =~ s#/+$##;
1257 if ($repo_path =~ m#^[a-z\+]+://#) {
1258 $ra = Git::SVN::Ra->new($repo_path);
1259 $repo_path = '';
1260 } else {
1261 $repo_path =~ s#^/+##;
1262 unless ($ra) {
1263 fatal("E: '$repo_path' is not a complete URL ",
1264 "and a separate URL is not specified");
1267 my $url = $ra->{url};
1268 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1269 my $k = "svn-remote.$gs->{repo_id}.url";
1270 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1271 if ($orig_url && ($orig_url ne $gs->{url})) {
1272 die "$k already set: $orig_url\n",
1273 "wanted to set to: $gs->{url}\n";
1275 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1276 my $remote_path = "$gs->{path}/$repo_path";
1277 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1278 $remote_path =~ s#/+#/#g;
1279 $remote_path =~ s#^/##g;
1280 $remote_path .= "/*" if $remote_path !~ /\*/;
1281 my ($n) = ($switch =~ /^--(\w+)/);
1282 if (length $pfx && $pfx !~ m#/$#) {
1283 die "--prefix='$pfx' must have a trailing slash '/'\n";
1285 command_noisy('config',
1286 '--add',
1287 "svn-remote.$gs->{repo_id}.$n",
1288 "$remote_path:refs/remotes/$pfx*" .
1289 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1292 sub verify_ref {
1293 my ($ref) = @_;
1294 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1295 { STDERR => 0 }); };
1298 sub get_tree_from_treeish {
1299 my ($treeish) = @_;
1300 # $treeish can be a symbolic ref, too:
1301 my $type = command_oneline(qw/cat-file -t/, $treeish);
1302 my $expected;
1303 while ($type eq 'tag') {
1304 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1306 if ($type eq 'commit') {
1307 $expected = (grep /^tree /, command(qw/cat-file commit/,
1308 $treeish))[0];
1309 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1310 die "Unable to get tree from $treeish\n" unless $expected;
1311 } elsif ($type eq 'tree') {
1312 $expected = $treeish;
1313 } else {
1314 die "$treeish is a $type, expected tree, tag or commit\n";
1316 return $expected;
1319 sub get_commit_entry {
1320 my ($treeish) = shift;
1321 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1322 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1323 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1324 open my $log_fh, '>', $commit_editmsg or croak $!;
1326 my $type = command_oneline(qw/cat-file -t/, $treeish);
1327 if ($type eq 'commit' || $type eq 'tag') {
1328 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1329 $type, $treeish);
1330 my $in_msg = 0;
1331 my $author;
1332 my $saw_from = 0;
1333 my $msgbuf = "";
1334 while (<$msg_fh>) {
1335 if (!$in_msg) {
1336 $in_msg = 1 if (/^\s*$/);
1337 $author = $1 if (/^author (.*>)/);
1338 } elsif (/^git-svn-id: /) {
1339 # skip this for now, we regenerate the
1340 # correct one on re-fetch anyways
1341 # TODO: set *:merge properties or like...
1342 } else {
1343 if (/^From:/ || /^Signed-off-by:/) {
1344 $saw_from = 1;
1346 $msgbuf .= $_;
1349 $msgbuf =~ s/\s+$//s;
1350 if ($Git::SVN::_add_author_from && defined($author)
1351 && !$saw_from) {
1352 $msgbuf .= "\n\nFrom: $author";
1354 print $log_fh $msgbuf or croak $!;
1355 command_close_pipe($msg_fh, $ctx);
1357 close $log_fh or croak $!;
1359 if ($_edit || ($type eq 'tree')) {
1360 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1361 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1363 rename $commit_editmsg, $commit_msg or croak $!;
1365 require Encode;
1366 # SVN requires messages to be UTF-8 when entering the repo
1367 local $/;
1368 open $log_fh, '<', $commit_msg or croak $!;
1369 binmode $log_fh;
1370 chomp($log_entry{log} = <$log_fh>);
1372 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1373 my $msg = $log_entry{log};
1375 eval { $msg = Encode::decode($enc, $msg, 1) };
1376 if ($@) {
1377 die "Could not decode as $enc:\n", $msg,
1378 "\nPerhaps you need to set i18n.commitencoding\n";
1381 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1382 die "Could not encode as UTF-8:\n$msg\n" if $@;
1384 $log_entry{log} = $msg;
1386 close $log_fh or croak $!;
1388 unlink $commit_msg;
1389 \%log_entry;
1392 sub s_to_file {
1393 my ($str, $file, $mode) = @_;
1394 open my $fd,'>',$file or croak $!;
1395 print $fd $str,"\n" or croak $!;
1396 close $fd or croak $!;
1397 chmod ($mode &~ umask, $file) if (defined $mode);
1400 sub file_to_s {
1401 my $file = shift;
1402 open my $fd,'<',$file or croak "$!: file: $file\n";
1403 local $/;
1404 my $ret = <$fd>;
1405 close $fd or croak $!;
1406 $ret =~ s/\s*$//s;
1407 return $ret;
1410 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1411 sub load_authors {
1412 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1413 my $log = $cmd eq 'log';
1414 while (<$authors>) {
1415 chomp;
1416 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1417 my ($user, $name, $email) = ($1, $2, $3);
1418 if ($log) {
1419 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1420 } else {
1421 $users{$user} = [$name, $email];
1424 close $authors or croak $!;
1427 # convert GetOpt::Long specs for use by git-config
1428 sub read_git_config {
1429 my $opts = shift;
1430 my @config_only;
1431 foreach my $o (keys %$opts) {
1432 # if we have mixedCase and a long option-only, then
1433 # it's a config-only variable that we don't need for
1434 # the command-line.
1435 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1436 my $v = $opts->{$o};
1437 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1438 $key =~ s/-//g;
1439 my $arg = 'git config';
1440 $arg .= ' --int' if ($o =~ /[:=]i$/);
1441 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1442 if (ref $v eq 'ARRAY') {
1443 chomp(my @tmp = `$arg --get-all svn.$key`);
1444 @$v = @tmp if @tmp;
1445 } else {
1446 chomp(my $tmp = `$arg --get svn.$key`);
1447 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1448 $$v = $tmp;
1452 delete @$opts{@config_only} if @config_only;
1455 sub extract_metadata {
1456 my $id = shift or return (undef, undef, undef);
1457 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1458 \s([a-f\d\-]+)$/ix);
1459 if (!defined $rev || !$uuid || !$url) {
1460 # some of the original repositories I made had
1461 # identifiers like this:
1462 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1464 return ($url, $rev, $uuid);
1467 sub cmt_metadata {
1468 return extract_metadata((grep(/^git-svn-id: /,
1469 command(qw/cat-file commit/, shift)))[-1]);
1472 sub cmt_sha2rev_batch {
1473 my %s2r;
1474 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1475 my $list = shift;
1477 foreach my $sha (@{$list}) {
1478 my $first = 1;
1479 my $size = 0;
1480 print $out $sha, "\n";
1482 while (my $line = <$in>) {
1483 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1484 last;
1485 } elsif ($first &&
1486 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1487 $first = 0;
1488 $size = $1;
1489 next;
1490 } elsif ($line =~ /^(git-svn-id: )/) {
1491 my (undef, $rev, undef) =
1492 extract_metadata($line);
1493 $s2r{$sha} = $rev;
1496 $size -= length($line);
1497 last if ($size == 0);
1501 command_close_bidi_pipe($pid, $in, $out, $ctx);
1503 return \%s2r;
1506 sub working_head_info {
1507 my ($head, $refs) = @_;
1508 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1509 my ($fh, $ctx) = command_output_pipe(@args, $head);
1510 my $hash;
1511 my %max;
1512 while (<$fh>) {
1513 if ( m{^commit ($::sha1)$} ) {
1514 unshift @$refs, $hash if $hash and $refs;
1515 $hash = $1;
1516 next;
1518 next unless s{^\s*(git-svn-id:)}{$1};
1519 my ($url, $rev, $uuid) = extract_metadata($_);
1520 if (defined $url && defined $rev) {
1521 next if $max{$url} and $max{$url} < $rev;
1522 if (my $gs = Git::SVN->find_by_url($url)) {
1523 my $c = $gs->rev_map_get($rev, $uuid);
1524 if ($c && $c eq $hash) {
1525 close $fh; # break the pipe
1526 return ($url, $rev, $uuid, $gs);
1527 } else {
1528 $max{$url} ||= $gs->rev_map_max;
1533 command_close_pipe($fh, $ctx);
1534 (undef, undef, undef, undef);
1537 sub read_commit_parents {
1538 my ($parents, $c) = @_;
1539 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1540 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1541 @{$parents->{$c}} = split(/ /, $p);
1544 sub linearize_history {
1545 my ($gs, $refs) = @_;
1546 my %parents;
1547 foreach my $c (@$refs) {
1548 read_commit_parents(\%parents, $c);
1551 my @linear_refs;
1552 my %skip = ();
1553 my $last_svn_commit = $gs->last_commit;
1554 foreach my $c (reverse @$refs) {
1555 next if $c eq $last_svn_commit;
1556 last if $skip{$c};
1558 unshift @linear_refs, $c;
1559 $skip{$c} = 1;
1561 # we only want the first parent to diff against for linear
1562 # history, we save the rest to inject when we finalize the
1563 # svn commit
1564 my $fp_a = verify_ref("$c~1");
1565 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1566 if (!$fp_a || !$fp_b) {
1567 die "Commit $c\n",
1568 "has no parent commit, and therefore ",
1569 "nothing to diff against.\n",
1570 "You should be working from a repository ",
1571 "originally created by git-svn\n";
1573 if ($fp_a ne $fp_b) {
1574 die "$c~1 = $fp_a, however parsing commit $c ",
1575 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1578 foreach my $p (@{$parents{$c}}) {
1579 $skip{$p} = 1;
1582 (\@linear_refs, \%parents);
1585 sub find_file_type_and_diff_status {
1586 my ($path) = @_;
1587 return ('dir', '') if $path eq '';
1589 my $diff_output =
1590 command_oneline(qw(diff --cached --name-status --), $path) || "";
1591 my $diff_status = (split(' ', $diff_output))[0] || "";
1593 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1595 return (undef, undef) if !$diff_status && !$ls_tree;
1597 if ($diff_status eq "A") {
1598 return ("link", $diff_status) if -l $path;
1599 return ("dir", $diff_status) if -d $path;
1600 return ("file", $diff_status);
1603 my $mode = (split(' ', $ls_tree))[0] || "";
1605 return ("link", $diff_status) if $mode eq "120000";
1606 return ("dir", $diff_status) if $mode eq "040000";
1607 return ("file", $diff_status);
1610 sub md5sum {
1611 my $arg = shift;
1612 my $ref = ref $arg;
1613 my $md5 = Digest::MD5->new();
1614 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1615 $md5->addfile($arg) or croak $!;
1616 } elsif ($ref eq 'SCALAR') {
1617 $md5->add($$arg) or croak $!;
1618 } elsif (!$ref) {
1619 $md5->add($arg) or croak $!;
1620 } else {
1621 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1623 return $md5->hexdigest();
1626 sub gc_directory {
1627 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1628 my $out_filename = $_ . ".gz";
1629 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1630 binmode $in_fh;
1631 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1632 die "Unable to open $out_filename: $!\n";
1634 my $res;
1635 while ($res = sysread($in_fh, my $str, 1024)) {
1636 $gz->gzwrite($str) or
1637 die "Unable to write: ".$gz->gzerror()."!\n";
1639 unlink $_ or die "unlink $File::Find::name: $!\n";
1640 } elsif (-f $_ && basename($_) eq "index") {
1641 unlink $_ or die "unlink $_: $!\n";
1645 package Git::SVN;
1646 use strict;
1647 use warnings;
1648 use Fcntl qw/:DEFAULT :seek/;
1649 use constant rev_map_fmt => 'NH40';
1650 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1651 $_repack $_repack_flags $_use_svm_props $_head
1652 $_use_svnsync_props $no_reuse_existing $_minimize_url
1653 $_use_log_author $_add_author_from $_localtime/;
1654 use Carp qw/croak/;
1655 use File::Path qw/mkpath/;
1656 use File::Copy qw/copy/;
1657 use IPC::Open3;
1658 use Memoize; # core since 5.8.0, Jul 2002
1659 use Memoize::Storable;
1661 my ($_gc_nr, $_gc_period);
1663 # properties that we do not log:
1664 my %SKIP_PROP;
1665 BEGIN {
1666 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1667 svn:special svn:executable
1668 svn:entry:committed-rev
1669 svn:entry:last-author
1670 svn:entry:uuid
1671 svn:entry:committed-date/;
1673 # some options are read globally, but can be overridden locally
1674 # per [svn-remote "..."] section. Command-line options will *NOT*
1675 # override options set in an [svn-remote "..."] section
1676 no strict 'refs';
1677 for my $option (qw/follow_parent no_metadata use_svm_props
1678 use_svnsync_props/) {
1679 my $key = $option;
1680 $key =~ tr/_//d;
1681 my $prop = "-$option";
1682 *$option = sub {
1683 my ($self) = @_;
1684 return $self->{$prop} if exists $self->{$prop};
1685 my $k = "svn-remote.$self->{repo_id}.$key";
1686 eval { command_oneline(qw/config --get/, $k) };
1687 if ($@) {
1688 $self->{$prop} = ${"Git::SVN::_$option"};
1689 } else {
1690 my $v = command_oneline(qw/config --bool/,$k);
1691 $self->{$prop} = $v eq 'false' ? 0 : 1;
1693 return $self->{$prop};
1699 my (%LOCKFILES, %INDEX_FILES);
1700 END {
1701 unlink keys %LOCKFILES if %LOCKFILES;
1702 unlink keys %INDEX_FILES if %INDEX_FILES;
1705 sub resolve_local_globs {
1706 my ($url, $fetch, $glob_spec) = @_;
1707 return unless defined $glob_spec;
1708 my $ref = $glob_spec->{ref};
1709 my $path = $glob_spec->{path};
1710 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1711 next unless m#^$ref->{regex}$#;
1712 my $p = $1;
1713 my $pathname = desanitize_refname($path->full_path($p));
1714 my $refname = desanitize_refname($ref->full_path($p));
1715 if (my $existing = $fetch->{$pathname}) {
1716 if ($existing ne $refname) {
1717 die "Refspec conflict:\n",
1718 "existing: $existing\n",
1719 " globbed: $refname\n";
1721 my $u = (::cmt_metadata("$refname"))[0];
1722 $u =~ s!^\Q$url\E(/|$)!! or die
1723 "$refname: '$url' not found in '$u'\n";
1724 if ($pathname ne $u) {
1725 warn "W: Refspec glob conflict ",
1726 "(ref: $refname):\n",
1727 "expected path: $pathname\n",
1728 " real path: $u\n",
1729 "Continuing ahead with $u\n";
1730 next;
1732 } else {
1733 $fetch->{$pathname} = $refname;
1738 sub parse_revision_argument {
1739 my ($base, $head) = @_;
1740 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1741 return ($base, $head);
1743 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1744 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1745 return ($head, $head) if ($::_revision eq 'HEAD');
1746 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1747 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1748 die "revision argument: $::_revision not understood by git-svn\n";
1751 sub fetch_all {
1752 my ($repo_id, $remotes) = @_;
1753 if (ref $repo_id) {
1754 my $gs = $repo_id;
1755 $repo_id = undef;
1756 $repo_id = $gs->{repo_id};
1758 $remotes ||= read_all_remotes();
1759 my $remote = $remotes->{$repo_id} or
1760 die "[svn-remote \"$repo_id\"] unknown\n";
1761 my $fetch = $remote->{fetch};
1762 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1763 my (@gs, @globs);
1764 my $ra = Git::SVN::Ra->new($url);
1765 my $uuid = $ra->get_uuid;
1766 my $head = $ra->get_latest_revnum;
1768 # ignore errors, $head revision may not even exist anymore
1769 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1770 warn "W: $@\n" if $@;
1772 my $base = defined $fetch ? $head : 0;
1774 # read the max revs for wildcard expansion (branches/*, tags/*)
1775 foreach my $t (qw/branches tags/) {
1776 defined $remote->{$t} or next;
1777 push @globs, @{$remote->{$t}};
1779 my $max_rev = eval { tmp_config(qw/--int --get/,
1780 "svn-remote.$repo_id.${t}-maxRev") };
1781 if (defined $max_rev && ($max_rev < $base)) {
1782 $base = $max_rev;
1783 } elsif (!defined $max_rev) {
1784 $base = 0;
1788 if ($fetch) {
1789 foreach my $p (sort keys %$fetch) {
1790 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1791 my $lr = $gs->rev_map_max;
1792 if (defined $lr) {
1793 $base = $lr if ($lr < $base);
1795 push @gs, $gs;
1799 ($base, $head) = parse_revision_argument($base, $head);
1800 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1803 sub read_all_remotes {
1804 my $r = {};
1805 my $use_svm_props = eval { command_oneline(qw/config --bool
1806 svn.useSvmProps/) };
1807 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1808 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1809 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1810 if (m!^(.+)\.fetch=$svn_refspec$!) {
1811 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1812 die("svn-remote.$remote: remote ref '$remote_ref' "
1813 . "must start with 'refs/'\n")
1814 unless $remote_ref =~ m{^refs/};
1815 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1816 $r->{$remote}->{svm} = {} if $use_svm_props;
1817 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1818 $r->{$1}->{svm} = {};
1819 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1820 $r->{$1}->{url} = $2;
1821 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1822 my ($remote, $t, $local_ref, $remote_ref) =
1823 ($1, $2, $3, $4);
1824 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1825 . "must start with 'refs/'\n")
1826 unless $remote_ref =~ m{^refs/};
1827 my $rs = {
1828 t => $t,
1829 remote => $remote,
1830 path => Git::SVN::GlobSpec->new($local_ref, 1),
1831 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1832 if (length($rs->{ref}->{right}) != 0) {
1833 die "The '*' glob character must be the last ",
1834 "character of '$remote_ref'\n";
1836 push @{ $r->{$remote}->{$t} }, $rs;
1840 map {
1841 if (defined $r->{$_}->{svm}) {
1842 my $svm;
1843 eval {
1844 my $section = "svn-remote.$_";
1845 $svm = {
1846 source => tmp_config('--get',
1847 "$section.svm-source"),
1848 replace => tmp_config('--get',
1849 "$section.svm-replace"),
1852 $r->{$_}->{svm} = $svm;
1854 } keys %$r;
1859 sub init_vars {
1860 $_gc_nr = $_gc_period = 1000;
1861 if (defined $_repack || defined $_repack_flags) {
1862 warn "Repack options are obsolete; they have no effect.\n";
1866 sub verify_remotes_sanity {
1867 return unless -d $ENV{GIT_DIR};
1868 my %seen;
1869 foreach (command(qw/config -l/)) {
1870 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1871 if ($seen{$1}) {
1872 die "Remote ref refs/remote/$1 is tracked by",
1873 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1874 "Please resolve this ambiguity in ",
1875 "your git configuration file before ",
1876 "continuing\n";
1878 $seen{$1} = $_;
1883 sub find_existing_remote {
1884 my ($url, $remotes) = @_;
1885 return undef if $no_reuse_existing;
1886 my $existing;
1887 foreach my $repo_id (keys %$remotes) {
1888 my $u = $remotes->{$repo_id}->{url} or next;
1889 next if $u ne $url;
1890 $existing = $repo_id;
1891 last;
1893 $existing;
1896 sub init_remote_config {
1897 my ($self, $url, $no_write) = @_;
1898 $url =~ s!/+$!!; # strip trailing slash
1899 my $r = read_all_remotes();
1900 my $existing = find_existing_remote($url, $r);
1901 if ($existing) {
1902 unless ($no_write) {
1903 print STDERR "Using existing ",
1904 "[svn-remote \"$existing\"]\n";
1906 $self->{repo_id} = $existing;
1907 } elsif ($_minimize_url) {
1908 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1909 $existing = find_existing_remote($min_url, $r);
1910 if ($existing) {
1911 unless ($no_write) {
1912 print STDERR "Using existing ",
1913 "[svn-remote \"$existing\"]\n";
1915 $self->{repo_id} = $existing;
1917 if ($min_url ne $url) {
1918 unless ($no_write) {
1919 print STDERR "Using higher level of URL: ",
1920 "$url => $min_url\n";
1922 my $old_path = $self->{path};
1923 $self->{path} = $url;
1924 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1925 if (length $old_path) {
1926 $self->{path} .= "/$old_path";
1928 $url = $min_url;
1931 my $orig_url;
1932 if (!$existing) {
1933 # verify that we aren't overwriting anything:
1934 $orig_url = eval {
1935 command_oneline('config', '--get',
1936 "svn-remote.$self->{repo_id}.url")
1938 if ($orig_url && ($orig_url ne $url)) {
1939 die "svn-remote.$self->{repo_id}.url already set: ",
1940 "$orig_url\nwanted to set to: $url\n";
1943 my ($xrepo_id, $xpath) = find_ref($self->refname);
1944 if (!$no_write && defined $xpath) {
1945 die "svn-remote.$xrepo_id.fetch already set to track ",
1946 "$xpath:", $self->refname, "\n";
1948 unless ($no_write) {
1949 command_noisy('config',
1950 "svn-remote.$self->{repo_id}.url", $url);
1951 $self->{path} =~ s{^/}{};
1952 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1953 command_noisy('config', '--add',
1954 "svn-remote.$self->{repo_id}.fetch",
1955 "$self->{path}:".$self->refname);
1957 $self->{url} = $url;
1960 sub find_by_url { # repos_root and, path are optional
1961 my ($class, $full_url, $repos_root, $path) = @_;
1963 return undef unless defined $full_url;
1964 remove_username($full_url);
1965 remove_username($repos_root) if defined $repos_root;
1966 my $remotes = read_all_remotes();
1967 if (defined $full_url && defined $repos_root && !defined $path) {
1968 $path = $full_url;
1969 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1971 foreach my $repo_id (keys %$remotes) {
1972 my $u = $remotes->{$repo_id}->{url} or next;
1973 remove_username($u);
1974 next if defined $repos_root && $repos_root ne $u;
1976 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1977 foreach my $t (qw/branches tags/) {
1978 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1979 resolve_local_globs($u, $fetch, $globspec);
1982 my $p = $path;
1983 my $rwr = rewrite_root({repo_id => $repo_id});
1984 my $svm = $remotes->{$repo_id}->{svm}
1985 if defined $remotes->{$repo_id}->{svm};
1986 unless (defined $p) {
1987 $p = $full_url;
1988 my $z = $u;
1989 my $prefix = '';
1990 if ($rwr) {
1991 $z = $rwr;
1992 remove_username($z);
1993 } elsif (defined $svm) {
1994 $z = $svm->{source};
1995 $prefix = $svm->{replace};
1996 $prefix =~ s#^\Q$u\E(?:/|$)##;
1997 $prefix =~ s#/$##;
1999 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2001 foreach my $f (keys %$fetch) {
2002 next if $f ne $p;
2003 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2006 undef;
2009 sub init {
2010 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2011 my $self = _new($class, $repo_id, $ref_id, $path);
2012 if (defined $url) {
2013 $self->init_remote_config($url, $no_write);
2015 $self;
2018 sub find_ref {
2019 my ($ref_id) = @_;
2020 foreach (command(qw/config -l/)) {
2021 next unless m!^svn-remote\.(.+)\.fetch=
2022 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2023 my ($repo_id, $path, $ref) = ($1, $2, $3);
2024 if ($ref eq $ref_id) {
2025 $path = '' if ($path =~ m#^\./?#);
2026 return ($repo_id, $path);
2029 (undef, undef, undef);
2032 sub new {
2033 my ($class, $ref_id, $repo_id, $path) = @_;
2034 if (defined $ref_id && !defined $repo_id && !defined $path) {
2035 ($repo_id, $path) = find_ref($ref_id);
2036 if (!defined $repo_id) {
2037 die "Could not find a \"svn-remote.*.fetch\" key ",
2038 "in the repository configuration matching: ",
2039 "$ref_id\n";
2042 my $self = _new($class, $repo_id, $ref_id, $path);
2043 if (!defined $self->{path} || !length $self->{path}) {
2044 my $fetch = command_oneline('config', '--get',
2045 "svn-remote.$repo_id.fetch",
2046 ":$ref_id\$") or
2047 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2048 "\":$ref_id\$\" in config\n";
2049 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2051 $self->{url} = command_oneline('config', '--get',
2052 "svn-remote.$repo_id.url") or
2053 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2054 $self->rebuild;
2055 $self;
2058 sub refname {
2059 my ($refname) = $_[0]->{ref_id} ;
2061 # It cannot end with a slash /, we'll throw up on this because
2062 # SVN can't have directories with a slash in their name, either:
2063 if ($refname =~ m{/$}) {
2064 die "ref: '$refname' ends with a trailing slash, this is ",
2065 "not permitted by git nor Subversion\n";
2068 # It cannot have ASCII control character space, tilde ~, caret ^,
2069 # colon :, question-mark ?, asterisk *, space, or open bracket [
2070 # anywhere.
2072 # Additionally, % must be escaped because it is used for escaping
2073 # and we want our escaped refname to be reversible
2074 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2076 # no slash-separated component can begin with a dot .
2077 # /.* becomes /%2E*
2078 $refname =~ s{/\.}{/%2E}g;
2080 # It cannot have two consecutive dots .. anywhere
2081 # .. becomes %2E%2E
2082 $refname =~ s{\.\.}{%2E%2E}g;
2084 return $refname;
2087 sub desanitize_refname {
2088 my ($refname) = @_;
2089 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2090 return $refname;
2093 sub svm_uuid {
2094 my ($self) = @_;
2095 return $self->{svm}->{uuid} if $self->svm;
2096 $self->ra;
2097 unless ($self->{svm}) {
2098 die "SVM UUID not cached, and reading remotely failed\n";
2100 $self->{svm}->{uuid};
2103 sub svm {
2104 my ($self) = @_;
2105 return $self->{svm} if $self->{svm};
2106 my $svm;
2107 # see if we have it in our config, first:
2108 eval {
2109 my $section = "svn-remote.$self->{repo_id}";
2110 $svm = {
2111 source => tmp_config('--get', "$section.svm-source"),
2112 uuid => tmp_config('--get', "$section.svm-uuid"),
2113 replace => tmp_config('--get', "$section.svm-replace"),
2116 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2117 $self->{svm} = $svm;
2119 $self->{svm};
2122 sub _set_svm_vars {
2123 my ($self, $ra) = @_;
2124 return $ra if $self->svm;
2126 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2127 "(svm:source, svm:uuid) ",
2128 "from the following URLs:\n" );
2129 sub read_svm_props {
2130 my ($self, $ra, $path, $r) = @_;
2131 my $props = ($ra->get_dir($path, $r))[2];
2132 my $src = $props->{'svm:source'};
2133 my $uuid = $props->{'svm:uuid'};
2134 return undef if (!$src || !$uuid);
2136 chomp($src, $uuid);
2138 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2139 or die "doesn't look right - svm:uuid is '$uuid'\n";
2141 # the '!' is used to mark the repos_root!/relative/path
2142 $src =~ s{/?!/?}{/};
2143 $src =~ s{/+$}{}; # no trailing slashes please
2144 # username is of no interest
2145 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2147 my $replace = $ra->{url};
2148 $replace .= "/$path" if length $path;
2150 my $section = "svn-remote.$self->{repo_id}";
2151 tmp_config("$section.svm-source", $src);
2152 tmp_config("$section.svm-replace", $replace);
2153 tmp_config("$section.svm-uuid", $uuid);
2154 $self->{svm} = {
2155 source => $src,
2156 uuid => $uuid,
2157 replace => $replace
2161 my $r = $ra->get_latest_revnum;
2162 my $path = $self->{path};
2163 my %tried;
2164 while (length $path) {
2165 unless ($tried{"$self->{url}/$path"}) {
2166 return $ra if $self->read_svm_props($ra, $path, $r);
2167 $tried{"$self->{url}/$path"} = 1;
2169 $path =~ s#/?[^/]+$##;
2171 die "Path: '$path' should be ''\n" if $path ne '';
2172 return $ra if $self->read_svm_props($ra, $path, $r);
2173 $tried{"$self->{url}/$path"} = 1;
2175 if ($ra->{repos_root} eq $self->{url}) {
2176 die @err, (map { " $_\n" } keys %tried), "\n";
2179 # nope, make sure we're connected to the repository root:
2180 my $ok;
2181 my @tried_b;
2182 $path = $ra->{svn_path};
2183 $ra = Git::SVN::Ra->new($ra->{repos_root});
2184 while (length $path) {
2185 unless ($tried{"$ra->{url}/$path"}) {
2186 $ok = $self->read_svm_props($ra, $path, $r);
2187 last if $ok;
2188 $tried{"$ra->{url}/$path"} = 1;
2190 $path =~ s#/?[^/]+$##;
2192 die "Path: '$path' should be ''\n" if $path ne '';
2193 $ok ||= $self->read_svm_props($ra, $path, $r);
2194 $tried{"$ra->{url}/$path"} = 1;
2195 if (!$ok) {
2196 die @err, (map { " $_\n" } keys %tried), "\n";
2198 Git::SVN::Ra->new($self->{url});
2201 sub svnsync {
2202 my ($self) = @_;
2203 return $self->{svnsync} if $self->{svnsync};
2205 if ($self->no_metadata) {
2206 die "Can't have both 'noMetadata' and ",
2207 "'useSvnsyncProps' options set!\n";
2209 if ($self->rewrite_root) {
2210 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2211 "options set!\n";
2213 if ($self->rewrite_uuid) {
2214 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2215 "options set!\n";
2218 my $svnsync;
2219 # see if we have it in our config, first:
2220 eval {
2221 my $section = "svn-remote.$self->{repo_id}";
2223 my $url = tmp_config('--get', "$section.svnsync-url");
2224 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2225 die "doesn't look right - svn:sync-from-url is '$url'\n";
2227 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2228 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2229 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2231 $svnsync = { url => $url, uuid => $uuid }
2233 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2234 return $self->{svnsync} = $svnsync;
2237 my $err = "useSvnsyncProps set, but failed to read " .
2238 "svnsync property: svn:sync-from-";
2239 my $rp = $self->ra->rev_proplist(0);
2241 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2242 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2243 die "doesn't look right - svn:sync-from-url is '$url'\n";
2245 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2246 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2247 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2249 my $section = "svn-remote.$self->{repo_id}";
2250 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2251 tmp_config('--add', "$section.svnsync-url", $url);
2252 return $self->{svnsync} = { url => $url, uuid => $uuid };
2255 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2256 # remote lookup (useful for 'git svn log').
2257 sub ra_uuid {
2258 my ($self) = @_;
2259 unless ($self->{ra_uuid}) {
2260 my $key = "svn-remote.$self->{repo_id}.uuid";
2261 my $uuid = eval { tmp_config('--get', $key) };
2262 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2263 $self->{ra_uuid} = $uuid;
2264 } else {
2265 die "ra_uuid called without URL\n" unless $self->{url};
2266 $self->{ra_uuid} = $self->ra->get_uuid;
2267 tmp_config('--add', $key, $self->{ra_uuid});
2270 $self->{ra_uuid};
2273 sub _set_repos_root {
2274 my ($self, $repos_root) = @_;
2275 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2276 $repos_root ||= $self->ra->{repos_root};
2277 tmp_config($k, $repos_root);
2278 $repos_root;
2281 sub repos_root {
2282 my ($self) = @_;
2283 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2284 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2287 sub ra {
2288 my ($self) = shift;
2289 my $ra = Git::SVN::Ra->new($self->{url});
2290 $self->_set_repos_root($ra->{repos_root});
2291 if ($self->use_svm_props && !$self->{svm}) {
2292 if ($self->no_metadata) {
2293 die "Can't have both 'noMetadata' and ",
2294 "'useSvmProps' options set!\n";
2295 } elsif ($self->use_svnsync_props) {
2296 die "Can't have both 'useSvnsyncProps' and ",
2297 "'useSvmProps' options set!\n";
2299 $ra = $self->_set_svm_vars($ra);
2300 $self->{-want_revprops} = 1;
2302 $ra;
2305 # prop_walk(PATH, REV, SUB)
2306 # -------------------------
2307 # Recursively traverse PATH at revision REV and invoke SUB for each
2308 # directory that contains a SVN property. SUB will be invoked as
2309 # follows: &SUB(gs, path, props); where `gs' is this instance of
2310 # Git::SVN, `path' the path to the directory where the properties
2311 # `props' were found. The `path' will be relative to point of checkout,
2312 # that is, if url://repo/trunk is the current Git branch, and that
2313 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2314 # as `path' (note the trailing `/').
2315 sub prop_walk {
2316 my ($self, $path, $rev, $sub) = @_;
2318 $path =~ s#^/##;
2319 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2320 $path =~ s#^/*#/#g;
2321 my $p = $path;
2322 # Strip the irrelevant part of the path.
2323 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2324 # Ensure the path is terminated by a `/'.
2325 $p =~ s#/*$#/#;
2327 # The properties contain all the internal SVN stuff nobody
2328 # (usually) cares about.
2329 my $interesting_props = 0;
2330 foreach (keys %{$props}) {
2331 # If it doesn't start with `svn:', it must be a
2332 # user-defined property.
2333 ++$interesting_props and next if $_ !~ /^svn:/;
2334 # FIXME: Fragile, if SVN adds new public properties,
2335 # this needs to be updated.
2336 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2337 |eol-style|mime-type
2338 |externals|needs-lock)$/x;
2340 &$sub($self, $p, $props) if $interesting_props;
2342 foreach (sort keys %$dirent) {
2343 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2344 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2348 sub last_rev { ($_[0]->last_rev_commit)[0] }
2349 sub last_commit { ($_[0]->last_rev_commit)[1] }
2351 # returns the newest SVN revision number and newest commit SHA1
2352 sub last_rev_commit {
2353 my ($self) = @_;
2354 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2355 return ($self->{last_rev}, $self->{last_commit});
2357 my $c = ::verify_ref($self->refname.'^0');
2358 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2359 my $rev = (::cmt_metadata($c))[1];
2360 if (defined $rev) {
2361 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2362 return ($rev, $c);
2365 my $map_path = $self->map_path;
2366 unless (-e $map_path) {
2367 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2368 return (undef, undef);
2370 my ($rev, $commit) = $self->rev_map_max(1);
2371 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2372 return ($rev, $commit);
2375 sub get_fetch_range {
2376 my ($self, $min, $max) = @_;
2377 $max ||= $self->ra->get_latest_revnum;
2378 $min ||= $self->rev_map_max;
2379 (++$min, $max);
2382 sub tmp_config {
2383 my (@args) = @_;
2384 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2385 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2386 if (! -f $config && -f $old_def_config) {
2387 rename $old_def_config, $config or
2388 die "Failed rename $old_def_config => $config: $!\n";
2390 my $old_config = $ENV{GIT_CONFIG};
2391 $ENV{GIT_CONFIG} = $config;
2392 $@ = undef;
2393 my @ret = eval {
2394 unless (-f $config) {
2395 mkfile($config);
2396 open my $fh, '>', $config or
2397 die "Can't open $config: $!\n";
2398 print $fh "; This file is used internally by ",
2399 "git-svn\n" or die
2400 "Couldn't write to $config: $!\n";
2401 print $fh "; You should not have to edit it\n" or
2402 die "Couldn't write to $config: $!\n";
2403 close $fh or die "Couldn't close $config: $!\n";
2405 command('config', @args);
2407 my $err = $@;
2408 if (defined $old_config) {
2409 $ENV{GIT_CONFIG} = $old_config;
2410 } else {
2411 delete $ENV{GIT_CONFIG};
2413 die $err if $err;
2414 wantarray ? @ret : $ret[0];
2417 sub tmp_index_do {
2418 my ($self, $sub) = @_;
2419 my $old_index = $ENV{GIT_INDEX_FILE};
2420 $ENV{GIT_INDEX_FILE} = $self->{index};
2421 $@ = undef;
2422 my @ret = eval {
2423 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2424 mkpath([$dir]) unless -d $dir;
2425 &$sub;
2427 my $err = $@;
2428 if (defined $old_index) {
2429 $ENV{GIT_INDEX_FILE} = $old_index;
2430 } else {
2431 delete $ENV{GIT_INDEX_FILE};
2433 die $err if $err;
2434 wantarray ? @ret : $ret[0];
2437 sub assert_index_clean {
2438 my ($self, $treeish) = @_;
2440 $self->tmp_index_do(sub {
2441 command_noisy('read-tree', $treeish) unless -e $self->{index};
2442 my $x = command_oneline('write-tree');
2443 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2444 /^tree ($::sha1)/mo);
2445 return if $y eq $x;
2447 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2448 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2449 command_noisy('read-tree', $treeish);
2450 $x = command_oneline('write-tree');
2451 if ($y ne $x) {
2452 ::fatal "trees ($treeish) $y != $x\n",
2453 "Something is seriously wrong...";
2458 sub get_commit_parents {
2459 my ($self, $log_entry) = @_;
2460 my (%seen, @ret, @tmp);
2461 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2462 if (my $ip = $self->{inject_parents}) {
2463 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2464 push @tmp, $commit;
2467 if (my $cur = ::verify_ref($self->refname.'^0')) {
2468 push @tmp, $cur;
2470 if (my $ipd = $self->{inject_parents_dcommit}) {
2471 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2472 push @tmp, @$commit;
2475 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2476 while (my $p = shift @tmp) {
2477 next if $seen{$p};
2478 $seen{$p} = 1;
2479 push @ret, $p;
2481 @ret;
2484 sub rewrite_root {
2485 my ($self) = @_;
2486 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2487 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2488 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2489 if ($rwr) {
2490 $rwr =~ s#/+$##;
2491 if ($rwr !~ m#^[a-z\+]+://#) {
2492 die "$rwr is not a valid URL (key: $k)\n";
2495 $self->{-rewrite_root} = $rwr;
2498 sub rewrite_uuid {
2499 my ($self) = @_;
2500 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2501 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2502 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2503 if ($rwid) {
2504 $rwid =~ s#/+$##;
2505 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2506 die "$rwid is not a valid UUID (key: $k)\n";
2509 $self->{-rewrite_uuid} = $rwid;
2512 sub metadata_url {
2513 my ($self) = @_;
2514 ($self->rewrite_root || $self->{url}) .
2515 (length $self->{path} ? '/' . $self->{path} : '');
2518 sub full_url {
2519 my ($self) = @_;
2520 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2524 sub set_commit_header_env {
2525 my ($log_entry) = @_;
2526 my %env;
2527 foreach my $ned (qw/NAME EMAIL DATE/) {
2528 foreach my $ac (qw/AUTHOR COMMITTER/) {
2529 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2533 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2534 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2535 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2537 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2538 ? $log_entry->{commit_name}
2539 : $log_entry->{name};
2540 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2541 ? $log_entry->{commit_email}
2542 : $log_entry->{email};
2543 \%env;
2546 sub restore_commit_header_env {
2547 my ($env) = @_;
2548 foreach my $ned (qw/NAME EMAIL DATE/) {
2549 foreach my $ac (qw/AUTHOR COMMITTER/) {
2550 my $k = "GIT_${ac}_${ned}";
2551 if (defined $env->{$k}) {
2552 $ENV{$k} = $env->{$k};
2553 } else {
2554 delete $ENV{$k};
2560 sub gc {
2561 command_noisy('gc', '--auto');
2564 sub do_git_commit {
2565 my ($self, $log_entry) = @_;
2566 my $lr = $self->last_rev;
2567 if (defined $lr && $lr >= $log_entry->{revision}) {
2568 die "Last fetched revision of ", $self->refname,
2569 " was r$lr, but we are about to fetch: ",
2570 "r$log_entry->{revision}!\n";
2572 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2573 croak "$log_entry->{revision} = $c already exists! ",
2574 "Why are we refetching it?\n";
2576 my $old_env = set_commit_header_env($log_entry);
2577 my $tree = $log_entry->{tree};
2578 if (!defined $tree) {
2579 $tree = $self->tmp_index_do(sub {
2580 command_oneline('write-tree') });
2582 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2584 my @exec = ('git', 'commit-tree', $tree);
2585 foreach ($self->get_commit_parents($log_entry)) {
2586 push @exec, '-p', $_;
2588 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2589 or croak $!;
2590 binmode $msg_fh;
2592 # we always get UTF-8 from SVN, but we may want our commits in
2593 # a different encoding.
2594 if (my $enc = Git::config('i18n.commitencoding')) {
2595 require Encode;
2596 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2598 print $msg_fh $log_entry->{log} or croak $!;
2599 restore_commit_header_env($old_env);
2600 unless ($self->no_metadata) {
2601 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2602 or croak $!;
2604 $msg_fh->flush == 0 or croak $!;
2605 close $msg_fh or croak $!;
2606 chomp(my $commit = do { local $/; <$out_fh> });
2607 close $out_fh or croak $!;
2608 waitpid $pid, 0;
2609 croak $? if $?;
2610 if ($commit !~ /^$::sha1$/o) {
2611 die "Failed to commit, invalid sha1: $commit\n";
2614 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2616 $self->{last_rev} = $log_entry->{revision};
2617 $self->{last_commit} = $commit;
2618 print "r$log_entry->{revision}" unless $::_q > 1;
2619 if (defined $log_entry->{svm_revision}) {
2620 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2621 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2622 0, $self->svm_uuid);
2624 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2625 if (--$_gc_nr == 0) {
2626 $_gc_nr = $_gc_period;
2627 gc();
2629 return $commit;
2632 sub match_paths {
2633 my ($self, $paths, $r) = @_;
2634 return 1 if $self->{path} eq '';
2635 if (my $path = $paths->{"/$self->{path}"}) {
2636 return ($path->{action} eq 'D') ? 0 : 1;
2638 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2639 if (grep /$self->{path_regex}/, keys %$paths) {
2640 return 1;
2642 my $c = '';
2643 foreach (split m#/#, $self->{path}) {
2644 $c .= "/$_";
2645 next unless ($paths->{$c} &&
2646 ($paths->{$c}->{action} =~ /^[AR]$/));
2647 if ($self->ra->check_path($self->{path}, $r) ==
2648 $SVN::Node::dir) {
2649 return 1;
2652 return 0;
2655 sub find_parent_branch {
2656 my ($self, $paths, $rev) = @_;
2657 return undef unless $self->follow_parent;
2658 unless (defined $paths) {
2659 my $err_handler = $SVN::Error::handler;
2660 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2661 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2662 sub { $paths = $_[0] });
2663 $SVN::Error::handler = $err_handler;
2665 return undef unless defined $paths;
2667 # look for a parent from another branch:
2668 my @b_path_components = split m#/#, $self->{path};
2669 my @a_path_components;
2670 my $i;
2671 while (@b_path_components) {
2672 $i = $paths->{'/'.join('/', @b_path_components)};
2673 last if $i && defined $i->{copyfrom_path};
2674 unshift(@a_path_components, pop(@b_path_components));
2676 return undef unless defined $i && defined $i->{copyfrom_path};
2677 my $branch_from = $i->{copyfrom_path};
2678 if (@a_path_components) {
2679 print STDERR "branch_from: $branch_from => ";
2680 $branch_from .= '/'.join('/', @a_path_components);
2681 print STDERR $branch_from, "\n";
2683 my $r = $i->{copyfrom_rev};
2684 my $repos_root = $self->ra->{repos_root};
2685 my $url = $self->ra->{url};
2686 my $new_url = $url . $branch_from;
2687 print STDERR "Found possible branch point: ",
2688 "$new_url => ", $self->full_url, ", $r\n"
2689 unless $::_q > 1;
2690 $branch_from =~ s#^/##;
2691 my $gs = $self->other_gs($new_url, $url,
2692 $branch_from, $r, $self->{ref_id});
2693 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2695 my ($base, $head);
2696 if (!defined $r0 || !defined $parent) {
2697 ($base, $head) = parse_revision_argument(0, $r);
2698 } else {
2699 if ($r0 < $r) {
2700 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2701 0, 1, sub { $base = $_[1] - 1 });
2704 if (defined $base && $base <= $r) {
2705 $gs->fetch($base, $r);
2707 ($r0, $parent) = $gs->find_rev_before($r, 1);
2709 if (defined $r0 && defined $parent) {
2710 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2711 unless $::_q > 1;
2712 my $ed;
2713 if ($self->ra->can_do_switch) {
2714 $self->assert_index_clean($parent);
2715 print STDERR "Following parent with do_switch\n"
2716 unless $::_q > 1;
2717 # do_switch works with svn/trunk >= r22312, but that
2718 # is not included with SVN 1.4.3 (the latest version
2719 # at the moment), so we can't rely on it
2720 $self->{last_rev} = $r0;
2721 $self->{last_commit} = $parent;
2722 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2723 $gs->ra->gs_do_switch($r0, $rev, $gs,
2724 $self->full_url, $ed)
2725 or die "SVN connection failed somewhere...\n";
2726 } elsif ($self->ra->trees_match($new_url, $r0,
2727 $self->full_url, $rev)) {
2728 print STDERR "Trees match:\n",
2729 " $new_url\@$r0\n",
2730 " ${\$self->full_url}\@$rev\n",
2731 "Following parent with no changes\n"
2732 unless $::_q > 1;
2733 $self->tmp_index_do(sub {
2734 command_noisy('read-tree', $parent);
2736 $self->{last_commit} = $parent;
2737 } else {
2738 print STDERR "Following parent with do_update\n"
2739 unless $::_q > 1;
2740 $ed = SVN::Git::Fetcher->new($self);
2741 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2742 or die "SVN connection failed somewhere...\n";
2744 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2745 return $self->make_log_entry($rev, [$parent], $ed);
2747 return undef;
2750 sub do_fetch {
2751 my ($self, $paths, $rev) = @_;
2752 my $ed;
2753 my ($last_rev, @parents);
2754 if (my $lc = $self->last_commit) {
2755 # we can have a branch that was deleted, then re-added
2756 # under the same name but copied from another path, in
2757 # which case we'll have multiple parents (we don't
2758 # want to break the original ref, nor lose copypath info):
2759 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2760 push @{$log_entry->{parents}}, $lc;
2761 return $log_entry;
2763 $ed = SVN::Git::Fetcher->new($self);
2764 $last_rev = $self->{last_rev};
2765 $ed->{c} = $lc;
2766 @parents = ($lc);
2767 } else {
2768 $last_rev = $rev;
2769 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2770 return $log_entry;
2772 $ed = SVN::Git::Fetcher->new($self);
2774 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2775 die "SVN connection failed somewhere...\n";
2777 $self->make_log_entry($rev, \@parents, $ed);
2780 sub mkemptydirs {
2781 my ($self, $r) = @_;
2783 sub scan {
2784 my ($r, $empty_dirs, $line) = @_;
2785 if (defined $r && $line =~ /^r(\d+)$/) {
2786 return 0 if $1 > $r;
2787 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2788 $empty_dirs->{$1} = 1;
2789 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2790 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2791 delete @$empty_dirs{@d};
2793 1; # continue
2796 my %empty_dirs = ();
2797 my $gz_file = "$self->{dir}/unhandled.log.gz";
2798 if (-f $gz_file) {
2799 if (!$can_compress) {
2800 warn "Compress::Zlib could not be found; ",
2801 "empty directories in $gz_file will not be read\n";
2802 } else {
2803 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2804 die "Unable to open $gz_file: $!\n";
2805 my $line;
2806 while ($gz->gzreadline($line) > 0) {
2807 scan($r, \%empty_dirs, $line) or last;
2809 $gz->gzclose;
2813 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2814 binmode $fh or croak "binmode: $!";
2815 while (<$fh>) {
2816 scan($r, \%empty_dirs, $_) or last;
2818 close $fh;
2821 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2822 foreach my $d (sort keys %empty_dirs) {
2823 $d = uri_decode($d);
2824 $d =~ s/$strip//;
2825 next if -d $d;
2826 if (-e _) {
2827 warn "$d exists but is not a directory\n";
2828 } else {
2829 print "creating empty directory: $d\n";
2830 mkpath([$d]);
2835 sub get_untracked {
2836 my ($self, $ed) = @_;
2837 my @out;
2838 my $h = $ed->{empty};
2839 foreach (sort keys %$h) {
2840 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2841 push @out, " $act: " . uri_encode($_);
2842 warn "W: $act: $_\n";
2844 foreach my $t (qw/dir_prop file_prop/) {
2845 $h = $ed->{$t} or next;
2846 foreach my $path (sort keys %$h) {
2847 my $ppath = $path eq '' ? '.' : $path;
2848 foreach my $prop (sort keys %{$h->{$path}}) {
2849 next if $SKIP_PROP{$prop};
2850 my $v = $h->{$path}->{$prop};
2851 my $t_ppath_prop = "$t: " .
2852 uri_encode($ppath) . ' ' .
2853 uri_encode($prop);
2854 if (defined $v) {
2855 push @out, " +$t_ppath_prop " .
2856 uri_encode($v);
2857 } else {
2858 push @out, " -$t_ppath_prop";
2863 foreach my $t (qw/absent_file absent_directory/) {
2864 $h = $ed->{$t} or next;
2865 foreach my $parent (sort keys %$h) {
2866 foreach my $path (sort @{$h->{$parent}}) {
2867 push @out, " $t: " .
2868 uri_encode("$parent/$path");
2869 warn "W: $t: $parent/$path ",
2870 "Insufficient permissions?\n";
2874 \@out;
2877 # parse_svn_date(DATE)
2878 # --------------------
2879 # Given a date (in UTC) from Subversion, return a string in the format
2880 # "<TZ Offset> <local date/time>" that Git will use.
2882 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2883 # is true we'll convert it to the local timezone instead.
2884 sub parse_svn_date {
2885 my $date = shift || return '+0000 1970-01-01 00:00:00';
2886 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2887 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2888 croak "Unable to parse date: $date\n";
2889 my $parsed_date; # Set next.
2891 if ($Git::SVN::_localtime) {
2892 # Translate the Subversion datetime to an epoch time.
2893 # Begin by switching ourselves to $date's timezone, UTC.
2894 my $old_env_TZ = $ENV{TZ};
2895 $ENV{TZ} = 'UTC';
2897 my $epoch_in_UTC =
2898 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2900 # Determine our local timezone (including DST) at the
2901 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2902 # value of TZ, if any, at the time we were run.
2903 if (defined $Git::SVN::Log::TZ) {
2904 $ENV{TZ} = $Git::SVN::Log::TZ;
2905 } else {
2906 delete $ENV{TZ};
2909 my $our_TZ =
2910 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2912 # This converts $epoch_in_UTC into our local timezone.
2913 my ($sec, $min, $hour, $mday, $mon, $year,
2914 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2916 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2917 $our_TZ, $year + 1900, $mon + 1,
2918 $mday, $hour, $min, $sec);
2920 # Reset us to the timezone in effect when we entered
2921 # this routine.
2922 if (defined $old_env_TZ) {
2923 $ENV{TZ} = $old_env_TZ;
2924 } else {
2925 delete $ENV{TZ};
2927 } else {
2928 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2931 return $parsed_date;
2934 sub other_gs {
2935 my ($self, $new_url, $url,
2936 $branch_from, $r, $old_ref_id) = @_;
2937 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2938 unless ($gs) {
2939 my $ref_id = $old_ref_id;
2940 $ref_id =~ s/\@\d+$//;
2941 $ref_id .= "\@$r";
2942 # just grow a tail if we're not unique enough :x
2943 $ref_id .= '-' while find_ref($ref_id);
2944 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2945 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2946 if ($u =~ s#^\Q$url\E(/|$)##) {
2947 $p = $u;
2948 $u = $url;
2949 $repo_id = $self->{repo_id};
2951 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2956 sub call_authors_prog {
2957 my ($orig_author) = @_;
2958 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2959 my $author = `$::_authors_prog $orig_author`;
2960 if ($? != 0) {
2961 die "$::_authors_prog failed with exit code $?\n"
2963 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2964 my ($name, $email) = ($1, $2);
2965 $email = undef if length $2 == 0;
2966 return [$name, $email];
2967 } else {
2968 die "Author: $orig_author: $::_authors_prog returned "
2969 . "invalid author format: $author\n";
2973 sub check_author {
2974 my ($author) = @_;
2975 if (!defined $author || length $author == 0) {
2976 $author = '(no author)';
2978 if (!defined $::users{$author}) {
2979 if (defined $::_authors_prog) {
2980 $::users{$author} = call_authors_prog($author);
2981 } elsif (defined $::_authors) {
2982 die "Author: $author not defined in $::_authors file\n";
2985 $author;
2988 sub find_extra_svk_parents {
2989 my ($self, $ed, $tickets, $parents) = @_;
2990 # aha! svk:merge property changed...
2991 my @tickets = split "\n", $tickets;
2992 my @known_parents;
2993 for my $ticket ( @tickets ) {
2994 my ($uuid, $path, $rev) = split /:/, $ticket;
2995 if ( $uuid eq $self->ra_uuid ) {
2996 my $url = $self->rewrite_root || $self->{url};
2997 my $repos_root = $url;
2998 my $branch_from = $path;
2999 $branch_from =~ s{^/}{};
3000 my $gs = $self->other_gs($repos_root."/".$branch_from,
3001 $url,
3002 $branch_from,
3003 $rev,
3004 $self->{ref_id});
3005 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3006 # wahey! we found it, but it might be
3007 # an old one (!)
3008 push @known_parents, [ $rev, $commit ];
3012 # Ordering matters; highest-numbered commit merge tickets
3013 # first, as they may account for later merge ticket additions
3014 # or changes.
3015 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3016 for my $parent ( @known_parents ) {
3017 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3018 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3019 my $new;
3020 while ( <$msg_fh> ) {
3021 $new=1;last;
3023 command_close_pipe($msg_fh, $ctx);
3024 if ( $new ) {
3025 print STDERR
3026 "Found merge parent (svk:merge ticket): $parent\n";
3027 push @$parents, $parent;
3032 sub lookup_svn_merge {
3033 my $uuid = shift;
3034 my $url = shift;
3035 my $merge = shift;
3037 my ($source, $revs) = split ":", $merge;
3038 my $path = $source;
3039 $path =~ s{^/}{};
3040 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3041 if ( !$gs ) {
3042 warn "Couldn't find revmap for $url$source\n";
3043 return;
3045 my @ranges = split ",", $revs;
3046 my ($tip, $tip_commit);
3047 my @merged_commit_ranges;
3048 # find the tip
3049 for my $range ( @ranges ) {
3050 my ($bottom, $top) = split "-", $range;
3051 $top ||= $bottom;
3052 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3053 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3055 unless ($top_commit and $bottom_commit) {
3056 warn "W:unknown path/rev in svn:mergeinfo "
3057 ."dirprop: $source:$range\n";
3058 next;
3061 push @merged_commit_ranges,
3062 "$bottom_commit^..$top_commit";
3064 if ( !defined $tip or $top > $tip ) {
3065 $tip = $top;
3066 $tip_commit = $top_commit;
3069 return ($tip_commit, @merged_commit_ranges);
3072 sub _rev_list {
3073 my ($msg_fh, $ctx) = command_output_pipe(
3074 "rev-list", @_,
3076 my @rv;
3077 while ( <$msg_fh> ) {
3078 chomp;
3079 push @rv, $_;
3081 command_close_pipe($msg_fh, $ctx);
3082 @rv;
3085 sub check_cherry_pick {
3086 my $base = shift;
3087 my $tip = shift;
3088 my @ranges = @_;
3089 my %commits = map { $_ => 1 }
3090 _rev_list("--no-merges", $tip, "--not", $base);
3091 for my $range ( @ranges ) {
3092 delete @commits{_rev_list($range)};
3094 for my $commit (keys %commits) {
3095 if (has_no_changes($commit)) {
3096 delete $commits{$commit};
3099 return (keys %commits);
3102 sub has_no_changes {
3103 my $commit = shift;
3105 my @revs = split / /, command_oneline(
3106 qw(rev-list --parents -1 -m), $commit);
3108 # Commits with no parents, e.g. the start of a partial branch,
3109 # have changes by definition.
3110 return 1 if (@revs < 2);
3112 # Commits with multiple parents, e.g a merge, have no changes
3113 # by definition.
3114 return 0 if (@revs > 2);
3116 return (command_oneline("rev-parse", "$commit^{tree}") eq
3117 command_oneline("rev-parse", "$commit~1^{tree}"));
3120 # The GIT_DIR environment variable is not always set until after the command
3121 # line arguments are processed, so we can't memoize in a BEGIN block.
3123 my $memoized = 0;
3125 sub memoize_svn_mergeinfo_functions {
3126 return if $memoized;
3127 $memoized = 1;
3129 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3130 mkpath([$cache_path]) unless -d $cache_path;
3132 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3133 "$cache_path/lookup_svn_merge.db", 'nstore';
3134 memoize 'lookup_svn_merge',
3135 SCALAR_CACHE => 'FAULT',
3136 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3139 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3140 "$cache_path/check_cherry_pick.db", 'nstore';
3141 memoize 'check_cherry_pick',
3142 SCALAR_CACHE => 'FAULT',
3143 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3146 tie my %has_no_changes_cache => 'Memoize::Storable',
3147 "$cache_path/has_no_changes.db", 'nstore';
3148 memoize 'has_no_changes',
3149 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3150 LIST_CACHE => 'FAULT',
3155 sub parents_exclude {
3156 my $parents = shift;
3157 my @commits = @_;
3158 return unless @commits;
3160 my @excluded;
3161 my $excluded;
3162 do {
3163 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3164 $excluded = command_oneline(@cmd);
3165 if ( $excluded ) {
3166 my @new;
3167 my $found;
3168 for my $commit ( @commits ) {
3169 if ( $commit eq $excluded ) {
3170 push @excluded, $commit;
3171 $found++;
3172 last;
3174 else {
3175 push @new, $commit;
3178 die "saw commit '$excluded' in rev-list output, "
3179 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3180 unless $found;
3181 @commits = @new;
3184 while ($excluded and @commits);
3186 return @excluded;
3190 # note: this function should only be called if the various dirprops
3191 # have actually changed
3192 sub find_extra_svn_parents {
3193 my ($self, $ed, $mergeinfo, $parents) = @_;
3194 # aha! svk:merge property changed...
3196 memoize_svn_mergeinfo_functions();
3198 # We first search for merged tips which are not in our
3199 # history. Then, we figure out which git revisions are in
3200 # that tip, but not this revision. If all of those revisions
3201 # are now marked as merge, we can add the tip as a parent.
3202 my @merges = split "\n", $mergeinfo;
3203 my @merge_tips;
3204 my $url = $self->rewrite_root || $self->{url};
3205 my $uuid = $self->ra_uuid;
3206 my %ranges;
3207 for my $merge ( @merges ) {
3208 my ($tip_commit, @ranges) =
3209 lookup_svn_merge( $uuid, $url, $merge );
3210 unless (!$tip_commit or
3211 grep { $_ eq $tip_commit } @$parents ) {
3212 push @merge_tips, $tip_commit;
3213 $ranges{$tip_commit} = \@ranges;
3214 } else {
3215 push @merge_tips, undef;
3219 my %excluded = map { $_ => 1 }
3220 parents_exclude($parents, grep { defined } @merge_tips);
3222 # check merge tips for new parents
3223 my @new_parents;
3224 for my $merge_tip ( @merge_tips ) {
3225 my $spec = shift @merges;
3226 next unless $merge_tip and $excluded{$merge_tip};
3228 my $ranges = $ranges{$merge_tip};
3230 # check out 'new' tips
3231 my $merge_base;
3232 eval {
3233 $merge_base = command_oneline(
3234 "merge-base",
3235 @$parents, $merge_tip,
3238 if ($@) {
3239 die "An error occurred during merge-base"
3240 unless $@->isa("Git::Error::Command");
3242 warn "W: Cannot find common ancestor between ".
3243 "@$parents and $merge_tip. Ignoring merge info.\n";
3244 next;
3247 # double check that there are no missing non-merge commits
3248 my (@incomplete) = check_cherry_pick(
3249 $merge_base, $merge_tip,
3250 @$ranges,
3253 if ( @incomplete ) {
3254 warn "W:svn cherry-pick ignored ($spec) - missing "
3255 .@incomplete." commit(s) (eg $incomplete[0])\n";
3256 } else {
3257 warn
3258 "Found merge parent (svn:mergeinfo prop): ",
3259 $merge_tip, "\n";
3260 push @new_parents, $merge_tip;
3264 # cater for merges which merge commits from multiple branches
3265 if ( @new_parents > 1 ) {
3266 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3267 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3268 next if $i == $j;
3269 next unless $new_parents[$i];
3270 next unless $new_parents[$j];
3271 my $revs = command_oneline(
3272 "rev-list", "-1",
3273 "$new_parents[$i]..$new_parents[$j]",
3275 if ( !$revs ) {
3276 undef($new_parents[$i]);
3281 push @$parents, grep { defined } @new_parents;
3284 sub make_log_entry {
3285 my ($self, $rev, $parents, $ed) = @_;
3286 my $untracked = $self->get_untracked($ed);
3288 my @parents = @$parents;
3289 my $ps = $ed->{path_strip} || "";
3290 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3291 my $props = $ed->{dir_prop}{$path};
3292 if ( $props->{"svk:merge"} ) {
3293 $self->find_extra_svk_parents
3294 ($ed, $props->{"svk:merge"}, \@parents);
3296 if ( $props->{"svn:mergeinfo"} ) {
3297 $self->find_extra_svn_parents
3298 ($ed,
3299 $props->{"svn:mergeinfo"},
3300 \@parents);
3304 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3305 print $un "r$rev\n" or croak $!;
3306 print $un $_, "\n" foreach @$untracked;
3307 my %log_entry = ( parents => \@parents, revision => $rev,
3308 log => '');
3310 my $headrev;
3311 my $logged = delete $self->{logged_rev_props};
3312 if (!$logged || $self->{-want_revprops}) {
3313 my $rp = $self->ra->rev_proplist($rev);
3314 foreach (sort keys %$rp) {
3315 my $v = $rp->{$_};
3316 if (/^svn:(author|date|log)$/) {
3317 $log_entry{$1} = $v;
3318 } elsif ($_ eq 'svm:headrev') {
3319 $headrev = $v;
3320 } else {
3321 print $un " rev_prop: ", uri_encode($_), ' ',
3322 uri_encode($v), "\n";
3325 } else {
3326 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3328 close $un or croak $!;
3330 $log_entry{date} = parse_svn_date($log_entry{date});
3331 $log_entry{log} .= "\n";
3332 my $author = $log_entry{author} = check_author($log_entry{author});
3333 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3334 : ($author, undef);
3336 my ($commit_name, $commit_email) = ($name, $email);
3337 if ($_use_log_author) {
3338 my $name_field;
3339 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3340 $name_field = $1;
3341 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3342 $name_field = $1;
3344 if (!defined $name_field) {
3345 if (!defined $email) {
3346 $email = $name;
3348 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3349 ($name, $email) = ($1, $2);
3350 } elsif ($name_field =~ /(.*)@/) {
3351 ($name, $email) = ($1, $name_field);
3352 } else {
3353 ($name, $email) = ($name_field, $name_field);
3356 if (defined $headrev && $self->use_svm_props) {
3357 if ($self->rewrite_root) {
3358 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3359 "options set!\n";
3361 if ($self->rewrite_uuid) {
3362 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3363 "options set!\n";
3365 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3366 # we don't want "SVM: initializing mirror for junk" ...
3367 return undef if $r == 0;
3368 my $svm = $self->svm;
3369 if ($uuid ne $svm->{uuid}) {
3370 die "UUID mismatch on SVM path:\n",
3371 "expected: $svm->{uuid}\n",
3372 " got: $uuid\n";
3374 my $full_url = $self->full_url;
3375 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3376 die "Failed to replace '$svm->{replace}' with ",
3377 "'$svm->{source}' in $full_url\n";
3378 # throw away username for storing in records
3379 remove_username($full_url);
3380 $log_entry{metadata} = "$full_url\@$r $uuid";
3381 $log_entry{svm_revision} = $r;
3382 $email ||= "$author\@$uuid";
3383 $commit_email ||= "$author\@$uuid";
3384 } elsif ($self->use_svnsync_props) {
3385 my $full_url = $self->svnsync->{url};
3386 $full_url .= "/$self->{path}" if length $self->{path};
3387 remove_username($full_url);
3388 my $uuid = $self->svnsync->{uuid};
3389 $log_entry{metadata} = "$full_url\@$rev $uuid";
3390 $email ||= "$author\@$uuid";
3391 $commit_email ||= "$author\@$uuid";