submodule: Fix t7400, t7405, t7406 for msysGit
[git/dscho.git] / git-svn.perl
blob4334b95f70fab5c3cb9e446a9d6c418748b95bca
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use 5.008;
5 use warnings;
6 use strict;
7 use vars qw/ $AUTHOR $VERSION
8 $sha1 $sha1_short $_revision $_repository
9 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16 } || '';
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
29 if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
34 $Git::SVN::Log::TZ = $ENV{TZ};
35 $ENV{TZ} = 'UTC';
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
39 sub _req_svn {
40 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
41 require SVN::Ra;
42 require SVN::Delta;
43 if ($SVN::Core::VERSION lt '1.1.0') {
44 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
47 my $can_compress = eval { require Compress::Zlib; 1};
48 push @Git::SVN::Ra::ISA, 'SVN::Ra';
49 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
50 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
51 use Carp qw/croak/;
52 use Digest::MD5;
53 use IO::File qw//;
54 use File::Basename qw/dirname basename/;
55 use File::Path qw/mkpath/;
56 use File::Spec;
57 use File::Find;
58 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
59 use IPC::Open3;
60 use Git;
61 use Memoize; # core since 5.8.0, Jul 2002
63 BEGIN {
64 # import functions from Git into our packages, en masse
65 no strict 'refs';
66 foreach (qw/command command_oneline command_noisy command_output_pipe
67 command_input_pipe command_close_pipe
68 command_bidi_pipe command_close_bidi_pipe/) {
69 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
70 Git::SVN::Migration Git::SVN::Log Git::SVN),
71 __PACKAGE__) {
72 *{"${package}::$_"} = \&{"Git::$_"};
75 Memoize::memoize 'Git::config';
76 Memoize::memoize 'Git::config_bool';
79 my ($SVN);
81 $sha1 = qr/[a-f\d]{40}/;
82 $sha1_short = qr/[a-f\d]{4,40}/;
83 my ($_stdin, $_help, $_edit,
84 $_message, $_file, $_branch_dest,
85 $_template, $_shared,
86 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
87 $_merge, $_strategy, $_dry_run, $_local,
88 $_prefix, $_no_checkout, $_url, $_verbose,
89 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
90 $Git::SVN::_follow_parent = 1;
91 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
92 $_q ||= 0;
93 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
94 'config-dir=s' => \$Git::SVN::Ra::config_dir,
95 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
97 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
98 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
99 'authors-file|A=s' => \$_authors,
100 'authors-prog=s' => \$_authors_prog,
101 'repack:i' => \$Git::SVN::_repack,
102 'noMetadata' => \$Git::SVN::_no_metadata,
103 'useSvmProps' => \$Git::SVN::_use_svm_props,
104 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
105 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
106 'no-checkout' => \$_no_checkout,
107 'quiet|q+' => \$_q,
108 'repack-flags|repack-args|repack-opts=s' =>
109 \$Git::SVN::_repack_flags,
110 'use-log-author' => \$Git::SVN::_use_log_author,
111 'add-author-from' => \$Git::SVN::_add_author_from,
112 'localtime' => \$Git::SVN::_localtime,
113 %remote_opts );
115 my ($_trunk, @_tags, @_branches, $_stdlayout);
116 my %icv;
117 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
118 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
119 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
120 'stdlayout|s' => \$_stdlayout,
121 'minimize-url|m!' => \$Git::SVN::_minimize_url,
122 'no-metadata' => sub { $icv{noMetadata} = 1 },
123 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
124 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
125 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
126 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
127 %remote_opts );
128 my %cmt_opts = ( 'edit|e' => \$_edit,
129 'rmdir' => \$SVN::Git::Editor::_rmdir,
130 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
131 'l=i' => \$SVN::Git::Editor::_rename_limit,
132 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
135 my %cmd = (
136 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
137 { 'revision|r=s' => \$_revision,
138 'fetch-all|all' => \$_fetch_all,
139 'parent|p' => \$_fetch_parent,
140 %fc_opts } ],
141 clone => [ \&cmd_clone, "Initialize and fetch revisions",
142 { 'revision|r=s' => \$_revision,
143 'preserve-empty-dirs' =>
144 \$SVN::Git::Fetcher::_preserve_empty_dirs,
145 'placeholder-filename=s' =>
146 \$SVN::Git::Fetcher::_placeholder_filename,
147 %fc_opts, %init_opts } ],
148 init => [ \&cmd_init, "Initialize a repo for tracking" .
149 " (requires URL argument)",
150 \%init_opts ],
151 'multi-init' => [ \&cmd_multi_init,
152 "Deprecated alias for ".
153 "'$0 init -T<trunk> -b<branches> -t<tags>'",
154 \%init_opts ],
155 dcommit => [ \&cmd_dcommit,
156 'Commit several diffs to merge with upstream',
157 { 'merge|m|M' => \$_merge,
158 'strategy|s=s' => \$_strategy,
159 'verbose|v' => \$_verbose,
160 'dry-run|n' => \$_dry_run,
161 'fetch-all|all' => \$_fetch_all,
162 'commit-url=s' => \$_commit_url,
163 'revision|r=i' => \$_revision,
164 'no-rebase' => \$_no_rebase,
165 'mergeinfo=s' => \$_merge_info,
166 'interactive|i' => \$_interactive,
167 %cmt_opts, %fc_opts } ],
168 branch => [ \&cmd_branch,
169 'Create a branch in the SVN repository',
170 { 'message|m=s' => \$_message,
171 'destination|d=s' => \$_branch_dest,
172 'dry-run|n' => \$_dry_run,
173 'tag|t' => \$_tag,
174 'username=s' => \$Git::SVN::Prompt::_username,
175 'commit-url=s' => \$_commit_url } ],
176 tag => [ sub { $_tag = 1; cmd_branch(@_) },
177 'Create a tag in the SVN repository',
178 { 'message|m=s' => \$_message,
179 'destination|d=s' => \$_branch_dest,
180 'dry-run|n' => \$_dry_run,
181 'username=s' => \$Git::SVN::Prompt::_username,
182 'commit-url=s' => \$_commit_url } ],
183 'set-tree' => [ \&cmd_set_tree,
184 "Set an SVN repository to a git tree-ish",
185 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
186 'create-ignore' => [ \&cmd_create_ignore,
187 'Create a .gitignore per svn:ignore',
188 { 'revision|r=i' => \$_revision
189 } ],
190 'mkdirs' => [ \&cmd_mkdirs ,
191 "recreate empty directories after a checkout",
192 { 'revision|r=i' => \$_revision } ],
193 'propget' => [ \&cmd_propget,
194 'Print the value of a property on a file or directory',
195 { 'revision|r=i' => \$_revision } ],
196 'proplist' => [ \&cmd_proplist,
197 'List all properties of a file or directory',
198 { 'revision|r=i' => \$_revision } ],
199 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
200 { 'revision|r=i' => \$_revision
201 } ],
202 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
203 { 'revision|r=i' => \$_revision
204 } ],
205 'multi-fetch' => [ \&cmd_multi_fetch,
206 "Deprecated alias for $0 fetch --all",
207 { 'revision|r=s' => \$_revision, %fc_opts } ],
208 'migrate' => [ sub { },
209 # no-op, we automatically run this anyways,
210 'Migrate configuration/metadata/layout from
211 previous versions of git-svn',
212 { 'minimize' => \$Git::SVN::Migration::_minimize,
213 %remote_opts } ],
214 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
215 { 'limit=i' => \$Git::SVN::Log::limit,
216 'revision|r=s' => \$_revision,
217 'verbose|v' => \$Git::SVN::Log::verbose,
218 'incremental' => \$Git::SVN::Log::incremental,
219 'oneline' => \$Git::SVN::Log::oneline,
220 'show-commit' => \$Git::SVN::Log::show_commit,
221 'non-recursive' => \$Git::SVN::Log::non_recursive,
222 'authors-file|A=s' => \$_authors,
223 'color' => \$Git::SVN::Log::color,
224 'pager=s' => \$Git::SVN::Log::pager
225 } ],
226 'find-rev' => [ \&cmd_find_rev,
227 "Translate between SVN revision numbers and tree-ish",
228 {} ],
229 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
230 { 'merge|m|M' => \$_merge,
231 'verbose|v' => \$_verbose,
232 'strategy|s=s' => \$_strategy,
233 'local|l' => \$_local,
234 'fetch-all|all' => \$_fetch_all,
235 'dry-run|n' => \$_dry_run,
236 %fc_opts } ],
237 'commit-diff' => [ \&cmd_commit_diff,
238 'Commit a diff between two trees',
239 { 'message|m=s' => \$_message,
240 'file|F=s' => \$_file,
241 'revision|r=s' => \$_revision,
242 %cmt_opts } ],
243 'info' => [ \&cmd_info,
244 "Show info about the latest SVN revision
245 on the current branch",
246 { 'url' => \$_url, } ],
247 'blame' => [ \&Git::SVN::Log::cmd_blame,
248 "Show what revision and author last modified each line of a file",
249 { 'git-format' => \$_git_format } ],
250 'reset' => [ \&cmd_reset,
251 "Undo fetches back to the specified SVN revision",
252 { 'revision|r=s' => \$_revision,
253 'parent|p' => \$_fetch_parent } ],
254 'gc' => [ \&cmd_gc,
255 "Compress unhandled.log files in .git/svn and remove " .
256 "index files in .git/svn",
257 {} ],
260 use Term::ReadLine;
261 package FakeTerm;
262 sub new {
263 my ($class, $reason) = @_;
264 return bless \$reason, shift;
266 sub readline {
267 my $self = shift;
268 die "Cannot use readline on FakeTerm: $$self";
270 package main;
272 my $term = eval {
273 $ENV{"GIT_SVN_NOTTY"}
274 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
275 : new Term::ReadLine 'git-svn';
277 if ($@) {
278 $term = new FakeTerm "$@: going non-interactive";
281 my $cmd;
282 for (my $i = 0; $i < @ARGV; $i++) {
283 if (defined $cmd{$ARGV[$i]}) {
284 $cmd = $ARGV[$i];
285 splice @ARGV, $i, 1;
286 last;
287 } elsif ($ARGV[$i] eq 'help') {
288 $cmd = $ARGV[$i+1];
289 usage(0);
293 # make sure we're always running at the top-level working directory
294 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
295 unless (-d $ENV{GIT_DIR}) {
296 if ($git_dir_user_set) {
297 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
298 "but it is not a directory\n";
300 my $git_dir = delete $ENV{GIT_DIR};
301 my $cdup = undef;
302 git_cmd_try {
303 $cdup = command_oneline(qw/rev-parse --show-cdup/);
304 $git_dir = '.' unless ($cdup);
305 chomp $cdup if ($cdup);
306 $cdup = "." unless ($cdup && length $cdup);
307 } "Already at toplevel, but $git_dir not found\n";
308 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
309 unless (-d $git_dir) {
310 die "$git_dir still not found after going to ",
311 "'$cdup'\n";
313 $ENV{GIT_DIR} = $git_dir;
315 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
318 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
320 read_git_config(\%opts);
321 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
322 Getopt::Long::Configure('pass_through');
324 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
325 'minimize-connections' => \$Git::SVN::Migration::_minimize,
326 'id|i=s' => \$Git::SVN::default_ref_id,
327 'svn-remote|remote|R=s' => sub {
328 $Git::SVN::no_reuse_existing = 1;
329 $Git::SVN::default_repo_id = $_[1] });
330 exit 1 if (!$rv && $cmd && $cmd ne 'log');
332 usage(0) if $_help;
333 version() if $_version;
334 usage(1) unless defined $cmd;
335 load_authors() if $_authors;
336 if (defined $_authors_prog) {
337 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
340 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
341 Git::SVN::Migration::migration_check();
343 Git::SVN::init_vars();
344 eval {
345 Git::SVN::verify_remotes_sanity();
346 $cmd{$cmd}->[0]->(@ARGV);
348 fatal $@ if $@;
349 post_fetch_checkout();
350 exit 0;
352 ####################### primary functions ######################
353 sub usage {
354 my $exit = shift || 0;
355 my $fd = $exit ? \*STDERR : \*STDOUT;
356 print $fd <<"";
357 git-svn - bidirectional operations between a single Subversion tree and git
358 Usage: git svn <command> [options] [arguments]\n
360 print $fd "Available commands:\n" unless $cmd;
362 foreach (sort keys %cmd) {
363 next if $cmd && $cmd ne $_;
364 next if /^multi-/; # don't show deprecated commands
365 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
366 foreach (sort keys %{$cmd{$_}->[2]}) {
367 # mixed-case options are for .git/config only
368 next if /[A-Z]/ && /^[a-z]+$/i;
369 # prints out arguments as they should be passed:
370 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
371 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
372 "--$_" : "-$_" }
373 split /\|/,$_)," $x\n";
376 print $fd <<"";
377 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
378 arbitrary identifier if you're tracking multiple SVN branches/repositories in
379 one git repository and want to keep them separate. See git-svn(1) for more
380 information.
382 exit $exit;
385 sub version {
386 ::_req_svn();
387 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
388 exit 0;
391 sub ask {
392 my ($prompt, %arg) = @_;
393 my $valid_re = $arg{valid_re};
394 my $default = $arg{default};
395 my $resp;
396 my $i = 0;
398 if ( !( defined($term->IN)
399 && defined( fileno($term->IN) )
400 && defined( $term->OUT )
401 && defined( fileno($term->OUT) ) ) ){
402 return defined($default) ? $default : undef;
405 while ($i++ < 10) {
406 $resp = $term->readline($prompt);
407 if (!defined $resp) { # EOF
408 print "\n";
409 return defined $default ? $default : undef;
411 if ($resp eq '' and defined $default) {
412 return $default;
414 if (!defined $valid_re or $resp =~ /$valid_re/) {
415 return $resp;
418 return undef;
421 sub do_git_init_db {
422 unless (-d $ENV{GIT_DIR}) {
423 my @init_db = ('init');
424 push @init_db, "--template=$_template" if defined $_template;
425 if (defined $_shared) {
426 if ($_shared =~ /[a-z]/) {
427 push @init_db, "--shared=$_shared";
428 } else {
429 push @init_db, "--shared";
432 command_noisy(@init_db);
433 $_repository = Git->repository(Repository => ".git");
435 my $set;
436 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
437 foreach my $i (keys %icv) {
438 die "'$set' and '$i' cannot both be set\n" if $set;
439 next unless defined $icv{$i};
440 command_noisy('config', "$pfx.$i", $icv{$i});
441 $set = $i;
443 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
444 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
445 if defined $$ignore_paths_regex;
446 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
447 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
448 if defined $$ignore_refs_regex;
450 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
451 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
452 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
453 command_noisy('config', "$pfx.placeholder-filename", $$fname);
457 sub init_subdir {
458 my $repo_path = shift or return;
459 mkpath([$repo_path]) unless -d $repo_path;
460 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
461 $ENV{GIT_DIR} = '.git';
462 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
465 sub cmd_clone {
466 my ($url, $path) = @_;
467 if (!defined $path &&
468 (defined $_trunk || @_branches || @_tags ||
469 defined $_stdlayout) &&
470 $url !~ m#^[a-z\+]+://#) {
471 $path = $url;
473 $path = basename($url) if !defined $path || !length $path;
474 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
475 cmd_init($url, $path);
476 command_oneline('config', 'svn.authorsfile', $authors_absolute)
477 if $_authors;
478 Git::SVN::fetch_all($Git::SVN::default_repo_id);
481 sub cmd_init {
482 if (defined $_stdlayout) {
483 $_trunk = 'trunk' if (!defined $_trunk);
484 @_tags = 'tags' if (! @_tags);
485 @_branches = 'branches' if (! @_branches);
487 if (defined $_trunk || @_branches || @_tags) {
488 return cmd_multi_init(@_);
490 my $url = shift or die "SVN repository location required ",
491 "as a command-line argument\n";
492 $url = canonicalize_url($url);
493 init_subdir(@_);
494 do_git_init_db();
496 if ($Git::SVN::_minimize_url eq 'unset') {
497 $Git::SVN::_minimize_url = 0;
500 Git::SVN->init($url);
503 sub cmd_fetch {
504 if (grep /^\d+=./, @_) {
505 die "'<rev>=<commit>' fetch arguments are ",
506 "no longer supported.\n";
508 my ($remote) = @_;
509 if (@_ > 1) {
510 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
512 $Git::SVN::no_reuse_existing = undef;
513 if ($_fetch_parent) {
514 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
515 unless ($gs) {
516 die "Unable to determine upstream SVN information from ",
517 "working tree history\n";
519 # just fetch, don't checkout.
520 $_no_checkout = 'true';
521 $_fetch_all ? $gs->fetch_all : $gs->fetch;
522 } elsif ($_fetch_all) {
523 cmd_multi_fetch();
524 } else {
525 $remote ||= $Git::SVN::default_repo_id;
526 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
530 sub cmd_set_tree {
531 my (@commits) = @_;
532 if ($_stdin || !@commits) {
533 print "Reading from stdin...\n";
534 @commits = ();
535 while (<STDIN>) {
536 if (/\b($sha1_short)\b/o) {
537 unshift @commits, $1;
541 my @revs;
542 foreach my $c (@commits) {
543 my @tmp = command('rev-parse',$c);
544 if (scalar @tmp == 1) {
545 push @revs, $tmp[0];
546 } elsif (scalar @tmp > 1) {
547 push @revs, reverse(command('rev-list',@tmp));
548 } else {
549 fatal "Failed to rev-parse $c";
552 my $gs = Git::SVN->new;
553 my ($r_last, $cmt_last) = $gs->last_rev_commit;
554 $gs->fetch;
555 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
556 fatal "There are new revisions that were fetched ",
557 "and need to be merged (or acknowledged) ",
558 "before committing.\nlast rev: $r_last\n",
559 " current: $gs->{last_rev}";
561 $gs->set_tree($_) foreach @revs;
562 print "Done committing ",scalar @revs," revisions to SVN\n";
563 unlink $gs->{index};
566 sub split_merge_info_range {
567 my ($range) = @_;
568 if ($range =~ /(\d+)-(\d+)/) {
569 return (int($1), int($2));
570 } else {
571 return (int($range), int($range));
575 sub combine_ranges {
576 my ($in) = @_;
578 my @fnums = ();
579 my @arr = split(/,/, $in);
580 for my $element (@arr) {
581 my ($start, $end) = split_merge_info_range($element);
582 push @fnums, $start;
585 my @sorted = @arr [ sort {
586 $fnums[$a] <=> $fnums[$b]
587 } 0..$#arr ];
589 my @return = ();
590 my $last = -1;
591 my $first = -1;
592 for my $element (@sorted) {
593 my ($start, $end) = split_merge_info_range($element);
595 if ($last == -1) {
596 $first = $start;
597 $last = $end;
598 next;
600 if ($start <= $last+1) {
601 if ($end > $last) {
602 $last = $end;
604 next;
606 if ($first == $last) {
607 push @return, "$first";
608 } else {
609 push @return, "$first-$last";
611 $first = $start;
612 $last = $end;
615 if ($first != -1) {
616 if ($first == $last) {
617 push @return, "$first";
618 } else {
619 push @return, "$first-$last";
623 return join(',', @return);
626 sub merge_revs_into_hash {
627 my ($hash, $minfo) = @_;
628 my @lines = split(' ', $minfo);
630 for my $line (@lines) {
631 my ($branchpath, $revs) = split(/:/, $line);
633 if (exists($hash->{$branchpath})) {
634 # Merge the two revision sets
635 my $combined = "$hash->{$branchpath},$revs";
636 $hash->{$branchpath} = combine_ranges($combined);
637 } else {
638 # Just do range combining for consolidation
639 $hash->{$branchpath} = combine_ranges($revs);
644 sub merge_merge_info {
645 my ($mergeinfo_one, $mergeinfo_two) = @_;
646 my %result_hash = ();
648 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
649 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
651 my $result = '';
652 # Sort below is for consistency's sake
653 for my $branchname (sort keys(%result_hash)) {
654 my $revlist = $result_hash{$branchname};
655 $result .= "$branchname:$revlist\n"
657 return $result;
660 sub populate_merge_info {
661 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
663 my %parentshash;
664 read_commit_parents(\%parentshash, $d);
665 my @parents = @{$parentshash{$d}};
666 if ($#parents > 0) {
667 # Merge commit
668 my $all_parents_ok = 1;
669 my $aggregate_mergeinfo = '';
670 my $rooturl = $gs->repos_root;
672 if (defined($rewritten_parent)) {
673 # Replace first parent with newly-rewritten version
674 shift @parents;
675 unshift @parents, $rewritten_parent;
678 foreach my $parent (@parents) {
679 my ($branchurl, $svnrev, $paruuid) =
680 cmt_metadata($parent);
682 unless (defined($svnrev)) {
683 # Should have been caught be preflight check
684 fatal "merge commit $d has ancestor $parent, but that change "
685 ."does not have git-svn metadata!";
687 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
688 fatal "commit $parent git-svn metadata changed mid-run!";
690 my $branchpath = $1;
692 my $ra = Git::SVN::Ra->new($branchurl);
693 my (undef, undef, $props) =
694 $ra->get_dir(canonicalize_path("."), $svnrev);
695 my $par_mergeinfo = $props->{'svn:mergeinfo'};
696 unless (defined $par_mergeinfo) {
697 $par_mergeinfo = '';
699 # Merge previous mergeinfo values
700 $aggregate_mergeinfo =
701 merge_merge_info($aggregate_mergeinfo,
702 $par_mergeinfo, 0);
704 next if $parent eq $parents[0]; # Skip first parent
705 # Add new changes being placed in tree by merge
706 my @cmd = (qw/rev-list --reverse/,
707 $parent, qw/--not/);
708 foreach my $par (@parents) {
709 unless ($par eq $parent) {
710 push @cmd, $par;
713 my @revsin = ();
714 my ($revlist, $ctx) = command_output_pipe(@cmd);
715 while (<$revlist>) {
716 my $irev = $_;
717 chomp $irev;
718 my (undef, $csvnrev, undef) =
719 cmt_metadata($irev);
720 unless (defined $csvnrev) {
721 # A child is missing SVN annotations...
722 # this might be OK, or might not be.
723 warn "W:child $irev is merged into revision "
724 ."$d but does not have git-svn metadata. "
725 ."This means git-svn cannot determine the "
726 ."svn revision numbers to place into the "
727 ."svn:mergeinfo property. You must ensure "
728 ."a branch is entirely committed to "
729 ."SVN before merging it in order for "
730 ."svn:mergeinfo population to function "
731 ."properly";
733 push @revsin, $csvnrev;
735 command_close_pipe($revlist, $ctx);
737 last unless $all_parents_ok;
739 # We now have a list of all SVN revnos which are
740 # merged by this particular parent. Integrate them.
741 next if $#revsin == -1;
742 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
743 $aggregate_mergeinfo =
744 merge_merge_info($aggregate_mergeinfo,
745 $newmergeinfo, 1);
747 if ($all_parents_ok and $aggregate_mergeinfo) {
748 return $aggregate_mergeinfo;
752 return undef;
755 sub cmd_dcommit {
756 my $head = shift;
757 command_noisy(qw/update-index --refresh/);
758 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
759 'Cannot dcommit with a dirty index. Commit your changes first, '
760 . "or stash them with `git stash'.\n";
761 $head ||= 'HEAD';
763 my $old_head;
764 if ($head ne 'HEAD') {
765 $old_head = eval {
766 command_oneline([qw/symbolic-ref -q HEAD/])
768 if ($old_head) {
769 $old_head =~ s{^refs/heads/}{};
770 } else {
771 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
773 command(['checkout', $head], STDERR => 0);
776 my @refs;
777 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
778 unless ($gs) {
779 die "Unable to determine upstream SVN information from ",
780 "$head history.\nPerhaps the repository is empty.";
783 if (defined $_commit_url) {
784 $url = $_commit_url;
785 } else {
786 $url = eval { command_oneline('config', '--get',
787 "svn-remote.$gs->{repo_id}.commiturl") };
788 if (!$url) {
789 $url = $gs->full_pushurl
793 my $last_rev = $_revision if defined $_revision;
794 if ($url) {
795 print "Committing to $url ...\n";
797 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
798 if ($_no_rebase && scalar(@$linear_refs) > 1) {
799 warn "Attempting to commit more than one change while ",
800 "--no-rebase is enabled.\n",
801 "If these changes depend on each other, re-running ",
802 "without --no-rebase may be required."
805 if (defined $_interactive){
806 my $ask_default = "y";
807 foreach my $d (@$linear_refs){
808 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
809 while (<$fh>){
810 print $_;
812 command_close_pipe($fh, $ctx);
813 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
814 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
815 default => $ask_default);
816 die "Commit this patch reply required" unless defined $_;
817 if (/^[nq]/i) {
818 exit(0);
819 } elsif (/^a/i) {
820 last;
825 my $expect_url = $url;
827 my $push_merge_info = eval {
828 command_oneline(qw/config --get svn.pushmergeinfo/)
830 if (not defined($push_merge_info)
831 or $push_merge_info eq "false"
832 or $push_merge_info eq "no"
833 or $push_merge_info eq "never") {
834 $push_merge_info = 0;
837 unless (defined($_merge_info) || ! $push_merge_info) {
838 # Preflight check of changes to ensure no issues with mergeinfo
839 # This includes check for uncommitted-to-SVN parents
840 # (other than the first parent, which we will handle),
841 # information from different SVN repos, and paths
842 # which are not underneath this repository root.
843 my $rooturl = $gs->repos_root;
844 foreach my $d (@$linear_refs) {
845 my %parentshash;
846 read_commit_parents(\%parentshash, $d);
847 my @realparents = @{$parentshash{$d}};
848 if ($#realparents > 0) {
849 # Merge commit
850 shift @realparents; # Remove/ignore first parent
851 foreach my $parent (@realparents) {
852 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
853 unless (defined $paruuid) {
854 # A parent is missing SVN annotations...
855 # abort the whole operation.
856 fatal "$parent is merged into revision $d, "
857 ."but does not have git-svn metadata. "
858 ."Either dcommit the branch or use a "
859 ."local cherry-pick, FF merge, or rebase "
860 ."instead of an explicit merge commit.";
863 unless ($paruuid eq $uuid) {
864 # Parent has SVN metadata from different repository
865 fatal "merge parent $parent for change $d has "
866 ."git-svn uuid $paruuid, while current change "
867 ."has uuid $uuid!";
870 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
871 # This branch is very strange indeed.
872 fatal "merge parent $parent for $d is on branch "
873 ."$branchurl, which is not under the "
874 ."git-svn root $rooturl!";
881 my $rewritten_parent;
882 Git::SVN::remove_username($expect_url);
883 if (defined($_merge_info)) {
884 $_merge_info =~ tr{ }{\n};
886 while (1) {
887 my $d = shift @$linear_refs or last;
888 unless (defined $last_rev) {
889 (undef, $last_rev, undef) = cmt_metadata("$d~1");
890 unless (defined $last_rev) {
891 fatal "Unable to extract revision information ",
892 "from commit $d~1";
895 if ($_dry_run) {
896 print "diff-tree $d~1 $d\n";
897 } else {
898 my $cmt_rev;
900 unless (defined($_merge_info) || ! $push_merge_info) {
901 $_merge_info = populate_merge_info($d, $gs,
902 $uuid,
903 $linear_refs,
904 $rewritten_parent);
907 my %ed_opts = ( r => $last_rev,
908 log => get_commit_entry($d)->{log},
909 ra => Git::SVN::Ra->new($url),
910 config => SVN::Core::config_get_config(
911 $Git::SVN::Ra::config_dir
913 tree_a => "$d~1",
914 tree_b => $d,
915 editor_cb => sub {
916 print "Committed r$_[0]\n";
917 $cmt_rev = $_[0];
919 mergeinfo => $_merge_info,
920 svn_path => '');
921 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
922 print "No changes\n$d~1 == $d\n";
923 } elsif ($parents->{$d} && @{$parents->{$d}}) {
924 $gs->{inject_parents_dcommit}->{$cmt_rev} =
925 $parents->{$d};
927 $_fetch_all ? $gs->fetch_all : $gs->fetch;
928 $last_rev = $cmt_rev;
929 next if $_no_rebase;
931 # we always want to rebase against the current HEAD,
932 # not any head that was passed to us
933 my @diff = command('diff-tree', $d,
934 $gs->refname, '--');
935 my @finish;
936 if (@diff) {
937 @finish = rebase_cmd();
938 print STDERR "W: $d and ", $gs->refname,
939 " differ, using @finish:\n",
940 join("\n", @diff), "\n";
941 } else {
942 print "No changes between current HEAD and ",
943 $gs->refname,
944 "\nResetting to the latest ",
945 $gs->refname, "\n";
946 @finish = qw/reset --mixed/;
948 command_noisy(@finish, $gs->refname);
950 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
952 if (@diff) {
953 @refs = ();
954 my ($url_, $rev_, $uuid_, $gs_) =
955 working_head_info('HEAD', \@refs);
956 my ($linear_refs_, $parents_) =
957 linearize_history($gs_, \@refs);
958 if (scalar(@$linear_refs) !=
959 scalar(@$linear_refs_)) {
960 fatal "# of revisions changed ",
961 "\nbefore:\n",
962 join("\n", @$linear_refs),
963 "\n\nafter:\n",
964 join("\n", @$linear_refs_), "\n",
965 'If you are attempting to commit ',
966 "merges, try running:\n\t",
967 'git rebase --interactive',
968 '--preserve-merges ',
969 $gs->refname,
970 "\nBefore dcommitting";
972 if ($url_ ne $expect_url) {
973 if ($url_ eq $gs->metadata_url) {
974 print
975 "Accepting rewritten URL:",
976 " $url_\n";
977 } else {
978 fatal
979 "URL mismatch after rebase:",
980 " $url_ != $expect_url";
983 if ($uuid_ ne $uuid) {
984 fatal "uuid mismatch after rebase: ",
985 "$uuid_ != $uuid";
987 # remap parents
988 my (%p, @l, $i);
989 for ($i = 0; $i < scalar @$linear_refs; $i++) {
990 my $new = $linear_refs_->[$i] or next;
991 $p{$new} =
992 $parents->{$linear_refs->[$i]};
993 push @l, $new;
995 $parents = \%p;
996 $linear_refs = \@l;
1001 if ($old_head) {
1002 my $new_head = command_oneline(qw/rev-parse HEAD/);
1003 my $new_is_symbolic = eval {
1004 command_oneline(qw/symbolic-ref -q HEAD/);
1006 if ($new_is_symbolic) {
1007 print "dcommitted the branch ", $head, "\n";
1008 } else {
1009 print "dcommitted on a detached HEAD because you gave ",
1010 "a revision argument.\n",
1011 "The rewritten commit is: ", $new_head, "\n";
1013 command(['checkout', $old_head], STDERR => 0);
1016 unlink $gs->{index};
1019 sub cmd_branch {
1020 my ($branch_name, $head) = @_;
1022 unless (defined $branch_name && length $branch_name) {
1023 die(($_tag ? "tag" : "branch") . " name required\n");
1025 $head ||= 'HEAD';
1027 my (undef, $rev, undef, $gs) = working_head_info($head);
1028 my $src = $gs->full_pushurl;
1030 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1031 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1032 my $glob;
1033 if ($#{$allglobs} == 0) {
1034 $glob = $allglobs->[0];
1035 } else {
1036 unless(defined $_branch_dest) {
1037 die "Multiple ",
1038 $_tag ? "tag" : "branch",
1039 " paths defined for Subversion repository.\n",
1040 "You must specify where you want to create the ",
1041 $_tag ? "tag" : "branch",
1042 " with the --destination argument.\n";
1044 foreach my $g (@{$allglobs}) {
1045 # SVN::Git::Editor could probably be moved to Git.pm..
1046 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1047 if ($_branch_dest =~ /$re/) {
1048 $glob = $g;
1049 last;
1052 unless (defined $glob) {
1053 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1054 foreach my $g (@{$allglobs}) {
1055 $g->{path}->{left} =~ /$dest_re/ or next;
1056 if (defined $glob) {
1057 die "Ambiguous destination: ",
1058 $_branch_dest, "\nmatches both '",
1059 $glob->{path}->{left}, "' and '",
1060 $g->{path}->{left}, "'\n";
1062 $glob = $g;
1064 unless (defined $glob) {
1065 die "Unknown ",
1066 $_tag ? "tag" : "branch",
1067 " destination $_branch_dest\n";
1071 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1072 my $url;
1073 if (defined $_commit_url) {
1074 $url = $_commit_url;
1075 } else {
1076 $url = eval { command_oneline('config', '--get',
1077 "svn-remote.$gs->{repo_id}.commiturl") };
1078 if (!$url) {
1079 $url = $remote->{pushurl} || $remote->{url};
1082 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1084 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1085 $src=~s/^http:/https:/;
1088 ::_req_svn();
1090 my $ctx = SVN::Client->new(
1091 auth => Git::SVN::Ra::_auth_providers(),
1092 log_msg => sub {
1093 ${ $_[0] } = defined $_message
1094 ? $_message
1095 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1096 . $branch_name;
1100 eval {
1101 $ctx->ls($dst, 'HEAD', 0);
1102 } and die "branch ${branch_name} already exists\n";
1104 print "Copying ${src} at r${rev} to ${dst}...\n";
1105 $ctx->copy($src, $rev, $dst)
1106 unless $_dry_run;
1108 $gs->fetch_all;
1111 sub cmd_find_rev {
1112 my $revision_or_hash = shift or die "SVN or git revision required ",
1113 "as a command-line argument\n";
1114 my $result;
1115 if ($revision_or_hash =~ /^r\d+$/) {
1116 my $head = shift;
1117 $head ||= 'HEAD';
1118 my @refs;
1119 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1120 unless ($gs) {
1121 die "Unable to determine upstream SVN information from ",
1122 "$head history\n";
1124 my $desired_revision = substr($revision_or_hash, 1);
1125 $result = $gs->rev_map_get($desired_revision, $uuid);
1126 } else {
1127 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1128 $result = $rev;
1130 print "$result\n" if $result;
1133 sub auto_create_empty_directories {
1134 my ($gs) = @_;
1135 my $var = eval { command_oneline('config', '--get', '--bool',
1136 "svn-remote.$gs->{repo_id}.automkdirs") };
1137 # By default, create empty directories by consulting the unhandled log,
1138 # but allow setting it to 'false' to skip it.
1139 return !($var && $var eq 'false');
1142 sub cmd_rebase {
1143 command_noisy(qw/update-index --refresh/);
1144 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1145 unless ($gs) {
1146 die "Unable to determine upstream SVN information from ",
1147 "working tree history\n";
1149 if ($_dry_run) {
1150 print "Remote Branch: " . $gs->refname . "\n";
1151 print "SVN URL: " . $url . "\n";
1152 return;
1154 if (command(qw/diff-index HEAD --/)) {
1155 print STDERR "Cannot rebase with uncommited changes:\n";
1156 command_noisy('status');
1157 exit 1;
1159 unless ($_local) {
1160 # rebase will checkout for us, so no need to do it explicitly
1161 $_no_checkout = 'true';
1162 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1164 command_noisy(rebase_cmd(), $gs->refname);
1165 if (auto_create_empty_directories($gs)) {
1166 $gs->mkemptydirs;
1170 sub cmd_show_ignore {
1171 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1172 $gs ||= Git::SVN->new;
1173 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1174 $gs->prop_walk($gs->{path}, $r, sub {
1175 my ($gs, $path, $props) = @_;
1176 print STDOUT "\n# $path\n";
1177 my $s = $props->{'svn:ignore'} or return;
1178 $s =~ s/[\r\n]+/\n/g;
1179 $s =~ s/^\n+//;
1180 chomp $s;
1181 $s =~ s#^#$path#gm;
1182 print STDOUT "$s\n";
1186 sub cmd_show_externals {
1187 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1188 $gs ||= Git::SVN->new;
1189 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1190 $gs->prop_walk($gs->{path}, $r, sub {
1191 my ($gs, $path, $props) = @_;
1192 print STDOUT "\n# $path\n";
1193 my $s = $props->{'svn:externals'} or return;
1194 $s =~ s/[\r\n]+/\n/g;
1195 chomp $s;
1196 $s =~ s#^#$path#gm;
1197 print STDOUT "$s\n";
1201 sub cmd_create_ignore {
1202 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1203 $gs ||= Git::SVN->new;
1204 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1205 $gs->prop_walk($gs->{path}, $r, sub {
1206 my ($gs, $path, $props) = @_;
1207 # $path is of the form /path/to/dir/
1208 $path = '.' . $path;
1209 # SVN can have attributes on empty directories,
1210 # which git won't track
1211 mkpath([$path]) unless -d $path;
1212 my $ignore = $path . '.gitignore';
1213 my $s = $props->{'svn:ignore'} or return;
1214 open(GITIGNORE, '>', $ignore)
1215 or fatal("Failed to open `$ignore' for writing: $!");
1216 $s =~ s/[\r\n]+/\n/g;
1217 $s =~ s/^\n+//;
1218 chomp $s;
1219 # Prefix all patterns so that the ignore doesn't apply
1220 # to sub-directories.
1221 $s =~ s#^#/#gm;
1222 print GITIGNORE "$s\n";
1223 close(GITIGNORE)
1224 or fatal("Failed to close `$ignore': $!");
1225 command_noisy('add', '-f', $ignore);
1229 sub cmd_mkdirs {
1230 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1231 $gs ||= Git::SVN->new;
1232 $gs->mkemptydirs($_revision);
1235 sub canonicalize_path {
1236 my ($path) = @_;
1237 my $dot_slash_added = 0;
1238 if (substr($path, 0, 1) ne "/") {
1239 $path = "./" . $path;
1240 $dot_slash_added = 1;
1242 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1243 # good reason), so let's do this manually.
1244 $path =~ s#/+#/#g;
1245 $path =~ s#/\.(?:/|$)#/#g;
1246 $path =~ s#/[^/]+/\.\.##g;
1247 $path =~ s#/$##g;
1248 $path =~ s#^\./## if $dot_slash_added;
1249 $path =~ s#^/##;
1250 $path =~ s#^\.$##;
1251 return $path;
1254 sub canonicalize_url {
1255 my ($url) = @_;
1256 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1257 return $url;
1260 # get_svnprops(PATH)
1261 # ------------------
1262 # Helper for cmd_propget and cmd_proplist below.
1263 sub get_svnprops {
1264 my $path = shift;
1265 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1266 $gs ||= Git::SVN->new;
1268 # prefix THE PATH by the sub-directory from which the user
1269 # invoked us.
1270 $path = $cmd_dir_prefix . $path;
1271 fatal("No such file or directory: $path") unless -e $path;
1272 my $is_dir = -d $path ? 1 : 0;
1273 $path = $gs->{path} . '/' . $path;
1275 # canonicalize the path (otherwise libsvn will abort or fail to
1276 # find the file)
1277 $path = canonicalize_path($path);
1279 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1280 my $props;
1281 if ($is_dir) {
1282 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1284 else {
1285 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1287 return $props;
1290 # cmd_propget (PROP, PATH)
1291 # ------------------------
1292 # Print the SVN property PROP for PATH.
1293 sub cmd_propget {
1294 my ($prop, $path) = @_;
1295 $path = '.' if not defined $path;
1296 usage(1) if not defined $prop;
1297 my $props = get_svnprops($path);
1298 if (not defined $props->{$prop}) {
1299 fatal("`$path' does not have a `$prop' SVN property.");
1301 print $props->{$prop} . "\n";
1304 # cmd_proplist (PATH)
1305 # -------------------
1306 # Print the list of SVN properties for PATH.
1307 sub cmd_proplist {
1308 my $path = shift;
1309 $path = '.' if not defined $path;
1310 my $props = get_svnprops($path);
1311 print "Properties on '$path':\n";
1312 foreach (sort keys %{$props}) {
1313 print " $_\n";
1317 sub cmd_multi_init {
1318 my $url = shift;
1319 unless (defined $_trunk || @_branches || @_tags) {
1320 usage(1);
1323 $_prefix = '' unless defined $_prefix;
1324 if (defined $url) {
1325 $url = canonicalize_url($url);
1326 init_subdir(@_);
1328 do_git_init_db();
1329 if (defined $_trunk) {
1330 $_trunk =~ s#^/+##;
1331 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1332 # try both old-style and new-style lookups:
1333 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1334 unless ($gs_trunk) {
1335 my ($trunk_url, $trunk_path) =
1336 complete_svn_url($url, $_trunk);
1337 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1338 undef, $trunk_ref);
1341 return unless @_branches || @_tags;
1342 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1343 foreach my $path (@_branches) {
1344 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1346 foreach my $path (@_tags) {
1347 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1351 sub cmd_multi_fetch {
1352 $Git::SVN::no_reuse_existing = undef;
1353 my $remotes = Git::SVN::read_all_remotes();
1354 foreach my $repo_id (sort keys %$remotes) {
1355 if ($remotes->{$repo_id}->{url}) {
1356 Git::SVN::fetch_all($repo_id, $remotes);
1361 # this command is special because it requires no metadata
1362 sub cmd_commit_diff {
1363 my ($ta, $tb, $url) = @_;
1364 my $usage = "Usage: $0 commit-diff -r<revision> ".
1365 "<tree-ish> <tree-ish> [<URL>]";
1366 fatal($usage) if (!defined $ta || !defined $tb);
1367 my $svn_path = '';
1368 if (!defined $url) {
1369 my $gs = eval { Git::SVN->new };
1370 if (!$gs) {
1371 fatal("Needed URL or usable git-svn --id in ",
1372 "the command-line\n", $usage);
1374 $url = $gs->{url};
1375 $svn_path = $gs->{path};
1377 unless (defined $_revision) {
1378 fatal("-r|--revision is a required argument\n", $usage);
1380 if (defined $_message && defined $_file) {
1381 fatal("Both --message/-m and --file/-F specified ",
1382 "for the commit message.\n",
1383 "I have no idea what you mean");
1385 if (defined $_file) {
1386 $_message = file_to_s($_file);
1387 } else {
1388 $_message ||= get_commit_entry($tb)->{log};
1390 my $ra ||= Git::SVN::Ra->new($url);
1391 my $r = $_revision;
1392 if ($r eq 'HEAD') {
1393 $r = $ra->get_latest_revnum;
1394 } elsif ($r !~ /^\d+$/) {
1395 die "revision argument: $r not understood by git-svn\n";
1397 my %ed_opts = ( r => $r,
1398 log => $_message,
1399 ra => $ra,
1400 tree_a => $ta,
1401 tree_b => $tb,
1402 editor_cb => sub { print "Committed r$_[0]\n" },
1403 svn_path => $svn_path );
1404 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1405 print "No changes\n$ta == $tb\n";
1409 sub escape_uri_only {
1410 my ($uri) = @_;
1411 my @tmp;
1412 foreach (split m{/}, $uri) {
1413 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1414 push @tmp, $_;
1416 join('/', @tmp);
1419 sub escape_url {
1420 my ($url) = @_;
1421 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1422 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1423 $url = "$scheme://$domain$uri";
1425 $url;
1428 sub cmd_info {
1429 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1430 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1431 if (exists $_[1]) {
1432 die "Too many arguments specified\n";
1435 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1437 if (!$file_type && !$diff_status) {
1438 print STDERR "svn: '$path' is not under version control\n";
1439 exit 1;
1442 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1443 unless ($gs) {
1444 die "Unable to determine upstream SVN information from ",
1445 "working tree history\n";
1448 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1449 $path = "." if $path eq "";
1451 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1453 if ($_url) {
1454 print escape_url($full_url), "\n";
1455 return;
1458 my $result = "Path: $path\n";
1459 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1460 $result .= "URL: " . escape_url($full_url) . "\n";
1462 eval {
1463 my $repos_root = $gs->repos_root;
1464 Git::SVN::remove_username($repos_root);
1465 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1467 if ($@) {
1468 $result .= "Repository Root: (offline)\n";
1470 ::_req_svn();
1471 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1472 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1473 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1475 $result .= "Node Kind: " .
1476 ($file_type eq "dir" ? "directory" : "file") . "\n";
1478 my $schedule = $diff_status eq "A"
1479 ? "add"
1480 : ($diff_status eq "D" ? "delete" : "normal");
1481 $result .= "Schedule: $schedule\n";
1483 if ($diff_status eq "A") {
1484 print $result, "\n";
1485 return;
1488 my ($lc_author, $lc_rev, $lc_date_utc);
1489 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1490 my $log = command_output_pipe(@args);
1491 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1492 while (<$log>) {
1493 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1494 $lc_author = $1;
1495 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1496 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1497 (undef, $lc_rev, undef) = ::extract_metadata($1);
1500 close $log;
1502 Git::SVN::Log::set_local_timezone();
1504 $result .= "Last Changed Author: $lc_author\n";
1505 $result .= "Last Changed Rev: $lc_rev\n";
1506 $result .= "Last Changed Date: " .
1507 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1509 if ($file_type ne "dir") {
1510 my $text_last_updated_date =
1511 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1512 $result .=
1513 "Text Last Updated: " .
1514 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1515 "\n";
1516 my $checksum;
1517 if ($diff_status eq "D") {
1518 my ($fh, $ctx) =
1519 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1520 if ($file_type eq "link") {
1521 my $file_name = <$fh>;
1522 $checksum = md5sum("link $file_name");
1523 } else {
1524 $checksum = md5sum($fh);
1526 command_close_pipe($fh, $ctx);
1527 } elsif ($file_type eq "link") {
1528 my $file_name =
1529 command(qw(cat-file blob), "HEAD:$path");
1530 $checksum =
1531 md5sum("link " . $file_name);
1532 } else {
1533 open FILE, "<", $path or die $!;
1534 $checksum = md5sum(\*FILE);
1535 close FILE or die $!;
1537 $result .= "Checksum: " . $checksum . "\n";
1540 print $result, "\n";
1543 sub cmd_reset {
1544 my $target = shift || $_revision or die "SVN revision required\n";
1545 $target = $1 if $target =~ /^r(\d+)$/;
1546 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1547 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1548 unless ($gs) {
1549 die "Unable to determine upstream SVN information from ".
1550 "history\n";
1552 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1553 die "Cannot find SVN revision $target\n" unless defined($c);
1554 $gs->rev_map_set($r, $c, 'reset', $uuid);
1555 print "r$r = $c ($gs->{ref_id})\n";
1558 sub cmd_gc {
1559 if (!$can_compress) {
1560 warn "Compress::Zlib could not be found; unhandled.log " .
1561 "files will not be compressed.\n";
1563 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1566 ########################### utility functions #########################
1568 sub rebase_cmd {
1569 my @cmd = qw/rebase/;
1570 push @cmd, '-v' if $_verbose;
1571 push @cmd, qw/--merge/ if $_merge;
1572 push @cmd, "--strategy=$_strategy" if $_strategy;
1573 @cmd;
1576 sub post_fetch_checkout {
1577 return if $_no_checkout;
1578 my $gs = $Git::SVN::_head or return;
1579 return if verify_ref('refs/heads/master^0');
1581 # look for "trunk" ref if it exists
1582 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1583 my $fetch = $remote->{fetch};
1584 if ($fetch) {
1585 foreach my $p (keys %$fetch) {
1586 basename($fetch->{$p}) eq 'trunk' or next;
1587 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1588 last;
1592 my $valid_head = verify_ref('HEAD^0');
1593 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1594 return if ($valid_head || !verify_ref('HEAD^0'));
1596 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1597 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1598 return if -f $index;
1600 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1601 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1602 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1603 print STDERR "Checked out HEAD:\n ",
1604 $gs->full_url, " r", $gs->last_rev, "\n";
1605 if (auto_create_empty_directories($gs)) {
1606 $gs->mkemptydirs($gs->last_rev);
1610 sub complete_svn_url {
1611 my ($url, $path) = @_;
1612 $path =~ s#/+$##;
1613 if ($path !~ m#^[a-z\+]+://#) {
1614 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1615 fatal("E: '$path' is not a complete URL ",
1616 "and a separate URL is not specified");
1618 return ($url, $path);
1620 return ($path, '');
1623 sub complete_url_ls_init {
1624 my ($ra, $repo_path, $switch, $pfx) = @_;
1625 unless ($repo_path) {
1626 print STDERR "W: $switch not specified\n";
1627 return;
1629 $repo_path =~ s#/+$##;
1630 if ($repo_path =~ m#^[a-z\+]+://#) {
1631 $ra = Git::SVN::Ra->new($repo_path);
1632 $repo_path = '';
1633 } else {
1634 $repo_path =~ s#^/+##;
1635 unless ($ra) {
1636 fatal("E: '$repo_path' is not a complete URL ",
1637 "and a separate URL is not specified");
1640 my $url = $ra->{url};
1641 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1642 my $k = "svn-remote.$gs->{repo_id}.url";
1643 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1644 if ($orig_url && ($orig_url ne $gs->{url})) {
1645 die "$k already set: $orig_url\n",
1646 "wanted to set to: $gs->{url}\n";
1648 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1649 my $remote_path = "$gs->{path}/$repo_path";
1650 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1651 $remote_path =~ s#/+#/#g;
1652 $remote_path =~ s#^/##g;
1653 $remote_path .= "/*" if $remote_path !~ /\*/;
1654 my ($n) = ($switch =~ /^--(\w+)/);
1655 if (length $pfx && $pfx !~ m#/$#) {
1656 die "--prefix='$pfx' must have a trailing slash '/'\n";
1658 command_noisy('config',
1659 '--add',
1660 "svn-remote.$gs->{repo_id}.$n",
1661 "$remote_path:refs/remotes/$pfx*" .
1662 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1665 sub verify_ref {
1666 my ($ref) = @_;
1667 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1668 { STDERR => 0 }); };
1671 sub get_tree_from_treeish {
1672 my ($treeish) = @_;
1673 # $treeish can be a symbolic ref, too:
1674 my $type = command_oneline(qw/cat-file -t/, $treeish);
1675 my $expected;
1676 while ($type eq 'tag') {
1677 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1679 if ($type eq 'commit') {
1680 $expected = (grep /^tree /, command(qw/cat-file commit/,
1681 $treeish))[0];
1682 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1683 die "Unable to get tree from $treeish\n" unless $expected;
1684 } elsif ($type eq 'tree') {
1685 $expected = $treeish;
1686 } else {
1687 die "$treeish is a $type, expected tree, tag or commit\n";
1689 return $expected;
1692 sub get_commit_entry {
1693 my ($treeish) = shift;
1694 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1695 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1696 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1697 open my $log_fh, '>', $commit_editmsg or croak $!;
1699 my $type = command_oneline(qw/cat-file -t/, $treeish);
1700 if ($type eq 'commit' || $type eq 'tag') {
1701 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1702 $type, $treeish);
1703 my $in_msg = 0;
1704 my $author;
1705 my $saw_from = 0;
1706 my $msgbuf = "";
1707 while (<$msg_fh>) {
1708 if (!$in_msg) {
1709 $in_msg = 1 if (/^\s*$/);
1710 $author = $1 if (/^author (.*>)/);
1711 } elsif (/^git-svn-id: /) {
1712 # skip this for now, we regenerate the
1713 # correct one on re-fetch anyways
1714 # TODO: set *:merge properties or like...
1715 } else {
1716 if (/^From:/ || /^Signed-off-by:/) {
1717 $saw_from = 1;
1719 $msgbuf .= $_;
1722 $msgbuf =~ s/\s+$//s;
1723 if ($Git::SVN::_add_author_from && defined($author)
1724 && !$saw_from) {
1725 $msgbuf .= "\n\nFrom: $author";
1727 print $log_fh $msgbuf or croak $!;
1728 command_close_pipe($msg_fh, $ctx);
1730 close $log_fh or croak $!;
1732 if ($_edit || ($type eq 'tree')) {
1733 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1734 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1736 rename $commit_editmsg, $commit_msg or croak $!;
1738 require Encode;
1739 # SVN requires messages to be UTF-8 when entering the repo
1740 local $/;
1741 open $log_fh, '<', $commit_msg or croak $!;
1742 binmode $log_fh;
1743 chomp($log_entry{log} = <$log_fh>);
1745 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1746 my $msg = $log_entry{log};
1748 eval { $msg = Encode::decode($enc, $msg, 1) };
1749 if ($@) {
1750 die "Could not decode as $enc:\n", $msg,
1751 "\nPerhaps you need to set i18n.commitencoding\n";
1754 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1755 die "Could not encode as UTF-8:\n$msg\n" if $@;
1757 $log_entry{log} = $msg;
1759 close $log_fh or croak $!;
1761 unlink $commit_msg;
1762 \%log_entry;
1765 sub s_to_file {
1766 my ($str, $file, $mode) = @_;
1767 open my $fd,'>',$file or croak $!;
1768 print $fd $str,"\n" or croak $!;
1769 close $fd or croak $!;
1770 chmod ($mode &~ umask, $file) if (defined $mode);
1773 sub file_to_s {
1774 my $file = shift;
1775 open my $fd,'<',$file or croak "$!: file: $file\n";
1776 local $/;
1777 my $ret = <$fd>;
1778 close $fd or croak $!;
1779 $ret =~ s/\s*$//s;
1780 return $ret;
1783 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1784 sub load_authors {
1785 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1786 my $log = $cmd eq 'log';
1787 while (<$authors>) {
1788 chomp;
1789 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1790 my ($user, $name, $email) = ($1, $2, $3);
1791 if ($log) {
1792 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1793 } else {
1794 $users{$user} = [$name, $email];
1797 close $authors or croak $!;
1800 # convert GetOpt::Long specs for use by git-config
1801 sub read_git_config {
1802 my $opts = shift;
1803 my @config_only;
1804 foreach my $o (keys %$opts) {
1805 # if we have mixedCase and a long option-only, then
1806 # it's a config-only variable that we don't need for
1807 # the command-line.
1808 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1809 my $v = $opts->{$o};
1810 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1811 $key =~ s/-//g;
1812 my $arg = 'git config';
1813 $arg .= ' --int' if ($o =~ /[:=]i$/);
1814 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1815 if (ref $v eq 'ARRAY') {
1816 chomp(my @tmp = `$arg --get-all svn.$key`);
1817 @$v = @tmp if @tmp;
1818 } else {
1819 chomp(my $tmp = `$arg --get svn.$key`);
1820 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1821 $$v = $tmp;
1825 delete @$opts{@config_only} if @config_only;
1828 sub extract_metadata {
1829 my $id = shift or return (undef, undef, undef);
1830 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1831 \s([a-f\d\-]+)$/ix);
1832 if (!defined $rev || !$uuid || !$url) {
1833 # some of the original repositories I made had
1834 # identifiers like this:
1835 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1837 return ($url, $rev, $uuid);
1840 sub cmt_metadata {
1841 return extract_metadata((grep(/^git-svn-id: /,
1842 command(qw/cat-file commit/, shift)))[-1]);
1845 sub cmt_sha2rev_batch {
1846 my %s2r;
1847 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1848 my $list = shift;
1850 foreach my $sha (@{$list}) {
1851 my $first = 1;
1852 my $size = 0;
1853 print $out $sha, "\n";
1855 while (my $line = <$in>) {
1856 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1857 last;
1858 } elsif ($first &&
1859 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1860 $first = 0;
1861 $size = $1;
1862 next;
1863 } elsif ($line =~ /^(git-svn-id: )/) {
1864 my (undef, $rev, undef) =
1865 extract_metadata($line);
1866 $s2r{$sha} = $rev;
1869 $size -= length($line);
1870 last if ($size == 0);
1874 command_close_bidi_pipe($pid, $in, $out, $ctx);
1876 return \%s2r;
1879 sub working_head_info {
1880 my ($head, $refs) = @_;
1881 my @args = qw/rev-list --first-parent --pretty=medium/;
1882 my ($fh, $ctx) = command_output_pipe(@args, $head);
1883 my $hash;
1884 my %max;
1885 while (<$fh>) {
1886 if ( m{^commit ($::sha1)$} ) {
1887 unshift @$refs, $hash if $hash and $refs;
1888 $hash = $1;
1889 next;
1891 next unless s{^\s*(git-svn-id:)}{$1};
1892 my ($url, $rev, $uuid) = extract_metadata($_);
1893 if (defined $url && defined $rev) {
1894 next if $max{$url} and $max{$url} < $rev;
1895 if (my $gs = Git::SVN->find_by_url($url)) {
1896 my $c = $gs->rev_map_get($rev, $uuid);
1897 if ($c && $c eq $hash) {
1898 close $fh; # break the pipe
1899 return ($url, $rev, $uuid, $gs);
1900 } else {
1901 $max{$url} ||= $gs->rev_map_max;
1906 command_close_pipe($fh, $ctx);
1907 (undef, undef, undef, undef);
1910 sub read_commit_parents {
1911 my ($parents, $c) = @_;
1912 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1913 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1914 @{$parents->{$c}} = split(/ /, $p);
1917 sub linearize_history {
1918 my ($gs, $refs) = @_;
1919 my %parents;
1920 foreach my $c (@$refs) {
1921 read_commit_parents(\%parents, $c);
1924 my @linear_refs;
1925 my %skip = ();
1926 my $last_svn_commit = $gs->last_commit;
1927 foreach my $c (reverse @$refs) {
1928 next if $c eq $last_svn_commit;
1929 last if $skip{$c};
1931 unshift @linear_refs, $c;
1932 $skip{$c} = 1;
1934 # we only want the first parent to diff against for linear
1935 # history, we save the rest to inject when we finalize the
1936 # svn commit
1937 my $fp_a = verify_ref("$c~1");
1938 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1939 if (!$fp_a || !$fp_b) {
1940 die "Commit $c\n",
1941 "has no parent commit, and therefore ",
1942 "nothing to diff against.\n",
1943 "You should be working from a repository ",
1944 "originally created by git-svn\n";
1946 if ($fp_a ne $fp_b) {
1947 die "$c~1 = $fp_a, however parsing commit $c ",
1948 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1951 foreach my $p (@{$parents{$c}}) {
1952 $skip{$p} = 1;
1955 (\@linear_refs, \%parents);
1958 sub find_file_type_and_diff_status {
1959 my ($path) = @_;
1960 return ('dir', '') if $path eq '';
1962 my $diff_output =
1963 command_oneline(qw(diff --cached --name-status --), $path) || "";
1964 my $diff_status = (split(' ', $diff_output))[0] || "";
1966 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1968 return (undef, undef) if !$diff_status && !$ls_tree;
1970 if ($diff_status eq "A") {
1971 return ("link", $diff_status) if -l $path;
1972 return ("dir", $diff_status) if -d $path;
1973 return ("file", $diff_status);
1976 my $mode = (split(' ', $ls_tree))[0] || "";
1978 return ("link", $diff_status) if $mode eq "120000";
1979 return ("dir", $diff_status) if $mode eq "040000";
1980 return ("file", $diff_status);
1983 sub md5sum {
1984 my $arg = shift;
1985 my $ref = ref $arg;
1986 my $md5 = Digest::MD5->new();
1987 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1988 $md5->addfile($arg) or croak $!;
1989 } elsif ($ref eq 'SCALAR') {
1990 $md5->add($$arg) or croak $!;
1991 } elsif (!$ref) {
1992 $md5->add($arg) or croak $!;
1993 } else {
1994 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1996 return $md5->hexdigest();
1999 sub gc_directory {
2000 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2001 my $out_filename = $_ . ".gz";
2002 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2003 binmode $in_fh;
2004 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2005 die "Unable to open $out_filename: $!\n";
2007 my $res;
2008 while ($res = sysread($in_fh, my $str, 1024)) {
2009 $gz->gzwrite($str) or
2010 die "Unable to write: ".$gz->gzerror()."!\n";
2012 unlink $_ or die "unlink $File::Find::name: $!\n";
2013 } elsif (-f $_ && basename($_) eq "index") {
2014 unlink $_ or die "unlink $_: $!\n";
2018 package Git::SVN;
2019 use strict;
2020 use warnings;
2021 use Fcntl qw/:DEFAULT :seek/;
2022 use constant rev_map_fmt => 'NH40';
2023 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2024 $_repack $_repack_flags $_use_svm_props $_head
2025 $_use_svnsync_props $no_reuse_existing $_minimize_url
2026 $_use_log_author $_add_author_from $_localtime/;
2027 use Carp qw/croak/;
2028 use File::Path qw/mkpath/;
2029 use File::Copy qw/copy/;
2030 use IPC::Open3;
2031 use Time::Local;
2032 use Memoize; # core since 5.8.0, Jul 2002
2033 use Memoize::Storable;
2035 my ($_gc_nr, $_gc_period);
2037 # properties that we do not log:
2038 my %SKIP_PROP;
2039 BEGIN {
2040 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2041 svn:special svn:executable
2042 svn:entry:committed-rev
2043 svn:entry:last-author
2044 svn:entry:uuid
2045 svn:entry:committed-date/;
2047 # some options are read globally, but can be overridden locally
2048 # per [svn-remote "..."] section. Command-line options will *NOT*
2049 # override options set in an [svn-remote "..."] section
2050 no strict 'refs';
2051 for my $option (qw/follow_parent no_metadata use_svm_props
2052 use_svnsync_props/) {
2053 my $key = $option;
2054 $key =~ tr/_//d;
2055 my $prop = "-$option";
2056 *$option = sub {
2057 my ($self) = @_;
2058 return $self->{$prop} if exists $self->{$prop};
2059 my $k = "svn-remote.$self->{repo_id}.$key";
2060 eval { command_oneline(qw/config --get/, $k) };
2061 if ($@) {
2062 $self->{$prop} = ${"Git::SVN::_$option"};
2063 } else {
2064 my $v = command_oneline(qw/config --bool/,$k);
2065 $self->{$prop} = $v eq 'false' ? 0 : 1;
2067 return $self->{$prop};
2073 my (%LOCKFILES, %INDEX_FILES);
2074 END {
2075 unlink keys %LOCKFILES if %LOCKFILES;
2076 unlink keys %INDEX_FILES if %INDEX_FILES;
2079 sub resolve_local_globs {
2080 my ($url, $fetch, $glob_spec) = @_;
2081 return unless defined $glob_spec;
2082 my $ref = $glob_spec->{ref};
2083 my $path = $glob_spec->{path};
2084 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2085 next unless m#^$ref->{regex}$#;
2086 my $p = $1;
2087 my $pathname = desanitize_refname($path->full_path($p));
2088 my $refname = desanitize_refname($ref->full_path($p));
2089 if (my $existing = $fetch->{$pathname}) {
2090 if ($existing ne $refname) {
2091 die "Refspec conflict:\n",
2092 "existing: $existing\n",
2093 " globbed: $refname\n";
2095 my $u = (::cmt_metadata("$refname"))[0];
2096 $u =~ s!^\Q$url\E(/|$)!! or die
2097 "$refname: '$url' not found in '$u'\n";
2098 if ($pathname ne $u) {
2099 warn "W: Refspec glob conflict ",
2100 "(ref: $refname):\n",
2101 "expected path: $pathname\n",
2102 " real path: $u\n",
2103 "Continuing ahead with $u\n";
2104 next;
2106 } else {
2107 $fetch->{$pathname} = $refname;
2112 sub parse_revision_argument {
2113 my ($base, $head) = @_;
2114 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2115 return ($base, $head);
2117 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2118 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2119 return ($head, $head) if ($::_revision eq 'HEAD');
2120 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2121 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2122 die "revision argument: $::_revision not understood by git-svn\n";
2125 sub fetch_all {
2126 my ($repo_id, $remotes) = @_;
2127 if (ref $repo_id) {
2128 my $gs = $repo_id;
2129 $repo_id = undef;
2130 $repo_id = $gs->{repo_id};
2132 $remotes ||= read_all_remotes();
2133 my $remote = $remotes->{$repo_id} or
2134 die "[svn-remote \"$repo_id\"] unknown\n";
2135 my $fetch = $remote->{fetch};
2136 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2137 my (@gs, @globs);
2138 my $ra = Git::SVN::Ra->new($url);
2139 my $uuid = $ra->get_uuid;
2140 my $head = $ra->get_latest_revnum;
2142 # ignore errors, $head revision may not even exist anymore
2143 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2144 warn "W: $@\n" if $@;
2146 my $base = defined $fetch ? $head : 0;
2148 # read the max revs for wildcard expansion (branches/*, tags/*)
2149 foreach my $t (qw/branches tags/) {
2150 defined $remote->{$t} or next;
2151 push @globs, @{$remote->{$t}};
2153 my $max_rev = eval { tmp_config(qw/--int --get/,
2154 "svn-remote.$repo_id.${t}-maxRev") };
2155 if (defined $max_rev && ($max_rev < $base)) {
2156 $base = $max_rev;
2157 } elsif (!defined $max_rev) {
2158 $base = 0;
2162 if ($fetch) {
2163 foreach my $p (sort keys %$fetch) {
2164 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2165 my $lr = $gs->rev_map_max;
2166 if (defined $lr) {
2167 $base = $lr if ($lr < $base);
2169 push @gs, $gs;
2173 ($base, $head) = parse_revision_argument($base, $head);
2174 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2177 sub read_all_remotes {
2178 my $r = {};
2179 my $use_svm_props = eval { command_oneline(qw/config --bool
2180 svn.useSvmProps/) };
2181 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2182 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2183 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2184 if (m!^(.+)\.fetch=$svn_refspec$!) {
2185 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2186 die("svn-remote.$remote: remote ref '$remote_ref' "
2187 . "must start with 'refs/'\n")
2188 unless $remote_ref =~ m{^refs/};
2189 $local_ref = uri_decode($local_ref);
2190 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2191 $r->{$remote}->{svm} = {} if $use_svm_props;
2192 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2193 $r->{$1}->{svm} = {};
2194 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2195 $r->{$1}->{url} = $2;
2196 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2197 $r->{$1}->{pushurl} = $2;
2198 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2199 $r->{$1}->{ignore_refs_regex} = $2;
2200 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2201 my ($remote, $t, $local_ref, $remote_ref) =
2202 ($1, $2, $3, $4);
2203 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2204 . "must start with 'refs/'\n")
2205 unless $remote_ref =~ m{^refs/};
2206 $local_ref = uri_decode($local_ref);
2207 my $rs = {
2208 t => $t,
2209 remote => $remote,
2210 path => Git::SVN::GlobSpec->new($local_ref, 1),
2211 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2212 if (length($rs->{ref}->{right}) != 0) {
2213 die "The '*' glob character must be the last ",
2214 "character of '$remote_ref'\n";
2216 push @{ $r->{$remote}->{$t} }, $rs;
2220 map {
2221 if (defined $r->{$_}->{svm}) {
2222 my $svm;
2223 eval {
2224 my $section = "svn-remote.$_";
2225 $svm = {
2226 source => tmp_config('--get',
2227 "$section.svm-source"),
2228 replace => tmp_config('--get',
2229 "$section.svm-replace"),
2232 $r->{$_}->{svm} = $svm;
2234 } keys %$r;
2236 foreach my $remote (keys %$r) {
2237 foreach ( grep { defined $_ }
2238 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2239 foreach my $rs ( @$_ ) {
2240 $rs->{ignore_refs_regex} =
2241 $r->{$remote}->{ignore_refs_regex};
2249 sub init_vars {
2250 $_gc_nr = $_gc_period = 1000;
2251 if (defined $_repack || defined $_repack_flags) {
2252 warn "Repack options are obsolete; they have no effect.\n";
2256 sub verify_remotes_sanity {
2257 return unless -d $ENV{GIT_DIR};
2258 my %seen;
2259 foreach (command(qw/config -l/)) {
2260 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2261 if ($seen{$1}) {
2262 die "Remote ref refs/remote/$1 is tracked by",
2263 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2264 "Please resolve this ambiguity in ",
2265 "your git configuration file before ",
2266 "continuing\n";
2268 $seen{$1} = $_;
2273 sub find_existing_remote {
2274 my ($url, $remotes) = @_;
2275 return undef if $no_reuse_existing;
2276 my $existing;
2277 foreach my $repo_id (keys %$remotes) {
2278 my $u = $remotes->{$repo_id}->{url} or next;
2279 next if $u ne $url;
2280 $existing = $repo_id;
2281 last;
2283 $existing;
2286 sub init_remote_config {
2287 my ($self, $url, $no_write) = @_;
2288 $url =~ s!/+$!!; # strip trailing slash
2289 my $r = read_all_remotes();
2290 my $existing = find_existing_remote($url, $r);
2291 if ($existing) {
2292 unless ($no_write) {
2293 print STDERR "Using existing ",
2294 "[svn-remote \"$existing\"]\n";
2296 $self->{repo_id} = $existing;
2297 } elsif ($_minimize_url) {
2298 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2299 $existing = find_existing_remote($min_url, $r);
2300 if ($existing) {
2301 unless ($no_write) {
2302 print STDERR "Using existing ",
2303 "[svn-remote \"$existing\"]\n";
2305 $self->{repo_id} = $existing;
2307 if ($min_url ne $url) {
2308 unless ($no_write) {
2309 print STDERR "Using higher level of URL: ",
2310 "$url => $min_url\n";
2312 my $old_path = $self->{path};
2313 $self->{path} = $url;
2314 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2315 if (length $old_path) {
2316 $self->{path} .= "/$old_path";
2318 $url = $min_url;
2321 my $orig_url;
2322 if (!$existing) {
2323 # verify that we aren't overwriting anything:
2324 $orig_url = eval {
2325 command_oneline('config', '--get',
2326 "svn-remote.$self->{repo_id}.url")
2328 if ($orig_url && ($orig_url ne $url)) {
2329 die "svn-remote.$self->{repo_id}.url already set: ",
2330 "$orig_url\nwanted to set to: $url\n";
2333 my ($xrepo_id, $xpath) = find_ref($self->refname);
2334 if (!$no_write && defined $xpath) {
2335 die "svn-remote.$xrepo_id.fetch already set to track ",
2336 "$xpath:", $self->refname, "\n";
2338 unless ($no_write) {
2339 command_noisy('config',
2340 "svn-remote.$self->{repo_id}.url", $url);
2341 $self->{path} =~ s{^/}{};
2342 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2343 command_noisy('config', '--add',
2344 "svn-remote.$self->{repo_id}.fetch",
2345 "$self->{path}:".$self->refname);
2347 $self->{url} = $url;
2350 sub find_by_url { # repos_root and, path are optional
2351 my ($class, $full_url, $repos_root, $path) = @_;
2353 return undef unless defined $full_url;
2354 remove_username($full_url);
2355 remove_username($repos_root) if defined $repos_root;
2356 my $remotes = read_all_remotes();
2357 if (defined $full_url && defined $repos_root && !defined $path) {
2358 $path = $full_url;
2359 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2361 foreach my $repo_id (keys %$remotes) {
2362 my $u = $remotes->{$repo_id}->{url} or next;
2363 remove_username($u);
2364 next if defined $repos_root && $repos_root ne $u;
2366 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2367 foreach my $t (qw/branches tags/) {
2368 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2369 resolve_local_globs($u, $fetch, $globspec);
2372 my $p = $path;
2373 my $rwr = rewrite_root({repo_id => $repo_id});
2374 my $svm = $remotes->{$repo_id}->{svm}
2375 if defined $remotes->{$repo_id}->{svm};
2376 unless (defined $p) {
2377 $p = $full_url;
2378 my $z = $u;
2379 my $prefix = '';
2380 if ($rwr) {
2381 $z = $rwr;
2382 remove_username($z);
2383 } elsif (defined $svm) {
2384 $z = $svm->{source};
2385 $prefix = $svm->{replace};
2386 $prefix =~ s#^\Q$u\E(?:/|$)##;
2387 $prefix =~ s#/$##;
2389 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2391 foreach my $f (keys %$fetch) {
2392 next if $f ne $p;
2393 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2396 undef;
2399 sub init {
2400 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2401 my $self = _new($class, $repo_id, $ref_id, $path);
2402 if (defined $url) {
2403 $self->init_remote_config($url, $no_write);
2405 $self;
2408 sub find_ref {
2409 my ($ref_id) = @_;
2410 foreach (command(qw/config -l/)) {
2411 next unless m!^svn-remote\.(.+)\.fetch=
2412 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2413 my ($repo_id, $path, $ref) = ($1, $2, $3);
2414 if ($ref eq $ref_id) {
2415 $path = '' if ($path =~ m#^\./?#);
2416 return ($repo_id, $path);
2419 (undef, undef, undef);
2422 sub new {
2423 my ($class, $ref_id, $repo_id, $path) = @_;
2424 if (defined $ref_id && !defined $repo_id && !defined $path) {
2425 ($repo_id, $path) = find_ref($ref_id);
2426 if (!defined $repo_id) {
2427 die "Could not find a \"svn-remote.*.fetch\" key ",
2428 "in the repository configuration matching: ",
2429 "$ref_id\n";
2432 my $self = _new($class, $repo_id, $ref_id, $path);
2433 if (!defined $self->{path} || !length $self->{path}) {
2434 my $fetch = command_oneline('config', '--get',
2435 "svn-remote.$repo_id.fetch",
2436 ":$ref_id\$") or
2437 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2438 "\":$ref_id\$\" in config\n";
2439 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2441 $self->{path} =~ s{/+}{/}g;
2442 $self->{path} =~ s{\A/}{};
2443 $self->{path} =~ s{/\z}{};
2444 $self->{url} = command_oneline('config', '--get',
2445 "svn-remote.$repo_id.url") or
2446 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2447 $self->{pushurl} = eval { command_oneline('config', '--get',
2448 "svn-remote.$repo_id.pushurl") };
2449 $self->rebuild;
2450 $self;
2453 sub refname {
2454 my ($refname) = $_[0]->{ref_id} ;
2456 # It cannot end with a slash /, we'll throw up on this because
2457 # SVN can't have directories with a slash in their name, either:
2458 if ($refname =~ m{/$}) {
2459 die "ref: '$refname' ends with a trailing slash, this is ",
2460 "not permitted by git nor Subversion\n";
2463 # It cannot have ASCII control character space, tilde ~, caret ^,
2464 # colon :, question-mark ?, asterisk *, space, or open bracket [
2465 # anywhere.
2467 # Additionally, % must be escaped because it is used for escaping
2468 # and we want our escaped refname to be reversible
2469 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2471 # no slash-separated component can begin with a dot .
2472 # /.* becomes /%2E*
2473 $refname =~ s{/\.}{/%2E}g;
2475 # It cannot have two consecutive dots .. anywhere
2476 # .. becomes %2E%2E
2477 $refname =~ s{\.\.}{%2E%2E}g;
2479 # trailing dots and .lock are not allowed
2480 # .$ becomes %2E and .lock becomes %2Elock
2481 $refname =~ s{\.(?=$|lock$)}{%2E};
2483 # the sequence @{ is used to access the reflog
2484 # @{ becomes %40{
2485 $refname =~ s{\@\{}{%40\{}g;
2487 return $refname;
2490 sub desanitize_refname {
2491 my ($refname) = @_;
2492 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2493 return $refname;
2496 sub svm_uuid {
2497 my ($self) = @_;
2498 return $self->{svm}->{uuid} if $self->svm;
2499 $self->ra;
2500 unless ($self->{svm}) {
2501 die "SVM UUID not cached, and reading remotely failed\n";
2503 $self->{svm}->{uuid};
2506 sub svm {
2507 my ($self) = @_;
2508 return $self->{svm} if $self->{svm};
2509 my $svm;
2510 # see if we have it in our config, first:
2511 eval {
2512 my $section = "svn-remote.$self->{repo_id}";
2513 $svm = {
2514 source => tmp_config('--get', "$section.svm-source"),
2515 uuid => tmp_config('--get', "$section.svm-uuid"),
2516 replace => tmp_config('--get', "$section.svm-replace"),
2519 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2520 $self->{svm} = $svm;
2522 $self->{svm};
2525 sub _set_svm_vars {
2526 my ($self, $ra) = @_;
2527 return $ra if $self->svm;
2529 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2530 "(svm:source, svm:uuid) ",
2531 "from the following URLs:\n" );
2532 sub read_svm_props {
2533 my ($self, $ra, $path, $r) = @_;
2534 my $props = ($ra->get_dir($path, $r))[2];
2535 my $src = $props->{'svm:source'};
2536 my $uuid = $props->{'svm:uuid'};
2537 return undef if (!$src || !$uuid);
2539 chomp($src, $uuid);
2541 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2542 or die "doesn't look right - svm:uuid is '$uuid'\n";
2544 # the '!' is used to mark the repos_root!/relative/path
2545 $src =~ s{/?!/?}{/};
2546 $src =~ s{/+$}{}; # no trailing slashes please
2547 # username is of no interest
2548 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2550 my $replace = $ra->{url};
2551 $replace .= "/$path" if length $path;
2553 my $section = "svn-remote.$self->{repo_id}";
2554 tmp_config("$section.svm-source", $src);
2555 tmp_config("$section.svm-replace", $replace);
2556 tmp_config("$section.svm-uuid", $uuid);
2557 $self->{svm} = {
2558 source => $src,
2559 uuid => $uuid,
2560 replace => $replace
2564 my $r = $ra->get_latest_revnum;
2565 my $path = $self->{path};
2566 my %tried;
2567 while (length $path) {
2568 unless ($tried{"$self->{url}/$path"}) {
2569 return $ra if $self->read_svm_props($ra, $path, $r);
2570 $tried{"$self->{url}/$path"} = 1;
2572 $path =~ s#/?[^/]+$##;
2574 die "Path: '$path' should be ''\n" if $path ne '';
2575 return $ra if $self->read_svm_props($ra, $path, $r);
2576 $tried{"$self->{url}/$path"} = 1;
2578 if ($ra->{repos_root} eq $self->{url}) {
2579 die @err, (map { " $_\n" } keys %tried), "\n";
2582 # nope, make sure we're connected to the repository root:
2583 my $ok;
2584 my @tried_b;
2585 $path = $ra->{svn_path};
2586 $ra = Git::SVN::Ra->new($ra->{repos_root});
2587 while (length $path) {
2588 unless ($tried{"$ra->{url}/$path"}) {
2589 $ok = $self->read_svm_props($ra, $path, $r);
2590 last if $ok;
2591 $tried{"$ra->{url}/$path"} = 1;
2593 $path =~ s#/?[^/]+$##;
2595 die "Path: '$path' should be ''\n" if $path ne '';
2596 $ok ||= $self->read_svm_props($ra, $path, $r);
2597 $tried{"$ra->{url}/$path"} = 1;
2598 if (!$ok) {
2599 die @err, (map { " $_\n" } keys %tried), "\n";
2601 Git::SVN::Ra->new($self->{url});
2604 sub svnsync {
2605 my ($self) = @_;
2606 return $self->{svnsync} if $self->{svnsync};
2608 if ($self->no_metadata) {
2609 die "Can't have both 'noMetadata' and ",
2610 "'useSvnsyncProps' options set!\n";
2612 if ($self->rewrite_root) {
2613 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2614 "options set!\n";
2616 if ($self->rewrite_uuid) {
2617 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2618 "options set!\n";
2621 my $svnsync;
2622 # see if we have it in our config, first:
2623 eval {
2624 my $section = "svn-remote.$self->{repo_id}";
2626 my $url = tmp_config('--get', "$section.svnsync-url");
2627 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2628 die "doesn't look right - svn:sync-from-url is '$url'\n";
2630 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2631 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2632 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2634 $svnsync = { url => $url, uuid => $uuid }
2636 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2637 return $self->{svnsync} = $svnsync;
2640 my $err = "useSvnsyncProps set, but failed to read " .
2641 "svnsync property: svn:sync-from-";
2642 my $rp = $self->ra->rev_proplist(0);
2644 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2645 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2646 die "doesn't look right - svn:sync-from-url is '$url'\n";
2648 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2649 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2650 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2652 my $section = "svn-remote.$self->{repo_id}";
2653 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2654 tmp_config('--add', "$section.svnsync-url", $url);
2655 return $self->{svnsync} = { url => $url, uuid => $uuid };
2658 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2659 # remote lookup (useful for 'git svn log').
2660 sub ra_uuid {
2661 my ($self) = @_;
2662 unless ($self->{ra_uuid}) {
2663 my $key = "svn-remote.$self->{repo_id}.uuid";
2664 my $uuid = eval { tmp_config('--get', $key) };
2665 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2666 $self->{ra_uuid} = $uuid;
2667 } else {
2668 die "ra_uuid called without URL\n" unless $self->{url};
2669 $self->{ra_uuid} = $self->ra->get_uuid;
2670 tmp_config('--add', $key, $self->{ra_uuid});
2673 $self->{ra_uuid};
2676 sub _set_repos_root {
2677 my ($self, $repos_root) = @_;
2678 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2679 $repos_root ||= $self->ra->{repos_root};
2680 tmp_config($k, $repos_root);
2681 $repos_root;
2684 sub repos_root {
2685 my ($self) = @_;
2686 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2687 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2690 sub ra {
2691 my ($self) = shift;
2692 my $ra = Git::SVN::Ra->new($self->{url});
2693 $self->_set_repos_root($ra->{repos_root});
2694 if ($self->use_svm_props && !$self->{svm}) {
2695 if ($self->no_metadata) {
2696 die "Can't have both 'noMetadata' and ",
2697 "'useSvmProps' options set!\n";
2698 } elsif ($self->use_svnsync_props) {
2699 die "Can't have both 'useSvnsyncProps' and ",
2700 "'useSvmProps' options set!\n";
2702 $ra = $self->_set_svm_vars($ra);
2703 $self->{-want_revprops} = 1;
2705 $ra;
2708 # prop_walk(PATH, REV, SUB)
2709 # -------------------------
2710 # Recursively traverse PATH at revision REV and invoke SUB for each
2711 # directory that contains a SVN property. SUB will be invoked as
2712 # follows: &SUB(gs, path, props); where `gs' is this instance of
2713 # Git::SVN, `path' the path to the directory where the properties
2714 # `props' were found. The `path' will be relative to point of checkout,
2715 # that is, if url://repo/trunk is the current Git branch, and that
2716 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2717 # as `path' (note the trailing `/').
2718 sub prop_walk {
2719 my ($self, $path, $rev, $sub) = @_;
2721 $path =~ s#^/##;
2722 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2723 $path =~ s#^/*#/#g;
2724 my $p = $path;
2725 # Strip the irrelevant part of the path.
2726 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2727 # Ensure the path is terminated by a `/'.
2728 $p =~ s#/*$#/#;
2730 # The properties contain all the internal SVN stuff nobody
2731 # (usually) cares about.
2732 my $interesting_props = 0;
2733 foreach (keys %{$props}) {
2734 # If it doesn't start with `svn:', it must be a
2735 # user-defined property.
2736 ++$interesting_props and next if $_ !~ /^svn:/;
2737 # FIXME: Fragile, if SVN adds new public properties,
2738 # this needs to be updated.
2739 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2740 |eol-style|mime-type
2741 |externals|needs-lock)$/x;
2743 &$sub($self, $p, $props) if $interesting_props;
2745 foreach (sort keys %$dirent) {
2746 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2747 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2751 sub last_rev { ($_[0]->last_rev_commit)[0] }
2752 sub last_commit { ($_[0]->last_rev_commit)[1] }
2754 # returns the newest SVN revision number and newest commit SHA1
2755 sub last_rev_commit {
2756 my ($self) = @_;
2757 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2758 return ($self->{last_rev}, $self->{last_commit});
2760 my $c = ::verify_ref($self->refname.'^0');
2761 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2762 my $rev = (::cmt_metadata($c))[1];
2763 if (defined $rev) {
2764 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2765 return ($rev, $c);
2768 my $map_path = $self->map_path;
2769 unless (-e $map_path) {
2770 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2771 return (undef, undef);
2773 my ($rev, $commit) = $self->rev_map_max(1);
2774 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2775 return ($rev, $commit);
2778 sub get_fetch_range {
2779 my ($self, $min, $max) = @_;
2780 $max ||= $self->ra->get_latest_revnum;
2781 $min ||= $self->rev_map_max;
2782 (++$min, $max);
2785 sub tmp_config {
2786 my (@args) = @_;
2787 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2788 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2789 if (! -f $config && -f $old_def_config) {
2790 rename $old_def_config, $config or
2791 die "Failed rename $old_def_config => $config: $!\n";
2793 my $old_config = $ENV{GIT_CONFIG};
2794 $ENV{GIT_CONFIG} = $config;
2795 $@ = undef;
2796 my @ret = eval {
2797 unless (-f $config) {
2798 mkfile($config);
2799 open my $fh, '>', $config or
2800 die "Can't open $config: $!\n";
2801 print $fh "; This file is used internally by ",
2802 "git-svn\n" or die
2803 "Couldn't write to $config: $!\n";
2804 print $fh "; You should not have to edit it\n" or
2805 die "Couldn't write to $config: $!\n";
2806 close $fh or die "Couldn't close $config: $!\n";
2808 command('config', @args);
2810 my $err = $@;
2811 if (defined $old_config) {
2812 $ENV{GIT_CONFIG} = $old_config;
2813 } else {
2814 delete $ENV{GIT_CONFIG};
2816 die $err if $err;
2817 wantarray ? @ret : $ret[0];
2820 sub tmp_index_do {
2821 my ($self, $sub) = @_;
2822 my $old_index = $ENV{GIT_INDEX_FILE};
2823 $ENV{GIT_INDEX_FILE} = $self->{index};
2824 $@ = undef;
2825 my @ret = eval {
2826 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2827 mkpath([$dir]) unless -d $dir;
2828 &$sub;
2830 my $err = $@;
2831 if (defined $old_index) {
2832 $ENV{GIT_INDEX_FILE} = $old_index;
2833 } else {
2834 delete $ENV{GIT_INDEX_FILE};
2836 die $err if $err;
2837 wantarray ? @ret : $ret[0];
2840 sub assert_index_clean {
2841 my ($self, $treeish) = @_;
2843 $self->tmp_index_do(sub {
2844 command_noisy('read-tree', $treeish) unless -e $self->{index};
2845 my $x = command_oneline('write-tree');
2846 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2847 /^tree ($::sha1)/mo);
2848 return if $y eq $x;
2850 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2851 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2852 command_noisy('read-tree', $treeish);
2853 $x = command_oneline('write-tree');
2854 if ($y ne $x) {
2855 ::fatal "trees ($treeish) $y != $x\n",
2856 "Something is seriously wrong...";
2861 sub get_commit_parents {
2862 my ($self, $log_entry) = @_;
2863 my (%seen, @ret, @tmp);
2864 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2865 if (my $ip = $self->{inject_parents}) {
2866 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2867 push @tmp, $commit;
2870 if (my $cur = ::verify_ref($self->refname.'^0')) {
2871 push @tmp, $cur;
2873 if (my $ipd = $self->{inject_parents_dcommit}) {
2874 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2875 push @tmp, @$commit;
2878 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2879 while (my $p = shift @tmp) {
2880 next if $seen{$p};
2881 $seen{$p} = 1;
2882 push @ret, $p;
2884 @ret;
2887 sub rewrite_root {
2888 my ($self) = @_;
2889 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2890 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2891 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2892 if ($rwr) {
2893 $rwr =~ s#/+$##;
2894 if ($rwr !~ m#^[a-z\+]+://#) {
2895 die "$rwr is not a valid URL (key: $k)\n";
2898 $self->{-rewrite_root} = $rwr;
2901 sub rewrite_uuid {
2902 my ($self) = @_;
2903 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2904 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2905 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2906 if ($rwid) {
2907 $rwid =~ s#/+$##;
2908 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2909 die "$rwid is not a valid UUID (key: $k)\n";
2912 $self->{-rewrite_uuid} = $rwid;
2915 sub metadata_url {
2916 my ($self) = @_;
2917 ($self->rewrite_root || $self->{url}) .
2918 (length $self->{path} ? '/' . $self->{path} : '');
2921 sub full_url {
2922 my ($self) = @_;
2923 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2926 sub full_pushurl {
2927 my ($self) = @_;
2928 if ($self->{pushurl}) {
2929 return $self->{pushurl} . (length $self->{path} ? '/' .
2930 $self->{path} : '');
2931 } else {
2932 return $self->full_url;
2936 sub set_commit_header_env {
2937 my ($log_entry) = @_;
2938 my %env;
2939 foreach my $ned (qw/NAME EMAIL DATE/) {
2940 foreach my $ac (qw/AUTHOR COMMITTER/) {
2941 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2945 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2946 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2947 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2949 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2950 ? $log_entry->{commit_name}
2951 : $log_entry->{name};
2952 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2953 ? $log_entry->{commit_email}
2954 : $log_entry->{email};
2955 \%env;
2958 sub restore_commit_header_env {
2959 my ($env) = @_;
2960 foreach my $ned (qw/NAME EMAIL DATE/) {
2961 foreach my $ac (qw/AUTHOR COMMITTER/) {
2962 my $k = "GIT_${ac}_${ned}";
2963 if (defined $env->{$k}) {
2964 $ENV{$k} = $env->{$k};
2965 } else {
2966 delete $ENV{$k};
2972 sub gc {
2973 command_noisy('gc', '--auto');
2976 sub do_git_commit {
2977 my ($self, $log_entry) = @_;
2978 my $lr = $self->last_rev;
2979 if (defined $lr && $lr >= $log_entry->{revision}) {
2980 die "Last fetched revision of ", $self->refname,
2981 " was r$lr, but we are about to fetch: ",
2982 "r$log_entry->{revision}!\n";
2984 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2985 croak "$log_entry->{revision} = $c already exists! ",
2986 "Why are we refetching it?\n";
2988 my $old_env = set_commit_header_env($log_entry);
2989 my $tree = $log_entry->{tree};
2990 if (!defined $tree) {
2991 $tree = $self->tmp_index_do(sub {
2992 command_oneline('write-tree') });
2994 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2996 my @exec = ('git', 'commit-tree', $tree);
2997 foreach ($self->get_commit_parents($log_entry)) {
2998 push @exec, '-p', $_;
3000 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3001 or croak $!;
3002 binmode $msg_fh;
3004 # we always get UTF-8 from SVN, but we may want our commits in
3005 # a different encoding.
3006 if (my $enc = Git::config('i18n.commitencoding')) {
3007 require Encode;
3008 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3010 print $msg_fh $log_entry->{log} or croak $!;
3011 restore_commit_header_env($old_env);
3012 unless ($self->no_metadata) {
3013 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3014 or croak $!;
3016 $msg_fh->flush == 0 or croak $!;
3017 close $msg_fh or croak $!;
3018 chomp(my $commit = do { local $/; <$out_fh> });
3019 close $out_fh or croak $!;
3020 waitpid $pid, 0;
3021 croak $? if $?;
3022 if ($commit !~ /^$::sha1$/o) {
3023 die "Failed to commit, invalid sha1: $commit\n";
3026 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3028 $self->{last_rev} = $log_entry->{revision};
3029 $self->{last_commit} = $commit;
3030 print "r$log_entry->{revision}" unless $::_q > 1;
3031 if (defined $log_entry->{svm_revision}) {
3032 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3033 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3034 0, $self->svm_uuid);
3036 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3037 if (--$_gc_nr == 0) {
3038 $_gc_nr = $_gc_period;
3039 gc();
3041 return $commit;
3044 sub match_paths {
3045 my ($self, $paths, $r) = @_;
3046 return 1 if $self->{path} eq '';
3047 if (my $path = $paths->{"/$self->{path}"}) {
3048 return ($path->{action} eq 'D') ? 0 : 1;
3050 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3051 if (grep /$self->{path_regex}/, keys %$paths) {
3052 return 1;
3054 my $c = '';
3055 foreach (split m#/#, $self->{path}) {
3056 $c .= "/$_";
3057 next unless ($paths->{$c} &&
3058 ($paths->{$c}->{action} =~ /^[AR]$/));
3059 if ($self->ra->check_path($self->{path}, $r) ==
3060 $SVN::Node::dir) {
3061 return 1;
3064 return 0;
3067 sub find_parent_branch {
3068 my ($self, $paths, $rev) = @_;
3069 return undef unless $self->follow_parent;
3070 unless (defined $paths) {
3071 my $err_handler = $SVN::Error::handler;
3072 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3073 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3074 sub { $paths = $_[0] });
3075 $SVN::Error::handler = $err_handler;
3077 return undef unless defined $paths;
3079 # look for a parent from another branch:
3080 my @b_path_components = split m#/#, $self->{path};
3081 my @a_path_components;
3082 my $i;
3083 while (@b_path_components) {
3084 $i = $paths->{'/'.join('/', @b_path_components)};
3085 last if $i && defined $i->{copyfrom_path};
3086 unshift(@a_path_components, pop(@b_path_components));
3088 return undef unless defined $i && defined $i->{copyfrom_path};
3089 my $branch_from = $i->{copyfrom_path};
3090 if (@a_path_components) {
3091 print STDERR "branch_from: $branch_from => ";
3092 $branch_from .= '/'.join('/', @a_path_components);
3093 print STDERR $branch_from, "\n";
3095 my $r = $i->{copyfrom_rev};
3096 my $repos_root = $self->ra->{repos_root};
3097 my $url = $self->ra->{url};
3098 my $new_url = $url . $branch_from;
3099 print STDERR "Found possible branch point: ",
3100 "$new_url => ", $self->full_url, ", $r\n"
3101 unless $::_q > 1;
3102 $branch_from =~ s#^/##;
3103 my $gs = $self->other_gs($new_url, $url,
3104 $branch_from, $r, $self->{ref_id});
3105 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3107 my ($base, $head);
3108 if (!defined $r0 || !defined $parent) {
3109 ($base, $head) = parse_revision_argument(0, $r);
3110 } else {
3111 if ($r0 < $r) {
3112 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3113 0, 1, sub { $base = $_[1] - 1 });
3116 if (defined $base && $base <= $r) {
3117 $gs->fetch($base, $r);
3119 ($r0, $parent) = $gs->find_rev_before($r, 1);
3121 if (defined $r0 && defined $parent) {
3122 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3123 unless $::_q > 1;
3124 my $ed;
3125 if ($self->ra->can_do_switch) {
3126 $self->assert_index_clean($parent);
3127 print STDERR "Following parent with do_switch\n"
3128 unless $::_q > 1;
3129 # do_switch works with svn/trunk >= r22312, but that
3130 # is not included with SVN 1.4.3 (the latest version
3131 # at the moment), so we can't rely on it
3132 $self->{last_rev} = $r0;
3133 $self->{last_commit} = $parent;
3134 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3135 $gs->ra->gs_do_switch($r0, $rev, $gs,
3136 $self->full_url, $ed)
3137 or die "SVN connection failed somewhere...\n";
3138 } elsif ($self->ra->trees_match($new_url, $r0,
3139 $self->full_url, $rev)) {
3140 print STDERR "Trees match:\n",
3141 " $new_url\@$r0\n",
3142 " ${\$self->full_url}\@$rev\n",
3143 "Following parent with no changes\n"
3144 unless $::_q > 1;
3145 $self->tmp_index_do(sub {
3146 command_noisy('read-tree', $parent);
3148 $self->{last_commit} = $parent;
3149 } else {
3150 print STDERR "Following parent with do_update\n"
3151 unless $::_q > 1;
3152 $ed = SVN::Git::Fetcher->new($self);
3153 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3154 or die "SVN connection failed somewhere...\n";
3156 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3157 return $self->make_log_entry($rev, [$parent], $ed);
3159 return undef;
3162 sub do_fetch {
3163 my ($self, $paths, $rev) = @_;
3164 my $ed;
3165 my ($last_rev, @parents);
3166 if (my $lc = $self->last_commit) {
3167 # we can have a branch that was deleted, then re-added
3168 # under the same name but copied from another path, in
3169 # which case we'll have multiple parents (we don't
3170 # want to break the original ref, nor lose copypath info):
3171 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3172 push @{$log_entry->{parents}}, $lc;
3173 return $log_entry;
3175 $ed = SVN::Git::Fetcher->new($self);
3176 $last_rev = $self->{last_rev};
3177 $ed->{c} = $lc;
3178 @parents = ($lc);
3179 } else {
3180 $last_rev = $rev;
3181 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3182 return $log_entry;
3184 $ed = SVN::Git::Fetcher->new($self);
3186 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3187 die "SVN connection failed somewhere...\n";
3189 $self->make_log_entry($rev, \@parents, $ed);
3192 sub mkemptydirs {
3193 my ($self, $r) = @_;
3195 sub scan {
3196 my ($r, $empty_dirs, $line) = @_;
3197 if (defined $r && $line =~ /^r(\d+)$/) {
3198 return 0 if $1 > $r;
3199 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3200 $empty_dirs->{$1} = 1;
3201 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3202 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3203 delete @$empty_dirs{@d};
3205 1; # continue
3208 my %empty_dirs = ();
3209 my $gz_file = "$self->{dir}/unhandled.log.gz";
3210 if (-f $gz_file) {
3211 if (!$can_compress) {
3212 warn "Compress::Zlib could not be found; ",
3213 "empty directories in $gz_file will not be read\n";
3214 } else {
3215 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3216 die "Unable to open $gz_file: $!\n";
3217 my $line;
3218 while ($gz->gzreadline($line) > 0) {
3219 scan($r, \%empty_dirs, $line) or last;
3221 $gz->gzclose;
3225 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3226 binmode $fh or croak "binmode: $!";
3227 while (<$fh>) {
3228 scan($r, \%empty_dirs, $_) or last;
3230 close $fh;
3233 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3234 foreach my $d (sort keys %empty_dirs) {
3235 $d = uri_decode($d);
3236 $d =~ s/$strip//;
3237 next unless length($d);
3238 next if -d $d;
3239 if (-e $d) {
3240 warn "$d exists but is not a directory\n";
3241 } else {
3242 print "creating empty directory: $d\n";
3243 mkpath([$d]);
3248 sub get_untracked {
3249 my ($self, $ed) = @_;
3250 my @out;
3251 my $h = $ed->{empty};
3252 foreach (sort keys %$h) {
3253 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3254 push @out, " $act: " . uri_encode($_);
3255 warn "W: $act: $_\n";
3257 foreach my $t (qw/dir_prop file_prop/) {
3258 $h = $ed->{$t} or next;
3259 foreach my $path (sort keys %$h) {
3260 my $ppath = $path eq '' ? '.' : $path;
3261 foreach my $prop (sort keys %{$h->{$path}}) {
3262 next if $SKIP_PROP{$prop};
3263 my $v = $h->{$path}->{$prop};
3264 my $t_ppath_prop = "$t: " .
3265 uri_encode($ppath) . ' ' .
3266 uri_encode($prop);
3267 if (defined $v) {
3268 push @out, " +$t_ppath_prop " .
3269 uri_encode($v);
3270 } else {
3271 push @out, " -$t_ppath_prop";
3276 foreach my $t (qw/absent_file absent_directory/) {
3277 $h = $ed->{$t} or next;
3278 foreach my $parent (sort keys %$h) {
3279 foreach my $path (sort @{$h->{$parent}}) {
3280 push @out, " $t: " .
3281 uri_encode("$parent/$path");
3282 warn "W: $t: $parent/$path ",
3283 "Insufficient permissions?\n";
3287 \@out;
3290 sub get_tz {
3291 # some systmes don't handle or mishandle %z, so be creative.
3292 my $t = shift || time;
3293 my $gm = timelocal(gmtime($t));
3294 my $sign = qw( + + - )[ $t <=> $gm ];
3295 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3298 # parse_svn_date(DATE)
3299 # --------------------
3300 # Given a date (in UTC) from Subversion, return a string in the format
3301 # "<TZ Offset> <local date/time>" that Git will use.
3303 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3304 # is true we'll convert it to the local timezone instead.
3305 sub parse_svn_date {
3306 my $date = shift || return '+0000 1970-01-01 00:00:00';
3307 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3308 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3309 croak "Unable to parse date: $date\n";
3310 my $parsed_date; # Set next.
3312 if ($Git::SVN::_localtime) {
3313 # Translate the Subversion datetime to an epoch time.
3314 # Begin by switching ourselves to $date's timezone, UTC.
3315 my $old_env_TZ = $ENV{TZ};
3316 $ENV{TZ} = 'UTC';
3318 my $epoch_in_UTC =
3319 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3321 # Determine our local timezone (including DST) at the
3322 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3323 # value of TZ, if any, at the time we were run.
3324 if (defined $Git::SVN::Log::TZ) {
3325 $ENV{TZ} = $Git::SVN::Log::TZ;
3326 } else {
3327 delete $ENV{TZ};
3330 my $our_TZ = get_tz();
3332 # This converts $epoch_in_UTC into our local timezone.
3333 my ($sec, $min, $hour, $mday, $mon, $year,
3334 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3336 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3337 $our_TZ, $year + 1900, $mon + 1,
3338 $mday, $hour, $min, $sec);
3340 # Reset us to the timezone in effect when we entered
3341 # this routine.
3342 if (defined $old_env_TZ) {
3343 $ENV{TZ} = $old_env_TZ;
3344 } else {
3345 delete $ENV{TZ};
3347 } else {
3348 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3351 return $parsed_date;
3354 sub other_gs {
3355 my ($self, $new_url, $url,
3356 $branch_from, $r, $old_ref_id) = @_;
3357 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3358 unless ($gs) {
3359 my $ref_id = $old_ref_id;
3360 $ref_id =~ s/\@\d+-*$//;
3361 $ref_id .= "\@$r";
3362 # just grow a tail if we're not unique enough :x
3363 $ref_id .= '-' while find_ref($ref_id);
3364 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3365 if ($u =~ s#^\Q$url\E(/|$)##) {
3366 $p = $u;
3367 $u = $url;
3368 $repo_id = $self->{repo_id};
3370 while (1) {
3371 # It is possible to tag two different subdirectories at
3372 # the same revision. If the url for an existing ref
3373 # does not match, we must either find a ref with a
3374 # matching url or create a new ref by growing a tail.
3375 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3376 my (undef, $max_commit) = $gs->rev_map_max(1);
3377 last if (!$max_commit);
3378 my ($url) = ::cmt_metadata($max_commit);
3379 last if ($url eq $gs->metadata_url);
3380 $ref_id .= '-';
3382 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3387 sub call_authors_prog {
3388 my ($orig_author) = @_;
3389 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3390 my $author = `$::_authors_prog $orig_author`;
3391 if ($? != 0) {
3392 die "$::_authors_prog failed with exit code $?\n"
3394 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3395 my ($name, $email) = ($1, $2);
3396 $email = undef if length $2 == 0;
3397 return [$name, $email];
3398 } else {
3399 die "Author: $orig_author: $::_authors_prog returned "
3400 . "invalid author format: $author\n";
3404 sub check_author {
3405 my ($author) = @_;
3406 if (!defined $author || length $author == 0) {
3407 $author = '(no author)';
3409 if (!defined $::users{$author}) {
3410 if (defined $::_authors_prog) {
3411 $::users{$author} = call_authors_prog($author);
3412 } elsif (defined $::_authors) {
3413 die "Author: $author not defined in $::_authors file\n";
3416 $author;
3419 sub find_extra_svk_parents {
3420 my ($self, $ed, $tickets, $parents) = @_;
3421 # aha! svk:merge property changed...
3422 my @tickets = split "\n", $tickets;
3423 my @known_parents;
3424 for my $ticket ( @tickets ) {
3425 my ($uuid, $path, $rev) = split /:/, $ticket;
3426 if ( $uuid eq $self->ra_uuid ) {
3427 my $url = $self->{url};
3428 my $repos_root = $url;
3429 my $branch_from = $path;
3430 $branch_from =~ s{^/}{};
3431 my $gs = $self->other_gs($repos_root."/".$branch_from,
3432 $url,
3433 $branch_from,
3434 $rev,
3435 $self->{ref_id});
3436 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3437 # wahey! we found it, but it might be
3438 # an old one (!)
3439 push @known_parents, [ $rev, $commit ];
3443 # Ordering matters; highest-numbered commit merge tickets
3444 # first, as they may account for later merge ticket additions
3445 # or changes.
3446 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3447 for my $parent ( @known_parents ) {
3448 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3449 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3450 my $new;
3451 while ( <$msg_fh> ) {
3452 $new=1;last;
3454 command_close_pipe($msg_fh, $ctx);
3455 if ( $new ) {
3456 print STDERR
3457 "Found merge parent (svk:merge ticket): $parent\n";
3458 push @$parents, $parent;
3463 sub lookup_svn_merge {
3464 my $uuid = shift;
3465 my $url = shift;
3466 my $merge = shift;
3468 my ($source, $revs) = split ":", $merge;
3469 my $path = $source;
3470 $path =~ s{^/}{};
3471 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3472 if ( !$gs ) {
3473 warn "Couldn't find revmap for $url$source\n";
3474 return;
3476 my @ranges = split ",", $revs;
3477 my ($tip, $tip_commit);
3478 my @merged_commit_ranges;
3479 # find the tip
3480 for my $range ( @ranges ) {
3481 my ($bottom, $top) = split "-", $range;
3482 $top ||= $bottom;
3483 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3484 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3486 unless ($top_commit and $bottom_commit) {
3487 warn "W:unknown path/rev in svn:mergeinfo "
3488 ."dirprop: $source:$range\n";
3489 next;
3492 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3493 push @merged_commit_ranges,
3494 "$bottom_commit^..$top_commit";
3495 } else {
3496 push @merged_commit_ranges, "$top_commit";
3499 if ( !defined $tip or $top > $tip ) {
3500 $tip = $top;
3501 $tip_commit = $top_commit;
3504 return ($tip_commit, @merged_commit_ranges);
3507 sub _rev_list {
3508 my ($msg_fh, $ctx) = command_output_pipe(
3509 "rev-list", @_,
3511 my @rv;
3512 while ( <$msg_fh> ) {
3513 chomp;
3514 push @rv, $_;
3516 command_close_pipe($msg_fh, $ctx);
3517 @rv;
3520 sub check_cherry_pick {
3521 my $base = shift;
3522 my $tip = shift;
3523 my $parents = shift;
3524 my @ranges = @_;
3525 my %commits = map { $_ => 1 }
3526 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3527 for my $range ( @ranges ) {
3528 delete @commits{_rev_list($range, "--")};
3530 for my $commit (keys %commits) {
3531 if (has_no_changes($commit)) {
3532 delete $commits{$commit};
3535 return (keys %commits);
3538 sub has_no_changes {
3539 my $commit = shift;
3541 my @revs = split / /, command_oneline(
3542 qw(rev-list --parents -1 -m), $commit);
3544 # Commits with no parents, e.g. the start of a partial branch,
3545 # have changes by definition.
3546 return 1 if (@revs < 2);
3548 # Commits with multiple parents, e.g a merge, have no changes
3549 # by definition.
3550 return 0 if (@revs > 2);
3552 return (command_oneline("rev-parse", "$commit^{tree}") eq
3553 command_oneline("rev-parse", "$commit~1^{tree}"));
3556 # The GIT_DIR environment variable is not always set until after the command
3557 # line arguments are processed, so we can't memoize in a BEGIN block.
3559 my $memoized = 0;
3561 sub memoize_svn_mergeinfo_functions {
3562 return if $memoized;
3563 $memoized = 1;
3565 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3566 mkpath([$cache_path]) unless -d $cache_path;
3568 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3569 "$cache_path/lookup_svn_merge.db", 'nstore';
3570 memoize 'lookup_svn_merge',
3571 SCALAR_CACHE => 'FAULT',
3572 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3575 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3576 "$cache_path/check_cherry_pick.db", 'nstore';
3577 memoize 'check_cherry_pick',
3578 SCALAR_CACHE => 'FAULT',
3579 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3582 tie my %has_no_changes_cache => 'Memoize::Storable',
3583 "$cache_path/has_no_changes.db", 'nstore';
3584 memoize 'has_no_changes',
3585 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3586 LIST_CACHE => 'FAULT',
3590 sub unmemoize_svn_mergeinfo_functions {
3591 return if not $memoized;
3592 $memoized = 0;
3594 Memoize::unmemoize 'lookup_svn_merge';
3595 Memoize::unmemoize 'check_cherry_pick';
3596 Memoize::unmemoize 'has_no_changes';
3599 Memoize::memoize 'Git::SVN::repos_root';
3602 END {
3603 # Force cache writeout explicitly instead of waiting for
3604 # global destruction to avoid segfault in Storable:
3605 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3606 unmemoize_svn_mergeinfo_functions();
3609 sub parents_exclude {
3610 my $parents = shift;
3611 my @commits = @_;
3612 return unless @commits;
3614 my @excluded;
3615 my $excluded;
3616 do {
3617 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3618 $excluded = command_oneline(@cmd);
3619 if ( $excluded ) {
3620 my @new;
3621 my $found;
3622 for my $commit ( @commits ) {
3623 if ( $commit eq $excluded ) {
3624 push @excluded, $commit;
3625 $found++;
3626 last;
3628 else {
3629 push @new, $commit;
3632 die "saw commit '$excluded' in rev-list output, "
3633 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3634 unless $found;
3635 @commits = @new;
3638 while ($excluded and @commits);
3640 return @excluded;
3644 # note: this function should only be called if the various dirprops
3645 # have actually changed
3646 sub find_extra_svn_parents {
3647 my ($self, $ed, $mergeinfo, $parents) = @_;
3648 # aha! svk:merge property changed...
3650 memoize_svn_mergeinfo_functions();
3652 # We first search for merged tips which are not in our
3653 # history. Then, we figure out which git revisions are in
3654 # that tip, but not this revision. If all of those revisions
3655 # are now marked as merge, we can add the tip as a parent.
3656 my @merges = split "\n", $mergeinfo;
3657 my @merge_tips;
3658 my $url = $self->{url};
3659 my $uuid = $self->ra_uuid;
3660 my %ranges;
3661 for my $merge ( @merges ) {
3662 my ($tip_commit, @ranges) =
3663 lookup_svn_merge( $uuid, $url, $merge );
3664 unless (!$tip_commit or
3665 grep { $_ eq $tip_commit } @$parents ) {
3666 push @merge_tips, $tip_commit;
3667 $ranges{$tip_commit} = \@ranges;
3668 } else {
3669 push @merge_tips, undef;
3673 my %excluded = map { $_ => 1 }
3674 parents_exclude($parents, grep { defined } @merge_tips);
3676 # check merge tips for new parents
3677 my @new_parents;
3678 for my $merge_tip ( @merge_tips ) {
3679 my $spec = shift @merges;
3680 next unless $merge_tip and $excluded{$merge_tip};
3682 my $ranges = $ranges{$merge_tip};
3684 # check out 'new' tips
3685 my $merge_base;
3686 eval {
3687 $merge_base = command_oneline(
3688 "merge-base",
3689 @$parents, $merge_tip,
3692 if ($@) {
3693 die "An error occurred during merge-base"
3694 unless $@->isa("Git::Error::Command");
3696 warn "W: Cannot find common ancestor between ".
3697 "@$parents and $merge_tip. Ignoring merge info.\n";
3698 next;
3701 # double check that there are no missing non-merge commits
3702 my (@incomplete) = check_cherry_pick(
3703 $merge_base, $merge_tip,
3704 $parents,
3705 @$ranges,
3708 if ( @incomplete ) {
3709 warn "W:svn cherry-pick ignored ($spec) - missing "
3710 .@incomplete." commit(s) (eg $incomplete[0])\n";
3711 } else {
3712 warn
3713 "Found merge parent (svn:mergeinfo prop): ",
3714 $merge_tip, "\n";
3715 push @new_parents, $merge_tip;
3719 # cater for merges which merge commits from multiple branches
3720 if ( @new_parents > 1 ) {
3721 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3722 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3723 next if $i == $j;
3724 next unless $new_parents[$i];
3725 next unless $new_parents[$j];
3726 my $revs = command_oneline(
3727 "rev-list", "-1",
3728 "$new_parents[$i]..$new_parents[$j]",
3730 if ( !$revs ) {
3731 undef($new_parents[$j]);
3736 push @$parents, grep { defined } @new_parents;
3739 sub make_log_entry {
3740 my ($self, $rev, $parents, $ed) = @_;
3741 my $untracked = $self->get_untracked($ed);
3743 my @parents = @$parents;
3744 my $ps = $ed->{path_strip} || "";
3745 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3746 my $props = $ed->{dir_prop}{$path};
3747 if ( $props->{"svk:merge"} ) {
3748 $self->find_extra_svk_parents
3749 ($ed, $props->{"svk:merge"}, \@parents);
3751 if ( $props->{"svn:mergeinfo"} ) {
3752 $self->find_extra_svn_parents
3753 ($ed,
3754 $props->{"svn:mergeinfo"},
3755 \@parents);
3759 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3760 print $un "r$rev\n" or croak $!;
3761 print $un $_, "\n" foreach @$untracked;
3762 my %log_entry = ( parents => \@parents, revision => $rev,
3763 log => '');
3765 my $headrev;
3766 my $logged = delete $self->{logged_rev_props};
3767 if (!$logged || $self->{-want_revprops}) {
3768 my $rp = $self->ra->rev_proplist($rev);
3769 foreach (sort keys %$rp) {
3770 my $v = $rp->{$_};
3771 if (/^svn:(author|date|log)$/) {
3772 $log_entry{$1} = $v;
3773 } elsif ($_ eq 'svm:headrev') {
3774 $headrev = $v;
3775 } else {
3776 print $un " rev_prop: ", uri_encode($_), ' ',
3777 uri_encode($v), "\n";
3780 } else {
3781 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3783 close $un or croak $!;
3785 $log_entry{date} = parse_svn_date($log_entry{date});
3786 $log_entry{log} .= "\n";
3787 my $author = $log_entry{author} = check_author($log_entry{author});
3788 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3789 : ($author, undef);
3791 my ($commit_name, $commit_email) = ($name, $email);
3792 if ($_use_log_author) {
3793 my $name_field;
3794 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {