am: Use cat instead of echo to avoid DOS line-endings (fixes t4150)
[git/dscho.git] / git-svn.perl
blob31d02b5f70f553e27e0bdc760355909cb535f813
1 #!/usr/bin/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 }
40 # All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
41 # repository decides to close the connection which we expect to be kept alive.
42 $SIG{PIPE} = 'IGNORE';
44 # Given a dot separated version number, "subtract" it from
45 # the SVN::Core::VERSION; non-negaitive return means the SVN::Core
46 # is at least at the version the caller asked for.
47 sub compare_svn_version {
48 my (@ours) = split(/\./, $SVN::Core::VERSION);
49 my (@theirs) = split(/\./, $_[0]);
50 my ($i, $diff);
52 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
53 $diff = $ours[$i] - $theirs[$i];
54 return $diff if ($diff);
56 return 1 if ($i < @ours);
57 return -1 if ($i < @theirs);
58 return 0;
61 sub _req_svn {
62 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
63 require SVN::Ra;
64 require SVN::Delta;
65 if (::compare_svn_version('1.1.0') < 0) {
66 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
69 my $can_compress = eval { require Compress::Zlib; 1};
70 push @Git::SVN::Ra::ISA, 'SVN::Ra';
71 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
72 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
73 use Carp qw/croak/;
74 use Digest::MD5;
75 use IO::File qw//;
76 use File::Basename qw/dirname basename/;
77 use File::Path qw/mkpath/;
78 use File::Spec;
79 use File::Find;
80 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
81 use IPC::Open3;
82 use Git;
83 use Memoize; # core since 5.8.0, Jul 2002
85 BEGIN {
86 # import functions from Git into our packages, en masse
87 no strict 'refs';
88 foreach (qw/command command_oneline command_noisy command_output_pipe
89 command_input_pipe command_close_pipe
90 command_bidi_pipe command_close_bidi_pipe/) {
91 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
92 Git::SVN::Migration Git::SVN::Log Git::SVN),
93 __PACKAGE__) {
94 *{"${package}::$_"} = \&{"Git::$_"};
97 Memoize::memoize 'Git::config';
98 Memoize::memoize 'Git::config_bool';
101 my ($SVN);
103 $sha1 = qr/[a-f\d]{40}/;
104 $sha1_short = qr/[a-f\d]{4,40}/;
105 my ($_stdin, $_help, $_edit,
106 $_message, $_file, $_branch_dest,
107 $_template, $_shared,
108 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
109 $_merge, $_strategy, $_dry_run, $_local,
110 $_prefix, $_no_checkout, $_url, $_verbose,
111 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
112 $Git::SVN::_follow_parent = 1;
113 $SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
114 $_q ||= 0;
115 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
116 'config-dir=s' => \$Git::SVN::Ra::config_dir,
117 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
118 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
119 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
120 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
121 'authors-file|A=s' => \$_authors,
122 'authors-prog=s' => \$_authors_prog,
123 'repack:i' => \$Git::SVN::_repack,
124 'noMetadata' => \$Git::SVN::_no_metadata,
125 'useSvmProps' => \$Git::SVN::_use_svm_props,
126 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
127 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
128 'no-checkout' => \$_no_checkout,
129 'quiet|q+' => \$_q,
130 'repack-flags|repack-args|repack-opts=s' =>
131 \$Git::SVN::_repack_flags,
132 'use-log-author' => \$Git::SVN::_use_log_author,
133 'add-author-from' => \$Git::SVN::_add_author_from,
134 'localtime' => \$Git::SVN::_localtime,
135 %remote_opts );
137 my ($_trunk, @_tags, @_branches, $_stdlayout);
138 my %icv;
139 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
140 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
141 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
142 'stdlayout|s' => \$_stdlayout,
143 'minimize-url|m!' => \$Git::SVN::_minimize_url,
144 'no-metadata' => sub { $icv{noMetadata} = 1 },
145 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
146 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
147 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
148 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
149 %remote_opts );
150 my %cmt_opts = ( 'edit|e' => \$_edit,
151 'rmdir' => \$SVN::Git::Editor::_rmdir,
152 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
153 'l=i' => \$SVN::Git::Editor::_rename_limit,
154 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
157 my %cmd = (
158 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
159 { 'revision|r=s' => \$_revision,
160 'fetch-all|all' => \$_fetch_all,
161 'parent|p' => \$_fetch_parent,
162 %fc_opts } ],
163 clone => [ \&cmd_clone, "Initialize and fetch revisions",
164 { 'revision|r=s' => \$_revision,
165 'preserve-empty-dirs' =>
166 \$SVN::Git::Fetcher::_preserve_empty_dirs,
167 'placeholder-filename=s' =>
168 \$SVN::Git::Fetcher::_placeholder_filename,
169 %fc_opts, %init_opts } ],
170 init => [ \&cmd_init, "Initialize a repo for tracking" .
171 " (requires URL argument)",
172 \%init_opts ],
173 'multi-init' => [ \&cmd_multi_init,
174 "Deprecated alias for ".
175 "'$0 init -T<trunk> -b<branches> -t<tags>'",
176 \%init_opts ],
177 dcommit => [ \&cmd_dcommit,
178 'Commit several diffs to merge with upstream',
179 { 'merge|m|M' => \$_merge,
180 'strategy|s=s' => \$_strategy,
181 'verbose|v' => \$_verbose,
182 'dry-run|n' => \$_dry_run,
183 'fetch-all|all' => \$_fetch_all,
184 'commit-url=s' => \$_commit_url,
185 'revision|r=i' => \$_revision,
186 'no-rebase' => \$_no_rebase,
187 'mergeinfo=s' => \$_merge_info,
188 'interactive|i' => \$_interactive,
189 %cmt_opts, %fc_opts } ],
190 branch => [ \&cmd_branch,
191 'Create a branch in the SVN repository',
192 { 'message|m=s' => \$_message,
193 'destination|d=s' => \$_branch_dest,
194 'dry-run|n' => \$_dry_run,
195 'tag|t' => \$_tag,
196 'username=s' => \$Git::SVN::Prompt::_username,
197 'commit-url=s' => \$_commit_url } ],
198 tag => [ sub { $_tag = 1; cmd_branch(@_) },
199 'Create a tag in the SVN repository',
200 { 'message|m=s' => \$_message,
201 'destination|d=s' => \$_branch_dest,
202 'dry-run|n' => \$_dry_run,
203 'username=s' => \$Git::SVN::Prompt::_username,
204 'commit-url=s' => \$_commit_url } ],
205 'set-tree' => [ \&cmd_set_tree,
206 "Set an SVN repository to a git tree-ish",
207 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
208 'create-ignore' => [ \&cmd_create_ignore,
209 'Create a .gitignore per svn:ignore',
210 { 'revision|r=i' => \$_revision
211 } ],
212 'mkdirs' => [ \&cmd_mkdirs ,
213 "recreate empty directories after a checkout",
214 { 'revision|r=i' => \$_revision } ],
215 'propget' => [ \&cmd_propget,
216 'Print the value of a property on a file or directory',
217 { 'revision|r=i' => \$_revision } ],
218 'proplist' => [ \&cmd_proplist,
219 'List all properties of a file or directory',
220 { 'revision|r=i' => \$_revision } ],
221 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
222 { 'revision|r=i' => \$_revision
223 } ],
224 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
225 { 'revision|r=i' => \$_revision
226 } ],
227 'multi-fetch' => [ \&cmd_multi_fetch,
228 "Deprecated alias for $0 fetch --all",
229 { 'revision|r=s' => \$_revision, %fc_opts } ],
230 'migrate' => [ sub { },
231 # no-op, we automatically run this anyways,
232 'Migrate configuration/metadata/layout from
233 previous versions of git-svn',
234 { 'minimize' => \$Git::SVN::Migration::_minimize,
235 %remote_opts } ],
236 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
237 { 'limit=i' => \$Git::SVN::Log::limit,
238 'revision|r=s' => \$_revision,
239 'verbose|v' => \$Git::SVN::Log::verbose,
240 'incremental' => \$Git::SVN::Log::incremental,
241 'oneline' => \$Git::SVN::Log::oneline,
242 'show-commit' => \$Git::SVN::Log::show_commit,
243 'non-recursive' => \$Git::SVN::Log::non_recursive,
244 'authors-file|A=s' => \$_authors,
245 'color' => \$Git::SVN::Log::color,
246 'pager=s' => \$Git::SVN::Log::pager
247 } ],
248 'find-rev' => [ \&cmd_find_rev,
249 "Translate between SVN revision numbers and tree-ish",
250 {} ],
251 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
252 { 'merge|m|M' => \$_merge,
253 'verbose|v' => \$_verbose,
254 'strategy|s=s' => \$_strategy,
255 'local|l' => \$_local,
256 'fetch-all|all' => \$_fetch_all,
257 'dry-run|n' => \$_dry_run,
258 %fc_opts } ],
259 'commit-diff' => [ \&cmd_commit_diff,
260 'Commit a diff between two trees',
261 { 'message|m=s' => \$_message,
262 'file|F=s' => \$_file,
263 'revision|r=s' => \$_revision,
264 %cmt_opts } ],
265 'info' => [ \&cmd_info,
266 "Show info about the latest SVN revision
267 on the current branch",
268 { 'url' => \$_url, } ],
269 'blame' => [ \&Git::SVN::Log::cmd_blame,
270 "Show what revision and author last modified each line of a file",
271 { 'git-format' => \$_git_format } ],
272 'reset' => [ \&cmd_reset,
273 "Undo fetches back to the specified SVN revision",
274 { 'revision|r=s' => \$_revision,
275 'parent|p' => \$_fetch_parent } ],
276 'gc' => [ \&cmd_gc,
277 "Compress unhandled.log files in .git/svn and remove " .
278 "index files in .git/svn",
279 {} ],
282 use Term::ReadLine;
283 package FakeTerm;
284 sub new {
285 my ($class, $reason) = @_;
286 return bless \$reason, shift;
288 sub readline {
289 my $self = shift;
290 die "Cannot use readline on FakeTerm: $$self";
292 package main;
294 my $term = eval {
295 $ENV{"GIT_SVN_NOTTY"}
296 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
297 : new Term::ReadLine 'git-svn';
299 if ($@) {
300 $term = new FakeTerm "$@: going non-interactive";
303 my $cmd;
304 for (my $i = 0; $i < @ARGV; $i++) {
305 if (defined $cmd{$ARGV[$i]}) {
306 $cmd = $ARGV[$i];
307 splice @ARGV, $i, 1;
308 last;
309 } elsif ($ARGV[$i] eq 'help') {
310 $cmd = $ARGV[$i+1];
311 usage(0);
315 # make sure we're always running at the top-level working directory
316 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
317 unless (-d $ENV{GIT_DIR}) {
318 if ($git_dir_user_set) {
319 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
320 "but it is not a directory\n";
322 my $git_dir = delete $ENV{GIT_DIR};
323 my $cdup = undef;
324 git_cmd_try {
325 $cdup = command_oneline(qw/rev-parse --show-cdup/);
326 $git_dir = '.' unless ($cdup);
327 chomp $cdup if ($cdup);
328 $cdup = "." unless ($cdup && length $cdup);
329 } "Already at toplevel, but $git_dir not found\n";
330 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
331 unless (-d $git_dir) {
332 die "$git_dir still not found after going to ",
333 "'$cdup'\n";
335 $ENV{GIT_DIR} = $git_dir;
337 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
340 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
342 read_git_config(\%opts);
343 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
344 Getopt::Long::Configure('pass_through');
346 my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
347 'minimize-connections' => \$Git::SVN::Migration::_minimize,
348 'id|i=s' => \$Git::SVN::default_ref_id,
349 'svn-remote|remote|R=s' => sub {
350 $Git::SVN::no_reuse_existing = 1;
351 $Git::SVN::default_repo_id = $_[1] });
352 exit 1 if (!$rv && $cmd && $cmd ne 'log');
354 usage(0) if $_help;
355 version() if $_version;
356 usage(1) unless defined $cmd;
357 load_authors() if $_authors;
358 if (defined $_authors_prog) {
359 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
362 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
363 Git::SVN::Migration::migration_check();
365 Git::SVN::init_vars();
366 eval {
367 Git::SVN::verify_remotes_sanity();
368 $cmd{$cmd}->[0]->(@ARGV);
370 fatal $@ if $@;
371 post_fetch_checkout();
372 exit 0;
374 ####################### primary functions ######################
375 sub usage {
376 my $exit = shift || 0;
377 my $fd = $exit ? \*STDERR : \*STDOUT;
378 print $fd <<"";
379 git-svn - bidirectional operations between a single Subversion tree and git
380 Usage: git svn <command> [options] [arguments]\n
382 print $fd "Available commands:\n" unless $cmd;
384 foreach (sort keys %cmd) {
385 next if $cmd && $cmd ne $_;
386 next if /^multi-/; # don't show deprecated commands
387 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
388 foreach (sort keys %{$cmd{$_}->[2]}) {
389 # mixed-case options are for .git/config only
390 next if /[A-Z]/ && /^[a-z]+$/i;
391 # prints out arguments as they should be passed:
392 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
393 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
394 "--$_" : "-$_" }
395 split /\|/,$_)," $x\n";
398 print $fd <<"";
399 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
400 arbitrary identifier if you're tracking multiple SVN branches/repositories in
401 one git repository and want to keep them separate. See git-svn(1) for more
402 information.
404 exit $exit;
407 sub version {
408 ::_req_svn();
409 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
410 exit 0;
413 sub ask {
414 my ($prompt, %arg) = @_;
415 my $valid_re = $arg{valid_re};
416 my $default = $arg{default};
417 my $resp;
418 my $i = 0;
420 if ( !( defined($term->IN)
421 && defined( fileno($term->IN) )
422 && defined( $term->OUT )
423 && defined( fileno($term->OUT) ) ) ){
424 return defined($default) ? $default : undef;
427 while ($i++ < 10) {
428 $resp = $term->readline($prompt);
429 if (!defined $resp) { # EOF
430 print "\n";
431 return defined $default ? $default : undef;
433 if ($resp eq '' and defined $default) {
434 return $default;
436 if (!defined $valid_re or $resp =~ /$valid_re/) {
437 return $resp;
440 return undef;
443 sub do_git_init_db {
444 unless (-d $ENV{GIT_DIR}) {
445 my @init_db = ('init');
446 push @init_db, "--template=$_template" if defined $_template;
447 if (defined $_shared) {
448 if ($_shared =~ /[a-z]/) {
449 push @init_db, "--shared=$_shared";
450 } else {
451 push @init_db, "--shared";
454 command_noisy(@init_db);
455 $_repository = Git->repository(Repository => ".git");
457 my $set;
458 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
459 foreach my $i (keys %icv) {
460 die "'$set' and '$i' cannot both be set\n" if $set;
461 next unless defined $icv{$i};
462 command_noisy('config', "$pfx.$i", $icv{$i});
463 $set = $i;
465 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
466 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
467 if defined $$ignore_paths_regex;
468 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
469 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
470 if defined $$ignore_refs_regex;
472 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
473 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
474 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
475 command_noisy('config', "$pfx.placeholder-filename", $$fname);
479 sub init_subdir {
480 my $repo_path = shift or return;
481 mkpath([$repo_path]) unless -d $repo_path;
482 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
483 $ENV{GIT_DIR} = '.git';
484 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
487 sub cmd_clone {
488 my ($url, $path) = @_;
489 if (!defined $path &&
490 (defined $_trunk || @_branches || @_tags ||
491 defined $_stdlayout) &&
492 $url !~ m#^[a-z\+]+://#) {
493 $path = $url;
495 $path = basename($url) if !defined $path || !length $path;
496 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
497 cmd_init($url, $path);
498 command_oneline('config', 'svn.authorsfile', $authors_absolute)
499 if $_authors;
500 Git::SVN::fetch_all($Git::SVN::default_repo_id);
503 sub cmd_init {
504 if (defined $_stdlayout) {
505 $_trunk = 'trunk' if (!defined $_trunk);
506 @_tags = 'tags' if (! @_tags);
507 @_branches = 'branches' if (! @_branches);
509 if (defined $_trunk || @_branches || @_tags) {
510 return cmd_multi_init(@_);
512 my $url = shift or die "SVN repository location required ",
513 "as a command-line argument\n";
514 $url = canonicalize_url($url);
515 init_subdir(@_);
516 do_git_init_db();
518 if ($Git::SVN::_minimize_url eq 'unset') {
519 $Git::SVN::_minimize_url = 0;
522 Git::SVN->init($url);
525 sub cmd_fetch {
526 if (grep /^\d+=./, @_) {
527 die "'<rev>=<commit>' fetch arguments are ",
528 "no longer supported.\n";
530 my ($remote) = @_;
531 if (@_ > 1) {
532 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
534 $Git::SVN::no_reuse_existing = undef;
535 if ($_fetch_parent) {
536 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
537 unless ($gs) {
538 die "Unable to determine upstream SVN information from ",
539 "working tree history\n";
541 # just fetch, don't checkout.
542 $_no_checkout = 'true';
543 $_fetch_all ? $gs->fetch_all : $gs->fetch;
544 } elsif ($_fetch_all) {
545 cmd_multi_fetch();
546 } else {
547 $remote ||= $Git::SVN::default_repo_id;
548 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
552 sub cmd_set_tree {
553 my (@commits) = @_;
554 if ($_stdin || !@commits) {
555 print "Reading from stdin...\n";
556 @commits = ();
557 while (<STDIN>) {
558 if (/\b($sha1_short)\b/o) {
559 unshift @commits, $1;
563 my @revs;
564 foreach my $c (@commits) {
565 my @tmp = command('rev-parse',$c);
566 if (scalar @tmp == 1) {
567 push @revs, $tmp[0];
568 } elsif (scalar @tmp > 1) {
569 push @revs, reverse(command('rev-list',@tmp));
570 } else {
571 fatal "Failed to rev-parse $c";
574 my $gs = Git::SVN->new;
575 my ($r_last, $cmt_last) = $gs->last_rev_commit;
576 $gs->fetch;
577 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
578 fatal "There are new revisions that were fetched ",
579 "and need to be merged (or acknowledged) ",
580 "before committing.\nlast rev: $r_last\n",
581 " current: $gs->{last_rev}";
583 $gs->set_tree($_) foreach @revs;
584 print "Done committing ",scalar @revs," revisions to SVN\n";
585 unlink $gs->{index};
588 sub split_merge_info_range {
589 my ($range) = @_;
590 if ($range =~ /(\d+)-(\d+)/) {
591 return (int($1), int($2));
592 } else {
593 return (int($range), int($range));
597 sub combine_ranges {
598 my ($in) = @_;
600 my @fnums = ();
601 my @arr = split(/,/, $in);
602 for my $element (@arr) {
603 my ($start, $end) = split_merge_info_range($element);
604 push @fnums, $start;
607 my @sorted = @arr [ sort {
608 $fnums[$a] <=> $fnums[$b]
609 } 0..$#arr ];
611 my @return = ();
612 my $last = -1;
613 my $first = -1;
614 for my $element (@sorted) {
615 my ($start, $end) = split_merge_info_range($element);
617 if ($last == -1) {
618 $first = $start;
619 $last = $end;
620 next;
622 if ($start <= $last+1) {
623 if ($end > $last) {
624 $last = $end;
626 next;
628 if ($first == $last) {
629 push @return, "$first";
630 } else {
631 push @return, "$first-$last";
633 $first = $start;
634 $last = $end;
637 if ($first != -1) {
638 if ($first == $last) {
639 push @return, "$first";
640 } else {
641 push @return, "$first-$last";
645 return join(',', @return);
648 sub merge_revs_into_hash {
649 my ($hash, $minfo) = @_;
650 my @lines = split(' ', $minfo);
652 for my $line (@lines) {
653 my ($branchpath, $revs) = split(/:/, $line);
655 if (exists($hash->{$branchpath})) {
656 # Merge the two revision sets
657 my $combined = "$hash->{$branchpath},$revs";
658 $hash->{$branchpath} = combine_ranges($combined);
659 } else {
660 # Just do range combining for consolidation
661 $hash->{$branchpath} = combine_ranges($revs);
666 sub merge_merge_info {
667 my ($mergeinfo_one, $mergeinfo_two) = @_;
668 my %result_hash = ();
670 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
671 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
673 my $result = '';
674 # Sort below is for consistency's sake
675 for my $branchname (sort keys(%result_hash)) {
676 my $revlist = $result_hash{$branchname};
677 $result .= "$branchname:$revlist\n"
679 return $result;
682 sub populate_merge_info {
683 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
685 my %parentshash;
686 read_commit_parents(\%parentshash, $d);
687 my @parents = @{$parentshash{$d}};
688 if ($#parents > 0) {
689 # Merge commit
690 my $all_parents_ok = 1;
691 my $aggregate_mergeinfo = '';
692 my $rooturl = $gs->repos_root;
694 if (defined($rewritten_parent)) {
695 # Replace first parent with newly-rewritten version
696 shift @parents;
697 unshift @parents, $rewritten_parent;
700 foreach my $parent (@parents) {
701 my ($branchurl, $svnrev, $paruuid) =
702 cmt_metadata($parent);
704 unless (defined($svnrev)) {
705 # Should have been caught be preflight check
706 fatal "merge commit $d has ancestor $parent, but that change "
707 ."does not have git-svn metadata!";
709 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
710 fatal "commit $parent git-svn metadata changed mid-run!";
712 my $branchpath = $1;
714 my $ra = Git::SVN::Ra->new($branchurl);
715 my (undef, undef, $props) =
716 $ra->get_dir(canonicalize_path("."), $svnrev);
717 my $par_mergeinfo = $props->{'svn:mergeinfo'};
718 unless (defined $par_mergeinfo) {
719 $par_mergeinfo = '';
721 # Merge previous mergeinfo values
722 $aggregate_mergeinfo =
723 merge_merge_info($aggregate_mergeinfo,
724 $par_mergeinfo, 0);
726 next if $parent eq $parents[0]; # Skip first parent
727 # Add new changes being placed in tree by merge
728 my @cmd = (qw/rev-list --reverse/,
729 $parent, qw/--not/);
730 foreach my $par (@parents) {
731 unless ($par eq $parent) {
732 push @cmd, $par;
735 my @revsin = ();
736 my ($revlist, $ctx) = command_output_pipe(@cmd);
737 while (<$revlist>) {
738 my $irev = $_;
739 chomp $irev;
740 my (undef, $csvnrev, undef) =
741 cmt_metadata($irev);
742 unless (defined $csvnrev) {
743 # A child is missing SVN annotations...
744 # this might be OK, or might not be.
745 warn "W:child $irev is merged into revision "
746 ."$d but does not have git-svn metadata. "
747 ."This means git-svn cannot determine the "
748 ."svn revision numbers to place into the "
749 ."svn:mergeinfo property. You must ensure "
750 ."a branch is entirely committed to "
751 ."SVN before merging it in order for "
752 ."svn:mergeinfo population to function "
753 ."properly";
755 push @revsin, $csvnrev;
757 command_close_pipe($revlist, $ctx);
759 last unless $all_parents_ok;
761 # We now have a list of all SVN revnos which are
762 # merged by this particular parent. Integrate them.
763 next if $#revsin == -1;
764 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
765 $aggregate_mergeinfo =
766 merge_merge_info($aggregate_mergeinfo,
767 $newmergeinfo, 1);
769 if ($all_parents_ok and $aggregate_mergeinfo) {
770 return $aggregate_mergeinfo;
774 return undef;
777 sub cmd_dcommit {
778 my $head = shift;
779 command_noisy(qw/update-index --refresh/);
780 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
781 'Cannot dcommit with a dirty index. Commit your changes first, '
782 . "or stash them with `git stash'.\n";
783 $head ||= 'HEAD';
785 my $old_head;
786 if ($head ne 'HEAD') {
787 $old_head = eval {
788 command_oneline([qw/symbolic-ref -q HEAD/])
790 if ($old_head) {
791 $old_head =~ s{^refs/heads/}{};
792 } else {
793 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
795 command(['checkout', $head], STDERR => 0);
798 my @refs;
799 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
800 unless ($gs) {
801 die "Unable to determine upstream SVN information from ",
802 "$head history.\nPerhaps the repository is empty.";
805 if (defined $_commit_url) {
806 $url = $_commit_url;
807 } else {
808 $url = eval { command_oneline('config', '--get',
809 "svn-remote.$gs->{repo_id}.commiturl") };
810 if (!$url) {
811 $url = $gs->full_pushurl
815 my $last_rev = $_revision if defined $_revision;
816 if ($url) {
817 print "Committing to $url ...\n";
819 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
820 if ($_no_rebase && scalar(@$linear_refs) > 1) {
821 warn "Attempting to commit more than one change while ",
822 "--no-rebase is enabled.\n",
823 "If these changes depend on each other, re-running ",
824 "without --no-rebase may be required."
827 if (defined $_interactive){
828 my $ask_default = "y";
829 foreach my $d (@$linear_refs){
830 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
831 while (<$fh>){
832 print $_;
834 command_close_pipe($fh, $ctx);
835 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
836 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
837 default => $ask_default);
838 die "Commit this patch reply required" unless defined $_;
839 if (/^[nq]/i) {
840 exit(0);
841 } elsif (/^a/i) {
842 last;
847 my $expect_url = $url;
849 my $push_merge_info = eval {
850 command_oneline(qw/config --get svn.pushmergeinfo/)
852 if (not defined($push_merge_info)
853 or $push_merge_info eq "false"
854 or $push_merge_info eq "no"
855 or $push_merge_info eq "never") {
856 $push_merge_info = 0;
859 unless (defined($_merge_info) || ! $push_merge_info) {
860 # Preflight check of changes to ensure no issues with mergeinfo
861 # This includes check for uncommitted-to-SVN parents
862 # (other than the first parent, which we will handle),
863 # information from different SVN repos, and paths
864 # which are not underneath this repository root.
865 my $rooturl = $gs->repos_root;
866 foreach my $d (@$linear_refs) {
867 my %parentshash;
868 read_commit_parents(\%parentshash, $d);
869 my @realparents = @{$parentshash{$d}};
870 if ($#realparents > 0) {
871 # Merge commit
872 shift @realparents; # Remove/ignore first parent
873 foreach my $parent (@realparents) {
874 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
875 unless (defined $paruuid) {
876 # A parent is missing SVN annotations...
877 # abort the whole operation.
878 fatal "$parent is merged into revision $d, "
879 ."but does not have git-svn metadata. "
880 ."Either dcommit the branch or use a "
881 ."local cherry-pick, FF merge, or rebase "
882 ."instead of an explicit merge commit.";
885 unless ($paruuid eq $uuid) {
886 # Parent has SVN metadata from different repository
887 fatal "merge parent $parent for change $d has "
888 ."git-svn uuid $paruuid, while current change "
889 ."has uuid $uuid!";
892 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
893 # This branch is very strange indeed.
894 fatal "merge parent $parent for $d is on branch "
895 ."$branchurl, which is not under the "
896 ."git-svn root $rooturl!";
903 my $rewritten_parent;
904 Git::SVN::remove_username($expect_url);
905 if (defined($_merge_info)) {
906 $_merge_info =~ tr{ }{\n};
908 while (1) {
909 my $d = shift @$linear_refs or last;
910 unless (defined $last_rev) {
911 (undef, $last_rev, undef) = cmt_metadata("$d~1");
912 unless (defined $last_rev) {
913 fatal "Unable to extract revision information ",
914 "from commit $d~1";
917 if ($_dry_run) {
918 print "diff-tree $d~1 $d\n";
919 } else {
920 my $cmt_rev;
922 unless (defined($_merge_info) || ! $push_merge_info) {
923 $_merge_info = populate_merge_info($d, $gs,
924 $uuid,
925 $linear_refs,
926 $rewritten_parent);
929 my %ed_opts = ( r => $last_rev,
930 log => get_commit_entry($d)->{log},
931 ra => Git::SVN::Ra->new($url),
932 config => SVN::Core::config_get_config(
933 $Git::SVN::Ra::config_dir
935 tree_a => "$d~1",
936 tree_b => $d,
937 editor_cb => sub {
938 print "Committed r$_[0]\n";
939 $cmt_rev = $_[0];
941 mergeinfo => $_merge_info,
942 svn_path => '');
943 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
944 print "No changes\n$d~1 == $d\n";
945 } elsif ($parents->{$d} && @{$parents->{$d}}) {
946 $gs->{inject_parents_dcommit}->{$cmt_rev} =
947 $parents->{$d};
949 $_fetch_all ? $gs->fetch_all : $gs->fetch;
950 $last_rev = $cmt_rev;
951 next if $_no_rebase;
953 # we always want to rebase against the current HEAD,
954 # not any head that was passed to us
955 my @diff = command('diff-tree', $d,
956 $gs->refname, '--');
957 my @finish;
958 if (@diff) {
959 @finish = rebase_cmd();
960 print STDERR "W: $d and ", $gs->refname,
961 " differ, using @finish:\n",
962 join("\n", @diff), "\n";
963 } else {
964 print "No changes between current HEAD and ",
965 $gs->refname,
966 "\nResetting to the latest ",
967 $gs->refname, "\n";
968 @finish = qw/reset --mixed/;
970 command_noisy(@finish, $gs->refname);
972 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
974 if (@diff) {
975 @refs = ();
976 my ($url_, $rev_, $uuid_, $gs_) =
977 working_head_info('HEAD', \@refs);
978 my ($linear_refs_, $parents_) =
979 linearize_history($gs_, \@refs);
980 if (scalar(@$linear_refs) !=
981 scalar(@$linear_refs_)) {
982 fatal "# of revisions changed ",
983 "\nbefore:\n",
984 join("\n", @$linear_refs),
985 "\n\nafter:\n",
986 join("\n", @$linear_refs_), "\n",
987 'If you are attempting to commit ',
988 "merges, try running:\n\t",
989 'git rebase --interactive',
990 '--preserve-merges ',
991 $gs->refname,
992 "\nBefore dcommitting";
994 if ($url_ ne $expect_url) {
995 if ($url_ eq $gs->metadata_url) {
996 print
997 "Accepting rewritten URL:",
998 " $url_\n";
999 } else {
1000 fatal
1001 "URL mismatch after rebase:",
1002 " $url_ != $expect_url";
1005 if ($uuid_ ne $uuid) {
1006 fatal "uuid mismatch after rebase: ",
1007 "$uuid_ != $uuid";
1009 # remap parents
1010 my (%p, @l, $i);
1011 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1012 my $new = $linear_refs_->[$i] or next;
1013 $p{$new} =
1014 $parents->{$linear_refs->[$i]};
1015 push @l, $new;
1017 $parents = \%p;
1018 $linear_refs = \@l;
1023 if ($old_head) {
1024 my $new_head = command_oneline(qw/rev-parse HEAD/);
1025 my $new_is_symbolic = eval {
1026 command_oneline(qw/symbolic-ref -q HEAD/);
1028 if ($new_is_symbolic) {
1029 print "dcommitted the branch ", $head, "\n";
1030 } else {
1031 print "dcommitted on a detached HEAD because you gave ",
1032 "a revision argument.\n",
1033 "The rewritten commit is: ", $new_head, "\n";
1035 command(['checkout', $old_head], STDERR => 0);
1038 unlink $gs->{index};
1041 sub cmd_branch {
1042 my ($branch_name, $head) = @_;
1044 unless (defined $branch_name && length $branch_name) {
1045 die(($_tag ? "tag" : "branch") . " name required\n");
1047 $head ||= 'HEAD';
1049 my (undef, $rev, undef, $gs) = working_head_info($head);
1050 my $src = $gs->full_pushurl;
1052 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1053 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1054 my $glob;
1055 if ($#{$allglobs} == 0) {
1056 $glob = $allglobs->[0];
1057 } else {
1058 unless(defined $_branch_dest) {
1059 die "Multiple ",
1060 $_tag ? "tag" : "branch",
1061 " paths defined for Subversion repository.\n",
1062 "You must specify where you want to create the ",
1063 $_tag ? "tag" : "branch",
1064 " with the --destination argument.\n";
1066 foreach my $g (@{$allglobs}) {
1067 # SVN::Git::Editor could probably be moved to Git.pm..
1068 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1069 if ($_branch_dest =~ /$re/) {
1070 $glob = $g;
1071 last;
1074 unless (defined $glob) {
1075 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1076 foreach my $g (@{$allglobs}) {
1077 $g->{path}->{left} =~ /$dest_re/ or next;
1078 if (defined $glob) {
1079 die "Ambiguous destination: ",
1080 $_branch_dest, "\nmatches both '",
1081 $glob->{path}->{left}, "' and '",
1082 $g->{path}->{left}, "'\n";
1084 $glob = $g;
1086 unless (defined $glob) {
1087 die "Unknown ",
1088 $_tag ? "tag" : "branch",
1089 " destination $_branch_dest\n";
1093 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
1094 my $url;
1095 if (defined $_commit_url) {
1096 $url = $_commit_url;
1097 } else {
1098 $url = eval { command_oneline('config', '--get',
1099 "svn-remote.$gs->{repo_id}.commiturl") };
1100 if (!$url) {
1101 $url = $remote->{pushurl} || $remote->{url};
1104 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
1106 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1107 $src=~s/^http:/https:/;
1110 ::_req_svn();
1112 my $ctx = SVN::Client->new(
1113 auth => Git::SVN::Ra::_auth_providers(),
1114 log_msg => sub {
1115 ${ $_[0] } = defined $_message
1116 ? $_message
1117 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1118 . $branch_name;
1122 eval {
1123 $ctx->ls($dst, 'HEAD', 0);
1124 } and die "branch ${branch_name} already exists\n";
1126 print "Copying ${src} at r${rev} to ${dst}...\n";
1127 $ctx->copy($src, $rev, $dst)
1128 unless $_dry_run;
1130 $gs->fetch_all;
1133 sub cmd_find_rev {
1134 my $revision_or_hash = shift or die "SVN or git revision required ",
1135 "as a command-line argument\n";
1136 my $result;
1137 if ($revision_or_hash =~ /^r\d+$/) {
1138 my $head = shift;
1139 $head ||= 'HEAD';
1140 my @refs;
1141 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
1142 unless ($gs) {
1143 die "Unable to determine upstream SVN information from ",
1144 "$head history\n";
1146 my $desired_revision = substr($revision_or_hash, 1);
1147 $result = $gs->rev_map_get($desired_revision, $uuid);
1148 } else {
1149 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1150 $result = $rev;
1152 print "$result\n" if $result;
1155 sub auto_create_empty_directories {
1156 my ($gs) = @_;
1157 my $var = eval { command_oneline('config', '--get', '--bool',
1158 "svn-remote.$gs->{repo_id}.automkdirs") };
1159 # By default, create empty directories by consulting the unhandled log,
1160 # but allow setting it to 'false' to skip it.
1161 return !($var && $var eq 'false');
1164 sub cmd_rebase {
1165 command_noisy(qw/update-index --refresh/);
1166 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1167 unless ($gs) {
1168 die "Unable to determine upstream SVN information from ",
1169 "working tree history\n";
1171 if ($_dry_run) {
1172 print "Remote Branch: " . $gs->refname . "\n";
1173 print "SVN URL: " . $url . "\n";
1174 return;
1176 if (command(qw/diff-index HEAD --/)) {
1177 print STDERR "Cannot rebase with uncommited changes:\n";
1178 command_noisy('status');
1179 exit 1;
1181 unless ($_local) {
1182 # rebase will checkout for us, so no need to do it explicitly
1183 $_no_checkout = 'true';
1184 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1186 command_noisy(rebase_cmd(), $gs->refname);
1187 if (auto_create_empty_directories($gs)) {
1188 $gs->mkemptydirs;
1192 sub cmd_show_ignore {
1193 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1194 $gs ||= Git::SVN->new;
1195 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1196 $gs->prop_walk($gs->{path}, $r, sub {
1197 my ($gs, $path, $props) = @_;
1198 print STDOUT "\n# $path\n";
1199 my $s = $props->{'svn:ignore'} or return;
1200 $s =~ s/[\r\n]+/\n/g;
1201 $s =~ s/^\n+//;
1202 chomp $s;
1203 $s =~ s#^#$path#gm;
1204 print STDOUT "$s\n";
1208 sub cmd_show_externals {
1209 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1210 $gs ||= Git::SVN->new;
1211 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1212 $gs->prop_walk($gs->{path}, $r, sub {
1213 my ($gs, $path, $props) = @_;
1214 print STDOUT "\n# $path\n";
1215 my $s = $props->{'svn:externals'} or return;
1216 $s =~ s/[\r\n]+/\n/g;
1217 chomp $s;
1218 $s =~ s#^#$path#gm;
1219 print STDOUT "$s\n";
1223 sub cmd_create_ignore {
1224 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1225 $gs ||= Git::SVN->new;
1226 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1227 $gs->prop_walk($gs->{path}, $r, sub {
1228 my ($gs, $path, $props) = @_;
1229 # $path is of the form /path/to/dir/
1230 $path = '.' . $path;
1231 # SVN can have attributes on empty directories,
1232 # which git won't track
1233 mkpath([$path]) unless -d $path;
1234 my $ignore = $path . '.gitignore';
1235 my $s = $props->{'svn:ignore'} or return;
1236 open(GITIGNORE, '>', $ignore)
1237 or fatal("Failed to open `$ignore' for writing: $!");
1238 $s =~ s/[\r\n]+/\n/g;
1239 $s =~ s/^\n+//;
1240 chomp $s;
1241 # Prefix all patterns so that the ignore doesn't apply
1242 # to sub-directories.
1243 $s =~ s#^#/#gm;
1244 print GITIGNORE "$s\n";
1245 close(GITIGNORE)
1246 or fatal("Failed to close `$ignore': $!");
1247 command_noisy('add', '-f', $ignore);
1251 sub cmd_mkdirs {
1252 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1253 $gs ||= Git::SVN->new;
1254 $gs->mkemptydirs($_revision);
1257 sub canonicalize_path {
1258 my ($path) = @_;
1259 my $dot_slash_added = 0;
1260 if (substr($path, 0, 1) ne "/") {
1261 $path = "./" . $path;
1262 $dot_slash_added = 1;
1264 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1265 # good reason), so let's do this manually.
1266 $path =~ s#/+#/#g;
1267 $path =~ s#/\.(?:/|$)#/#g;
1268 $path =~ s#/[^/]+/\.\.##g;
1269 $path =~ s#/$##g;
1270 $path =~ s#^\./## if $dot_slash_added;
1271 $path =~ s#^/##;
1272 $path =~ s#^\.$##;
1273 return $path;
1276 sub canonicalize_url {
1277 my ($url) = @_;
1278 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1279 return $url;
1282 # get_svnprops(PATH)
1283 # ------------------
1284 # Helper for cmd_propget and cmd_proplist below.
1285 sub get_svnprops {
1286 my $path = shift;
1287 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1288 $gs ||= Git::SVN->new;
1290 # prefix THE PATH by the sub-directory from which the user
1291 # invoked us.
1292 $path = $cmd_dir_prefix . $path;
1293 fatal("No such file or directory: $path") unless -e $path;
1294 my $is_dir = -d $path ? 1 : 0;
1295 $path = $gs->{path} . '/' . $path;
1297 # canonicalize the path (otherwise libsvn will abort or fail to
1298 # find the file)
1299 $path = canonicalize_path($path);
1301 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1302 my $props;
1303 if ($is_dir) {
1304 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1306 else {
1307 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1309 return $props;
1312 # cmd_propget (PROP, PATH)
1313 # ------------------------
1314 # Print the SVN property PROP for PATH.
1315 sub cmd_propget {
1316 my ($prop, $path) = @_;
1317 $path = '.' if not defined $path;
1318 usage(1) if not defined $prop;
1319 my $props = get_svnprops($path);
1320 if (not defined $props->{$prop}) {
1321 fatal("`$path' does not have a `$prop' SVN property.");
1323 print $props->{$prop} . "\n";
1326 # cmd_proplist (PATH)
1327 # -------------------
1328 # Print the list of SVN properties for PATH.
1329 sub cmd_proplist {
1330 my $path = shift;
1331 $path = '.' if not defined $path;
1332 my $props = get_svnprops($path);
1333 print "Properties on '$path':\n";
1334 foreach (sort keys %{$props}) {
1335 print " $_\n";
1339 sub cmd_multi_init {
1340 my $url = shift;
1341 unless (defined $_trunk || @_branches || @_tags) {
1342 usage(1);
1345 $_prefix = '' unless defined $_prefix;
1346 if (defined $url) {
1347 $url = canonicalize_url($url);
1348 init_subdir(@_);
1350 do_git_init_db();
1351 if (defined $_trunk) {
1352 $_trunk =~ s#^/+##;
1353 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
1354 # try both old-style and new-style lookups:
1355 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
1356 unless ($gs_trunk) {
1357 my ($trunk_url, $trunk_path) =
1358 complete_svn_url($url, $_trunk);
1359 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1360 undef, $trunk_ref);
1363 return unless @_branches || @_tags;
1364 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
1365 foreach my $path (@_branches) {
1366 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1368 foreach my $path (@_tags) {
1369 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1373 sub cmd_multi_fetch {
1374 $Git::SVN::no_reuse_existing = undef;
1375 my $remotes = Git::SVN::read_all_remotes();
1376 foreach my $repo_id (sort keys %$remotes) {
1377 if ($remotes->{$repo_id}->{url}) {
1378 Git::SVN::fetch_all($repo_id, $remotes);
1383 # this command is special because it requires no metadata
1384 sub cmd_commit_diff {
1385 my ($ta, $tb, $url) = @_;
1386 my $usage = "Usage: $0 commit-diff -r<revision> ".
1387 "<tree-ish> <tree-ish> [<URL>]";
1388 fatal($usage) if (!defined $ta || !defined $tb);
1389 my $svn_path = '';
1390 if (!defined $url) {
1391 my $gs = eval { Git::SVN->new };
1392 if (!$gs) {
1393 fatal("Needed URL or usable git-svn --id in ",
1394 "the command-line\n", $usage);
1396 $url = $gs->{url};
1397 $svn_path = $gs->{path};
1399 unless (defined $_revision) {
1400 fatal("-r|--revision is a required argument\n", $usage);
1402 if (defined $_message && defined $_file) {
1403 fatal("Both --message/-m and --file/-F specified ",
1404 "for the commit message.\n",
1405 "I have no idea what you mean");
1407 if (defined $_file) {
1408 $_message = file_to_s($_file);
1409 } else {
1410 $_message ||= get_commit_entry($tb)->{log};
1412 my $ra ||= Git::SVN::Ra->new($url);
1413 my $r = $_revision;
1414 if ($r eq 'HEAD') {
1415 $r = $ra->get_latest_revnum;
1416 } elsif ($r !~ /^\d+$/) {
1417 die "revision argument: $r not understood by git-svn\n";
1419 my %ed_opts = ( r => $r,
1420 log => $_message,
1421 ra => $ra,
1422 tree_a => $ta,
1423 tree_b => $tb,
1424 editor_cb => sub { print "Committed r$_[0]\n" },
1425 svn_path => $svn_path );
1426 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1427 print "No changes\n$ta == $tb\n";
1431 sub escape_uri_only {
1432 my ($uri) = @_;
1433 my @tmp;
1434 foreach (split m{/}, $uri) {
1435 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1436 push @tmp, $_;
1438 join('/', @tmp);
1441 sub escape_url {
1442 my ($url) = @_;
1443 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1444 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1445 $url = "$scheme://$domain$uri";
1447 $url;
1450 sub cmd_info {
1451 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1452 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1453 if (exists $_[1]) {
1454 die "Too many arguments specified\n";
1457 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1459 if (!$file_type && !$diff_status) {
1460 print STDERR "svn: '$path' is not under version control\n";
1461 exit 1;
1464 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1465 unless ($gs) {
1466 die "Unable to determine upstream SVN information from ",
1467 "working tree history\n";
1470 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1471 $path = "." if $path eq "";
1473 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1475 if ($_url) {
1476 print escape_url($full_url), "\n";
1477 return;
1480 my $result = "Path: $path\n";
1481 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1482 $result .= "URL: " . escape_url($full_url) . "\n";
1484 eval {
1485 my $repos_root = $gs->repos_root;
1486 Git::SVN::remove_username($repos_root);
1487 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1489 if ($@) {
1490 $result .= "Repository Root: (offline)\n";
1492 ::_req_svn();
1493 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1494 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
1495 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1497 $result .= "Node Kind: " .
1498 ($file_type eq "dir" ? "directory" : "file") . "\n";
1500 my $schedule = $diff_status eq "A"
1501 ? "add"
1502 : ($diff_status eq "D" ? "delete" : "normal");
1503 $result .= "Schedule: $schedule\n";
1505 if ($diff_status eq "A") {
1506 print $result, "\n";
1507 return;
1510 my ($lc_author, $lc_rev, $lc_date_utc);
1511 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1512 my $log = command_output_pipe(@args);
1513 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1514 while (<$log>) {
1515 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1516 $lc_author = $1;
1517 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1518 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1519 (undef, $lc_rev, undef) = ::extract_metadata($1);
1522 close $log;
1524 Git::SVN::Log::set_local_timezone();
1526 $result .= "Last Changed Author: $lc_author\n";
1527 $result .= "Last Changed Rev: $lc_rev\n";
1528 $result .= "Last Changed Date: " .
1529 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1531 if ($file_type ne "dir") {
1532 my $text_last_updated_date =
1533 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1534 $result .=
1535 "Text Last Updated: " .
1536 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1537 "\n";
1538 my $checksum;
1539 if ($diff_status eq "D") {
1540 my ($fh, $ctx) =
1541 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1542 if ($file_type eq "link") {
1543 my $file_name = <$fh>;
1544 $checksum = md5sum("link $file_name");
1545 } else {
1546 $checksum = md5sum($fh);
1548 command_close_pipe($fh, $ctx);
1549 } elsif ($file_type eq "link") {
1550 my $file_name =
1551 command(qw(cat-file blob), "HEAD:$path");
1552 $checksum =
1553 md5sum("link " . $file_name);
1554 } else {
1555 open FILE, "<", $path or die $!;
1556 $checksum = md5sum(\*FILE);
1557 close FILE or die $!;
1559 $result .= "Checksum: " . $checksum . "\n";
1562 print $result, "\n";
1565 sub cmd_reset {
1566 my $target = shift || $_revision or die "SVN revision required\n";
1567 $target = $1 if $target =~ /^r(\d+)$/;
1568 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1569 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1570 unless ($gs) {
1571 die "Unable to determine upstream SVN information from ".
1572 "history\n";
1574 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1575 die "Cannot find SVN revision $target\n" unless defined($c);
1576 $gs->rev_map_set($r, $c, 'reset', $uuid);
1577 print "r$r = $c ($gs->{ref_id})\n";
1580 sub cmd_gc {
1581 if (!$can_compress) {
1582 warn "Compress::Zlib could not be found; unhandled.log " .
1583 "files will not be compressed.\n";
1585 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1588 ########################### utility functions #########################
1590 sub rebase_cmd {
1591 my @cmd = qw/rebase/;
1592 push @cmd, '-v' if $_verbose;
1593 push @cmd, qw/--merge/ if $_merge;
1594 push @cmd, "--strategy=$_strategy" if $_strategy;
1595 @cmd;
1598 sub post_fetch_checkout {
1599 return if $_no_checkout;
1600 my $gs = $Git::SVN::_head or return;
1601 return if verify_ref('refs/heads/master^0');
1603 # look for "trunk" ref if it exists
1604 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1605 my $fetch = $remote->{fetch};
1606 if ($fetch) {
1607 foreach my $p (keys %$fetch) {
1608 basename($fetch->{$p}) eq 'trunk' or next;
1609 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1610 last;
1614 my $valid_head = verify_ref('HEAD^0');
1615 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1616 return if ($valid_head || !verify_ref('HEAD^0'));
1618 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1619 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1620 return if -f $index;
1622 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1623 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1624 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1625 print STDERR "Checked out HEAD:\n ",
1626 $gs->full_url, " r", $gs->last_rev, "\n";
1627 if (auto_create_empty_directories($gs)) {
1628 $gs->mkemptydirs($gs->last_rev);
1632 sub complete_svn_url {
1633 my ($url, $path) = @_;
1634 $path =~ s#/+$##;
1635 if ($path !~ m#^[a-z\+]+://#) {
1636 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1637 fatal("E: '$path' is not a complete URL ",
1638 "and a separate URL is not specified");
1640 return ($url, $path);
1642 return ($path, '');
1645 sub complete_url_ls_init {
1646 my ($ra, $repo_path, $switch, $pfx) = @_;
1647 unless ($repo_path) {
1648 print STDERR "W: $switch not specified\n";
1649 return;
1651 $repo_path =~ s#/+$##;
1652 if ($repo_path =~ m#^[a-z\+]+://#) {
1653 $ra = Git::SVN::Ra->new($repo_path);
1654 $repo_path = '';
1655 } else {
1656 $repo_path =~ s#^/+##;
1657 unless ($ra) {
1658 fatal("E: '$repo_path' is not a complete URL ",
1659 "and a separate URL is not specified");
1662 my $url = $ra->{url};
1663 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1664 my $k = "svn-remote.$gs->{repo_id}.url";
1665 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1666 if ($orig_url && ($orig_url ne $gs->{url})) {
1667 die "$k already set: $orig_url\n",
1668 "wanted to set to: $gs->{url}\n";
1670 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1671 my $remote_path = "$gs->{path}/$repo_path";
1672 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1673 $remote_path =~ s#/+#/#g;
1674 $remote_path =~ s#^/##g;
1675 $remote_path .= "/*" if $remote_path !~ /\*/;
1676 my ($n) = ($switch =~ /^--(\w+)/);
1677 if (length $pfx && $pfx !~ m#/$#) {
1678 die "--prefix='$pfx' must have a trailing slash '/'\n";
1680 command_noisy('config',
1681 '--add',
1682 "svn-remote.$gs->{repo_id}.$n",
1683 "$remote_path:refs/remotes/$pfx*" .
1684 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1687 sub verify_ref {
1688 my ($ref) = @_;
1689 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1690 { STDERR => 0 }); };
1693 sub get_tree_from_treeish {
1694 my ($treeish) = @_;
1695 # $treeish can be a symbolic ref, too:
1696 my $type = command_oneline(qw/cat-file -t/, $treeish);
1697 my $expected;
1698 while ($type eq 'tag') {
1699 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1701 if ($type eq 'commit') {
1702 $expected = (grep /^tree /, command(qw/cat-file commit/,
1703 $treeish))[0];
1704 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1705 die "Unable to get tree from $treeish\n" unless $expected;
1706 } elsif ($type eq 'tree') {
1707 $expected = $treeish;
1708 } else {
1709 die "$treeish is a $type, expected tree, tag or commit\n";
1711 return $expected;
1714 sub get_commit_entry {
1715 my ($treeish) = shift;
1716 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1717 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1718 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1719 open my $log_fh, '>', $commit_editmsg or croak $!;
1721 my $type = command_oneline(qw/cat-file -t/, $treeish);
1722 if ($type eq 'commit' || $type eq 'tag') {
1723 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1724 $type, $treeish);
1725 my $in_msg = 0;
1726 my $author;
1727 my $saw_from = 0;
1728 my $msgbuf = "";
1729 while (<$msg_fh>) {
1730 if (!$in_msg) {
1731 $in_msg = 1 if (/^\s*$/);
1732 $author = $1 if (/^author (.*>)/);
1733 } elsif (/^git-svn-id: /) {
1734 # skip this for now, we regenerate the
1735 # correct one on re-fetch anyways
1736 # TODO: set *:merge properties or like...
1737 } else {
1738 if (/^From:/ || /^Signed-off-by:/) {
1739 $saw_from = 1;
1741 $msgbuf .= $_;
1744 $msgbuf =~ s/\s+$//s;
1745 if ($Git::SVN::_add_author_from && defined($author)
1746 && !$saw_from) {
1747 $msgbuf .= "\n\nFrom: $author";
1749 print $log_fh $msgbuf or croak $!;
1750 command_close_pipe($msg_fh, $ctx);
1752 close $log_fh or croak $!;
1754 if ($_edit || ($type eq 'tree')) {
1755 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1756 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1758 rename $commit_editmsg, $commit_msg or croak $!;
1760 require Encode;
1761 # SVN requires messages to be UTF-8 when entering the repo
1762 local $/;
1763 open $log_fh, '<', $commit_msg or croak $!;
1764 binmode $log_fh;
1765 chomp($log_entry{log} = <$log_fh>);
1767 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1768 my $msg = $log_entry{log};
1770 eval { $msg = Encode::decode($enc, $msg, 1) };
1771 if ($@) {
1772 die "Could not decode as $enc:\n", $msg,
1773 "\nPerhaps you need to set i18n.commitencoding\n";
1776 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1777 die "Could not encode as UTF-8:\n$msg\n" if $@;
1779 $log_entry{log} = $msg;
1781 close $log_fh or croak $!;
1783 unlink $commit_msg;
1784 \%log_entry;
1787 sub s_to_file {
1788 my ($str, $file, $mode) = @_;
1789 open my $fd,'>',$file or croak $!;
1790 print $fd $str,"\n" or croak $!;
1791 close $fd or croak $!;
1792 chmod ($mode &~ umask, $file) if (defined $mode);
1795 sub file_to_s {
1796 my $file = shift;
1797 open my $fd,'<',$file or croak "$!: file: $file\n";
1798 local $/;
1799 my $ret = <$fd>;
1800 close $fd or croak $!;
1801 $ret =~ s/\s*$//s;
1802 return $ret;
1805 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1806 sub load_authors {
1807 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1808 my $log = $cmd eq 'log';
1809 while (<$authors>) {
1810 chomp;
1811 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1812 my ($user, $name, $email) = ($1, $2, $3);
1813 if ($log) {
1814 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1815 } else {
1816 $users{$user} = [$name, $email];
1819 close $authors or croak $!;
1822 # convert GetOpt::Long specs for use by git-config
1823 sub read_git_config {
1824 my $opts = shift;
1825 my @config_only;
1826 foreach my $o (keys %$opts) {
1827 # if we have mixedCase and a long option-only, then
1828 # it's a config-only variable that we don't need for
1829 # the command-line.
1830 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1831 my $v = $opts->{$o};
1832 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1833 $key =~ s/-//g;
1834 my $arg = 'git config';
1835 $arg .= ' --int' if ($o =~ /[:=]i$/);
1836 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1837 if (ref $v eq 'ARRAY') {
1838 chomp(my @tmp = `$arg --get-all svn.$key`);
1839 @$v = @tmp if @tmp;
1840 } else {
1841 chomp(my $tmp = `$arg --get svn.$key`);
1842 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1843 $$v = $tmp;
1847 delete @$opts{@config_only} if @config_only;
1850 sub extract_metadata {
1851 my $id = shift or return (undef, undef, undef);
1852 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1853 \s([a-f\d\-]+)$/ix);
1854 if (!defined $rev || !$uuid || !$url) {
1855 # some of the original repositories I made had
1856 # identifiers like this:
1857 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1859 return ($url, $rev, $uuid);
1862 sub cmt_metadata {
1863 return extract_metadata((grep(/^git-svn-id: /,
1864 command(qw/cat-file commit/, shift)))[-1]);
1867 sub cmt_sha2rev_batch {
1868 my %s2r;
1869 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1870 my $list = shift;
1872 foreach my $sha (@{$list}) {
1873 my $first = 1;
1874 my $size = 0;
1875 print $out $sha, "\n";
1877 while (my $line = <$in>) {
1878 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1879 last;
1880 } elsif ($first &&
1881 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1882 $first = 0;
1883 $size = $1;
1884 next;
1885 } elsif ($line =~ /^(git-svn-id: )/) {
1886 my (undef, $rev, undef) =
1887 extract_metadata($line);
1888 $s2r{$sha} = $rev;
1891 $size -= length($line);
1892 last if ($size == 0);
1896 command_close_bidi_pipe($pid, $in, $out, $ctx);
1898 return \%s2r;
1901 sub working_head_info {
1902 my ($head, $refs) = @_;
1903 my @args = qw/rev-list --first-parent --pretty=medium/;
1904 my ($fh, $ctx) = command_output_pipe(@args, $head);
1905 my $hash;
1906 my %max;
1907 while (<$fh>) {
1908 if ( m{^commit ($::sha1)$} ) {
1909 unshift @$refs, $hash if $hash and $refs;
1910 $hash = $1;
1911 next;
1913 next unless s{^\s*(git-svn-id:)}{$1};
1914 my ($url, $rev, $uuid) = extract_metadata($_);
1915 if (defined $url && defined $rev) {
1916 next if $max{$url} and $max{$url} < $rev;
1917 if (my $gs = Git::SVN->find_by_url($url)) {
1918 my $c = $gs->rev_map_get($rev, $uuid);
1919 if ($c && $c eq $hash) {
1920 close $fh; # break the pipe
1921 return ($url, $rev, $uuid, $gs);
1922 } else {
1923 $max{$url} ||= $gs->rev_map_max;
1928 command_close_pipe($fh, $ctx);
1929 (undef, undef, undef, undef);
1932 sub read_commit_parents {
1933 my ($parents, $c) = @_;
1934 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1935 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1936 @{$parents->{$c}} = split(/ /, $p);
1939 sub linearize_history {
1940 my ($gs, $refs) = @_;
1941 my %parents;
1942 foreach my $c (@$refs) {
1943 read_commit_parents(\%parents, $c);
1946 my @linear_refs;
1947 my %skip = ();
1948 my $last_svn_commit = $gs->last_commit;
1949 foreach my $c (reverse @$refs) {
1950 next if $c eq $last_svn_commit;
1951 last if $skip{$c};
1953 unshift @linear_refs, $c;
1954 $skip{$c} = 1;
1956 # we only want the first parent to diff against for linear
1957 # history, we save the rest to inject when we finalize the
1958 # svn commit
1959 my $fp_a = verify_ref("$c~1");
1960 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1961 if (!$fp_a || !$fp_b) {
1962 die "Commit $c\n",
1963 "has no parent commit, and therefore ",
1964 "nothing to diff against.\n",
1965 "You should be working from a repository ",
1966 "originally created by git-svn\n";
1968 if ($fp_a ne $fp_b) {
1969 die "$c~1 = $fp_a, however parsing commit $c ",
1970 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1973 foreach my $p (@{$parents{$c}}) {
1974 $skip{$p} = 1;
1977 (\@linear_refs, \%parents);
1980 sub find_file_type_and_diff_status {
1981 my ($path) = @_;
1982 return ('dir', '') if $path eq '';
1984 my $diff_output =
1985 command_oneline(qw(diff --cached --name-status --), $path) || "";
1986 my $diff_status = (split(' ', $diff_output))[0] || "";
1988 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1990 return (undef, undef) if !$diff_status && !$ls_tree;
1992 if ($diff_status eq "A") {
1993 return ("link", $diff_status) if -l $path;
1994 return ("dir", $diff_status) if -d $path;
1995 return ("file", $diff_status);
1998 my $mode = (split(' ', $ls_tree))[0] || "";
2000 return ("link", $diff_status) if $mode eq "120000";
2001 return ("dir", $diff_status) if $mode eq "040000";
2002 return ("file", $diff_status);
2005 sub md5sum {
2006 my $arg = shift;
2007 my $ref = ref $arg;
2008 my $md5 = Digest::MD5->new();
2009 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
2010 $md5->addfile($arg) or croak $!;
2011 } elsif ($ref eq 'SCALAR') {
2012 $md5->add($$arg) or croak $!;
2013 } elsif (!$ref) {
2014 $md5->add($arg) or croak $!;
2015 } else {
2016 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2018 return $md5->hexdigest();
2021 sub gc_directory {
2022 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2023 my $out_filename = $_ . ".gz";
2024 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2025 binmode $in_fh;
2026 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2027 die "Unable to open $out_filename: $!\n";
2029 my $res;
2030 while ($res = sysread($in_fh, my $str, 1024)) {
2031 $gz->gzwrite($str) or
2032 die "Unable to write: ".$gz->gzerror()."!\n";
2034 unlink $_ or die "unlink $File::Find::name: $!\n";
2035 } elsif (-f $_ && basename($_) eq "index") {
2036 unlink $_ or die "unlink $_: $!\n";
2040 package Git::SVN;
2041 use strict;
2042 use warnings;
2043 use Fcntl qw/:DEFAULT :seek/;
2044 use constant rev_map_fmt => 'NH40';
2045 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
2046 $_repack $_repack_flags $_use_svm_props $_head
2047 $_use_svnsync_props $no_reuse_existing $_minimize_url
2048 $_use_log_author $_add_author_from $_localtime/;
2049 use Carp qw/croak/;
2050 use File::Path qw/mkpath/;
2051 use File::Copy qw/copy/;
2052 use IPC::Open3;
2053 use Time::Local;
2054 use Memoize; # core since 5.8.0, Jul 2002
2055 use Memoize::Storable;
2056 use POSIX qw(:signal_h);
2058 my ($_gc_nr, $_gc_period);
2060 # properties that we do not log:
2061 my %SKIP_PROP;
2062 BEGIN {
2063 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2064 svn:special svn:executable
2065 svn:entry:committed-rev
2066 svn:entry:last-author
2067 svn:entry:uuid
2068 svn:entry:committed-date/;
2070 # some options are read globally, but can be overridden locally
2071 # per [svn-remote "..."] section. Command-line options will *NOT*
2072 # override options set in an [svn-remote "..."] section
2073 no strict 'refs';
2074 for my $option (qw/follow_parent no_metadata use_svm_props
2075 use_svnsync_props/) {
2076 my $key = $option;
2077 $key =~ tr/_//d;
2078 my $prop = "-$option";
2079 *$option = sub {
2080 my ($self) = @_;
2081 return $self->{$prop} if exists $self->{$prop};
2082 my $k = "svn-remote.$self->{repo_id}.$key";
2083 eval { command_oneline(qw/config --get/, $k) };
2084 if ($@) {
2085 $self->{$prop} = ${"Git::SVN::_$option"};
2086 } else {
2087 my $v = command_oneline(qw/config --bool/,$k);
2088 $self->{$prop} = $v eq 'false' ? 0 : 1;
2090 return $self->{$prop};
2096 my (%LOCKFILES, %INDEX_FILES);
2097 END {
2098 unlink keys %LOCKFILES if %LOCKFILES;
2099 unlink keys %INDEX_FILES if %INDEX_FILES;
2102 sub resolve_local_globs {
2103 my ($url, $fetch, $glob_spec) = @_;
2104 return unless defined $glob_spec;
2105 my $ref = $glob_spec->{ref};
2106 my $path = $glob_spec->{path};
2107 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2108 next unless m#^$ref->{regex}$#;
2109 my $p = $1;
2110 my $pathname = desanitize_refname($path->full_path($p));
2111 my $refname = desanitize_refname($ref->full_path($p));
2112 if (my $existing = $fetch->{$pathname}) {
2113 if ($existing ne $refname) {
2114 die "Refspec conflict:\n",
2115 "existing: $existing\n",
2116 " globbed: $refname\n";
2118 my $u = (::cmt_metadata("$refname"))[0];
2119 $u =~ s!^\Q$url\E(/|$)!! or die
2120 "$refname: '$url' not found in '$u'\n";
2121 if ($pathname ne $u) {
2122 warn "W: Refspec glob conflict ",
2123 "(ref: $refname):\n",
2124 "expected path: $pathname\n",
2125 " real path: $u\n",
2126 "Continuing ahead with $u\n";
2127 next;
2129 } else {
2130 $fetch->{$pathname} = $refname;
2135 sub parse_revision_argument {
2136 my ($base, $head) = @_;
2137 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2138 return ($base, $head);
2140 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2141 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2142 return ($head, $head) if ($::_revision eq 'HEAD');
2143 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2144 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2145 die "revision argument: $::_revision not understood by git-svn\n";
2148 sub fetch_all {
2149 my ($repo_id, $remotes) = @_;
2150 if (ref $repo_id) {
2151 my $gs = $repo_id;
2152 $repo_id = undef;
2153 $repo_id = $gs->{repo_id};
2155 $remotes ||= read_all_remotes();
2156 my $remote = $remotes->{$repo_id} or
2157 die "[svn-remote \"$repo_id\"] unknown\n";
2158 my $fetch = $remote->{fetch};
2159 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
2160 my (@gs, @globs);
2161 my $ra = Git::SVN::Ra->new($url);
2162 my $uuid = $ra->get_uuid;
2163 my $head = $ra->get_latest_revnum;
2165 # ignore errors, $head revision may not even exist anymore
2166 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2167 warn "W: $@\n" if $@;
2169 my $base = defined $fetch ? $head : 0;
2171 # read the max revs for wildcard expansion (branches/*, tags/*)
2172 foreach my $t (qw/branches tags/) {
2173 defined $remote->{$t} or next;
2174 push @globs, @{$remote->{$t}};
2176 my $max_rev = eval { tmp_config(qw/--int --get/,
2177 "svn-remote.$repo_id.${t}-maxRev") };
2178 if (defined $max_rev && ($max_rev < $base)) {
2179 $base = $max_rev;
2180 } elsif (!defined $max_rev) {
2181 $base = 0;
2185 if ($fetch) {
2186 foreach my $p (sort keys %$fetch) {
2187 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
2188 my $lr = $gs->rev_map_max;
2189 if (defined $lr) {
2190 $base = $lr if ($lr < $base);
2192 push @gs, $gs;
2196 ($base, $head) = parse_revision_argument($base, $head);
2197 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
2200 sub read_all_remotes {
2201 my $r = {};
2202 my $use_svm_props = eval { command_oneline(qw/config --bool
2203 svn.useSvmProps/) };
2204 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
2205 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
2206 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
2207 if (m!^(.+)\.fetch=$svn_refspec$!) {
2208 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2209 die("svn-remote.$remote: remote ref '$remote_ref' "
2210 . "must start with 'refs/'\n")
2211 unless $remote_ref =~ m{^refs/};
2212 $local_ref = uri_decode($local_ref);
2213 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
2214 $r->{$remote}->{svm} = {} if $use_svm_props;
2215 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2216 $r->{$1}->{svm} = {};
2217 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2218 $r->{$1}->{url} = $2;
2219 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2220 $r->{$1}->{pushurl} = $2;
2221 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2222 $r->{$1}->{ignore_refs_regex} = $2;
2223 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2224 my ($remote, $t, $local_ref, $remote_ref) =
2225 ($1, $2, $3, $4);
2226 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2227 . "must start with 'refs/'\n")
2228 unless $remote_ref =~ m{^refs/};
2229 $local_ref = uri_decode($local_ref);
2230 my $rs = {
2231 t => $t,
2232 remote => $remote,
2233 path => Git::SVN::GlobSpec->new($local_ref, 1),
2234 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
2235 if (length($rs->{ref}->{right}) != 0) {
2236 die "The '*' glob character must be the last ",
2237 "character of '$remote_ref'\n";
2239 push @{ $r->{$remote}->{$t} }, $rs;
2243 map {
2244 if (defined $r->{$_}->{svm}) {
2245 my $svm;
2246 eval {
2247 my $section = "svn-remote.$_";
2248 $svm = {
2249 source => tmp_config('--get',
2250 "$section.svm-source"),
2251 replace => tmp_config('--get',
2252 "$section.svm-replace"),
2255 $r->{$_}->{svm} = $svm;
2257 } keys %$r;
2259 foreach my $remote (keys %$r) {
2260 foreach ( grep { defined $_ }
2261 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2262 foreach my $rs ( @$_ ) {
2263 $rs->{ignore_refs_regex} =
2264 $r->{$remote}->{ignore_refs_regex};
2272 sub init_vars {
2273 $_gc_nr = $_gc_period = 1000;
2274 if (defined $_repack || defined $_repack_flags) {
2275 warn "Repack options are obsolete; they have no effect.\n";
2279 sub verify_remotes_sanity {
2280 return unless -d $ENV{GIT_DIR};
2281 my %seen;
2282 foreach (command(qw/config -l/)) {
2283 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2284 if ($seen{$1}) {
2285 die "Remote ref refs/remote/$1 is tracked by",
2286 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2287 "Please resolve this ambiguity in ",
2288 "your git configuration file before ",
2289 "continuing\n";
2291 $seen{$1} = $_;
2296 sub find_existing_remote {
2297 my ($url, $remotes) = @_;
2298 return undef if $no_reuse_existing;
2299 my $existing;
2300 foreach my $repo_id (keys %$remotes) {
2301 my $u = $remotes->{$repo_id}->{url} or next;
2302 next if $u ne $url;
2303 $existing = $repo_id;
2304 last;
2306 $existing;
2309 sub init_remote_config {
2310 my ($self, $url, $no_write) = @_;
2311 $url =~ s!/+$!!; # strip trailing slash
2312 my $r = read_all_remotes();
2313 my $existing = find_existing_remote($url, $r);
2314 if ($existing) {
2315 unless ($no_write) {
2316 print STDERR "Using existing ",
2317 "[svn-remote \"$existing\"]\n";
2319 $self->{repo_id} = $existing;
2320 } elsif ($_minimize_url) {
2321 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2322 $existing = find_existing_remote($min_url, $r);
2323 if ($existing) {
2324 unless ($no_write) {
2325 print STDERR "Using existing ",
2326 "[svn-remote \"$existing\"]\n";
2328 $self->{repo_id} = $existing;
2330 if ($min_url ne $url) {
2331 unless ($no_write) {
2332 print STDERR "Using higher level of URL: ",
2333 "$url => $min_url\n";
2335 my $old_path = $self->{path};
2336 $self->{path} = $url;
2337 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
2338 if (length $old_path) {
2339 $self->{path} .= "/$old_path";
2341 $url = $min_url;
2344 my $orig_url;
2345 if (!$existing) {
2346 # verify that we aren't overwriting anything:
2347 $orig_url = eval {
2348 command_oneline('config', '--get',
2349 "svn-remote.$self->{repo_id}.url")
2351 if ($orig_url && ($orig_url ne $url)) {
2352 die "svn-remote.$self->{repo_id}.url already set: ",
2353 "$orig_url\nwanted to set to: $url\n";
2356 my ($xrepo_id, $xpath) = find_ref($self->refname);
2357 if (!$no_write && defined $xpath) {
2358 die "svn-remote.$xrepo_id.fetch already set to track ",
2359 "$xpath:", $self->refname, "\n";
2361 unless ($no_write) {
2362 command_noisy('config',
2363 "svn-remote.$self->{repo_id}.url", $url);
2364 $self->{path} =~ s{^/}{};
2365 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
2366 command_noisy('config', '--add',
2367 "svn-remote.$self->{repo_id}.fetch",
2368 "$self->{path}:".$self->refname);
2370 $self->{url} = $url;
2373 sub find_by_url { # repos_root and, path are optional
2374 my ($class, $full_url, $repos_root, $path) = @_;
2376 return undef unless defined $full_url;
2377 remove_username($full_url);
2378 remove_username($repos_root) if defined $repos_root;
2379 my $remotes = read_all_remotes();
2380 if (defined $full_url && defined $repos_root && !defined $path) {
2381 $path = $full_url;
2382 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2384 foreach my $repo_id (keys %$remotes) {
2385 my $u = $remotes->{$repo_id}->{url} or next;
2386 remove_username($u);
2387 next if defined $repos_root && $repos_root ne $u;
2389 my $fetch = $remotes->{$repo_id}->{fetch} || {};
2390 foreach my $t (qw/branches tags/) {
2391 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2392 resolve_local_globs($u, $fetch, $globspec);
2395 my $p = $path;
2396 my $rwr = rewrite_root({repo_id => $repo_id});
2397 my $svm = $remotes->{$repo_id}->{svm}
2398 if defined $remotes->{$repo_id}->{svm};
2399 unless (defined $p) {
2400 $p = $full_url;
2401 my $z = $u;
2402 my $prefix = '';
2403 if ($rwr) {
2404 $z = $rwr;
2405 remove_username($z);
2406 } elsif (defined $svm) {
2407 $z = $svm->{source};
2408 $prefix = $svm->{replace};
2409 $prefix =~ s#^\Q$u\E(?:/|$)##;
2410 $prefix =~ s#/$##;
2412 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2414 foreach my $f (keys %$fetch) {
2415 next if $f ne $p;
2416 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2419 undef;
2422 sub init {
2423 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2424 my $self = _new($class, $repo_id, $ref_id, $path);
2425 if (defined $url) {
2426 $self->init_remote_config($url, $no_write);
2428 $self;
2431 sub find_ref {
2432 my ($ref_id) = @_;
2433 foreach (command(qw/config -l/)) {
2434 next unless m!^svn-remote\.(.+)\.fetch=
2435 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2436 my ($repo_id, $path, $ref) = ($1, $2, $3);
2437 if ($ref eq $ref_id) {
2438 $path = '' if ($path =~ m#^\./?#);
2439 return ($repo_id, $path);
2442 (undef, undef, undef);
2445 sub new {
2446 my ($class, $ref_id, $repo_id, $path) = @_;
2447 if (defined $ref_id && !defined $repo_id && !defined $path) {
2448 ($repo_id, $path) = find_ref($ref_id);
2449 if (!defined $repo_id) {
2450 die "Could not find a \"svn-remote.*.fetch\" key ",
2451 "in the repository configuration matching: ",
2452 "$ref_id\n";
2455 my $self = _new($class, $repo_id, $ref_id, $path);
2456 if (!defined $self->{path} || !length $self->{path}) {
2457 my $fetch = command_oneline('config', '--get',
2458 "svn-remote.$repo_id.fetch",
2459 ":$ref_id\$") or
2460 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2461 "\":$ref_id\$\" in config\n";
2462 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2464 $self->{path} =~ s{/+}{/}g;
2465 $self->{path} =~ s{\A/}{};
2466 $self->{path} =~ s{/\z}{};
2467 $self->{url} = command_oneline('config', '--get',
2468 "svn-remote.$repo_id.url") or
2469 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2470 $self->{pushurl} = eval { command_oneline('config', '--get',
2471 "svn-remote.$repo_id.pushurl") };
2472 $self->rebuild;
2473 $self;
2476 sub refname {
2477 my ($refname) = $_[0]->{ref_id} ;
2479 # It cannot end with a slash /, we'll throw up on this because
2480 # SVN can't have directories with a slash in their name, either:
2481 if ($refname =~ m{/$}) {
2482 die "ref: '$refname' ends with a trailing slash, this is ",
2483 "not permitted by git nor Subversion\n";
2486 # It cannot have ASCII control character space, tilde ~, caret ^,
2487 # colon :, question-mark ?, asterisk *, space, or open bracket [
2488 # anywhere.
2490 # Additionally, % must be escaped because it is used for escaping
2491 # and we want our escaped refname to be reversible
2492 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2494 # no slash-separated component can begin with a dot .
2495 # /.* becomes /%2E*
2496 $refname =~ s{/\.}{/%2E}g;
2498 # It cannot have two consecutive dots .. anywhere
2499 # .. becomes %2E%2E
2500 $refname =~ s{\.\.}{%2E%2E}g;
2502 # trailing dots and .lock are not allowed
2503 # .$ becomes %2E and .lock becomes %2Elock
2504 $refname =~ s{\.(?=$|lock$)}{%2E};
2506 # the sequence @{ is used to access the reflog
2507 # @{ becomes %40{
2508 $refname =~ s{\@\{}{%40\{}g;
2510 return $refname;
2513 sub desanitize_refname {
2514 my ($refname) = @_;
2515 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2516 return $refname;
2519 sub svm_uuid {
2520 my ($self) = @_;
2521 return $self->{svm}->{uuid} if $self->svm;
2522 $self->ra;
2523 unless ($self->{svm}) {
2524 die "SVM UUID not cached, and reading remotely failed\n";
2526 $self->{svm}->{uuid};
2529 sub svm {
2530 my ($self) = @_;
2531 return $self->{svm} if $self->{svm};
2532 my $svm;
2533 # see if we have it in our config, first:
2534 eval {
2535 my $section = "svn-remote.$self->{repo_id}";
2536 $svm = {
2537 source => tmp_config('--get', "$section.svm-source"),
2538 uuid => tmp_config('--get', "$section.svm-uuid"),
2539 replace => tmp_config('--get', "$section.svm-replace"),
2542 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2543 $self->{svm} = $svm;
2545 $self->{svm};
2548 sub _set_svm_vars {
2549 my ($self, $ra) = @_;
2550 return $ra if $self->svm;
2552 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2553 "(svm:source, svm:uuid) ",
2554 "from the following URLs:\n" );
2555 sub read_svm_props {
2556 my ($self, $ra, $path, $r) = @_;
2557 my $props = ($ra->get_dir($path, $r))[2];
2558 my $src = $props->{'svm:source'};
2559 my $uuid = $props->{'svm:uuid'};
2560 return undef if (!$src || !$uuid);
2562 chomp($src, $uuid);
2564 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2565 or die "doesn't look right - svm:uuid is '$uuid'\n";
2567 # the '!' is used to mark the repos_root!/relative/path
2568 $src =~ s{/?!/?}{/};
2569 $src =~ s{/+$}{}; # no trailing slashes please
2570 # username is of no interest
2571 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2573 my $replace = $ra->{url};
2574 $replace .= "/$path" if length $path;
2576 my $section = "svn-remote.$self->{repo_id}";
2577 tmp_config("$section.svm-source", $src);
2578 tmp_config("$section.svm-replace", $replace);
2579 tmp_config("$section.svm-uuid", $uuid);
2580 $self->{svm} = {
2581 source => $src,
2582 uuid => $uuid,
2583 replace => $replace
2587 my $r = $ra->get_latest_revnum;
2588 my $path = $self->{path};
2589 my %tried;
2590 while (length $path) {
2591 unless ($tried{"$self->{url}/$path"}) {
2592 return $ra if $self->read_svm_props($ra, $path, $r);
2593 $tried{"$self->{url}/$path"} = 1;
2595 $path =~ s#/?[^/]+$##;
2597 die "Path: '$path' should be ''\n" if $path ne '';
2598 return $ra if $self->read_svm_props($ra, $path, $r);
2599 $tried{"$self->{url}/$path"} = 1;
2601 if ($ra->{repos_root} eq $self->{url}) {
2602 die @err, (map { " $_\n" } keys %tried), "\n";
2605 # nope, make sure we're connected to the repository root:
2606 my $ok;
2607 my @tried_b;
2608 $path = $ra->{svn_path};
2609 $ra = Git::SVN::Ra->new($ra->{repos_root});
2610 while (length $path) {
2611 unless ($tried{"$ra->{url}/$path"}) {
2612 $ok = $self->read_svm_props($ra, $path, $r);
2613 last if $ok;
2614 $tried{"$ra->{url}/$path"} = 1;
2616 $path =~ s#/?[^/]+$##;
2618 die "Path: '$path' should be ''\n" if $path ne '';
2619 $ok ||= $self->read_svm_props($ra, $path, $r);
2620 $tried{"$ra->{url}/$path"} = 1;
2621 if (!$ok) {
2622 die @err, (map { " $_\n" } keys %tried), "\n";
2624 Git::SVN::Ra->new($self->{url});
2627 sub svnsync {
2628 my ($self) = @_;
2629 return $self->{svnsync} if $self->{svnsync};
2631 if ($self->no_metadata) {
2632 die "Can't have both 'noMetadata' and ",
2633 "'useSvnsyncProps' options set!\n";
2635 if ($self->rewrite_root) {
2636 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2637 "options set!\n";
2639 if ($self->rewrite_uuid) {
2640 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2641 "options set!\n";
2644 my $svnsync;
2645 # see if we have it in our config, first:
2646 eval {
2647 my $section = "svn-remote.$self->{repo_id}";
2649 my $url = tmp_config('--get', "$section.svnsync-url");
2650 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2651 die "doesn't look right - svn:sync-from-url is '$url'\n";
2653 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2654 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2655 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2657 $svnsync = { url => $url, uuid => $uuid }
2659 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2660 return $self->{svnsync} = $svnsync;
2663 my $err = "useSvnsyncProps set, but failed to read " .
2664 "svnsync property: svn:sync-from-";
2665 my $rp = $self->ra->rev_proplist(0);
2667 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2668 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2669 die "doesn't look right - svn:sync-from-url is '$url'\n";
2671 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2672 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2673 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2675 my $section = "svn-remote.$self->{repo_id}";
2676 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2677 tmp_config('--add', "$section.svnsync-url", $url);
2678 return $self->{svnsync} = { url => $url, uuid => $uuid };
2681 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2682 # remote lookup (useful for 'git svn log').
2683 sub ra_uuid {
2684 my ($self) = @_;
2685 unless ($self->{ra_uuid}) {
2686 my $key = "svn-remote.$self->{repo_id}.uuid";
2687 my $uuid = eval { tmp_config('--get', $key) };
2688 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2689 $self->{ra_uuid} = $uuid;
2690 } else {
2691 die "ra_uuid called without URL\n" unless $self->{url};
2692 $self->{ra_uuid} = $self->ra->get_uuid;
2693 tmp_config('--add', $key, $self->{ra_uuid});
2696 $self->{ra_uuid};
2699 sub _set_repos_root {
2700 my ($self, $repos_root) = @_;
2701 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2702 $repos_root ||= $self->ra->{repos_root};
2703 tmp_config($k, $repos_root);
2704 $repos_root;
2707 sub repos_root {
2708 my ($self) = @_;
2709 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2710 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2713 sub ra {
2714 my ($self) = shift;
2715 my $ra = Git::SVN::Ra->new($self->{url});
2716 $self->_set_repos_root($ra->{repos_root});
2717 if ($self->use_svm_props && !$self->{svm}) {
2718 if ($self->no_metadata) {
2719 die "Can't have both 'noMetadata' and ",
2720 "'useSvmProps' options set!\n";
2721 } elsif ($self->use_svnsync_props) {
2722 die "Can't have both 'useSvnsyncProps' and ",
2723 "'useSvmProps' options set!\n";
2725 $ra = $self->_set_svm_vars($ra);
2726 $self->{-want_revprops} = 1;
2728 $ra;
2731 # prop_walk(PATH, REV, SUB)
2732 # -------------------------
2733 # Recursively traverse PATH at revision REV and invoke SUB for each
2734 # directory that contains a SVN property. SUB will be invoked as
2735 # follows: &SUB(gs, path, props); where `gs' is this instance of
2736 # Git::SVN, `path' the path to the directory where the properties
2737 # `props' were found. The `path' will be relative to point of checkout,
2738 # that is, if url://repo/trunk is the current Git branch, and that
2739 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2740 # as `path' (note the trailing `/').
2741 sub prop_walk {
2742 my ($self, $path, $rev, $sub) = @_;
2744 $path =~ s#^/##;
2745 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2746 $path =~ s#^/*#/#g;
2747 my $p = $path;
2748 # Strip the irrelevant part of the path.
2749 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2750 # Ensure the path is terminated by a `/'.
2751 $p =~ s#/*$#/#;
2753 # The properties contain all the internal SVN stuff nobody
2754 # (usually) cares about.
2755 my $interesting_props = 0;
2756 foreach (keys %{$props}) {
2757 # If it doesn't start with `svn:', it must be a
2758 # user-defined property.
2759 ++$interesting_props and next if $_ !~ /^svn:/;
2760 # FIXME: Fragile, if SVN adds new public properties,
2761 # this needs to be updated.
2762 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2763 |eol-style|mime-type
2764 |externals|needs-lock)$/x;
2766 &$sub($self, $p, $props) if $interesting_props;
2768 foreach (sort keys %$dirent) {
2769 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2770 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2774 sub last_rev { ($_[0]->last_rev_commit)[0] }
2775 sub last_commit { ($_[0]->last_rev_commit)[1] }
2777 # returns the newest SVN revision number and newest commit SHA1
2778 sub last_rev_commit {
2779 my ($self) = @_;
2780 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2781 return ($self->{last_rev}, $self->{last_commit});
2783 my $c = ::verify_ref($self->refname.'^0');
2784 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2785 my $rev = (::cmt_metadata($c))[1];
2786 if (defined $rev) {
2787 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2788 return ($rev, $c);
2791 my $map_path = $self->map_path;
2792 unless (-e $map_path) {
2793 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2794 return (undef, undef);
2796 my ($rev, $commit) = $self->rev_map_max(1);
2797 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2798 return ($rev, $commit);
2801 sub get_fetch_range {
2802 my ($self, $min, $max) = @_;
2803 $max ||= $self->ra->get_latest_revnum;
2804 $min ||= $self->rev_map_max;
2805 (++$min, $max);
2808 sub tmp_config {
2809 my (@args) = @_;
2810 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2811 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2812 if (! -f $config && -f $old_def_config) {
2813 rename $old_def_config, $config or
2814 die "Failed rename $old_def_config => $config: $!\n";
2816 my $old_config = $ENV{GIT_CONFIG};
2817 $ENV{GIT_CONFIG} = $config;
2818 $@ = undef;
2819 my @ret = eval {
2820 unless (-f $config) {
2821 mkfile($config);
2822 open my $fh, '>', $config or
2823 die "Can't open $config: $!\n";
2824 print $fh "; This file is used internally by ",
2825 "git-svn\n" or die
2826 "Couldn't write to $config: $!\n";
2827 print $fh "; You should not have to edit it\n" or
2828 die "Couldn't write to $config: $!\n";
2829 close $fh or die "Couldn't close $config: $!\n";
2831 command('config', @args);
2833 my $err = $@;
2834 if (defined $old_config) {
2835 $ENV{GIT_CONFIG} = $old_config;
2836 } else {
2837 delete $ENV{GIT_CONFIG};
2839 die $err if $err;
2840 wantarray ? @ret : $ret[0];
2843 sub tmp_index_do {
2844 my ($self, $sub) = @_;
2845 my $old_index = $ENV{GIT_INDEX_FILE};
2846 $ENV{GIT_INDEX_FILE} = $self->{index};
2847 $@ = undef;
2848 my @ret = eval {
2849 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2850 mkpath([$dir]) unless -d $dir;
2851 &$sub;
2853 my $err = $@;
2854 if (defined $old_index) {
2855 $ENV{GIT_INDEX_FILE} = $old_index;
2856 } else {
2857 delete $ENV{GIT_INDEX_FILE};
2859 die $err if $err;
2860 wantarray ? @ret : $ret[0];
2863 sub assert_index_clean {
2864 my ($self, $treeish) = @_;
2866 $self->tmp_index_do(sub {
2867 command_noisy('read-tree', $treeish) unless -e $self->{index};
2868 my $x = command_oneline('write-tree');
2869 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2870 /^tree ($::sha1)/mo);
2871 return if $y eq $x;
2873 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2874 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2875 command_noisy('read-tree', $treeish);
2876 $x = command_oneline('write-tree');
2877 if ($y ne $x) {
2878 ::fatal "trees ($treeish) $y != $x\n",
2879 "Something is seriously wrong...";
2884 sub get_commit_parents {
2885 my ($self, $log_entry) = @_;
2886 my (%seen, @ret, @tmp);
2887 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2888 if (my $ip = $self->{inject_parents}) {
2889 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2890 push @tmp, $commit;
2893 if (my $cur = ::verify_ref($self->refname.'^0')) {
2894 push @tmp, $cur;
2896 if (my $ipd = $self->{inject_parents_dcommit}) {
2897 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2898 push @tmp, @$commit;
2901 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2902 while (my $p = shift @tmp) {
2903 next if $seen{$p};
2904 $seen{$p} = 1;
2905 push @ret, $p;
2907 @ret;
2910 sub rewrite_root {
2911 my ($self) = @_;
2912 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2913 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2914 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2915 if ($rwr) {
2916 $rwr =~ s#/+$##;
2917 if ($rwr !~ m#^[a-z\+]+://#) {
2918 die "$rwr is not a valid URL (key: $k)\n";
2921 $self->{-rewrite_root} = $rwr;
2924 sub rewrite_uuid {
2925 my ($self) = @_;
2926 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2927 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2928 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2929 if ($rwid) {
2930 $rwid =~ s#/+$##;
2931 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2932 die "$rwid is not a valid UUID (key: $k)\n";
2935 $self->{-rewrite_uuid} = $rwid;
2938 sub metadata_url {
2939 my ($self) = @_;
2940 ($self->rewrite_root || $self->{url}) .
2941 (length $self->{path} ? '/' . $self->{path} : '');
2944 sub full_url {
2945 my ($self) = @_;
2946 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2949 sub full_pushurl {
2950 my ($self) = @_;
2951 if ($self->{pushurl}) {
2952 return $self->{pushurl} . (length $self->{path} ? '/' .
2953 $self->{path} : '');
2954 } else {
2955 return $self->full_url;
2959 sub set_commit_header_env {
2960 my ($log_entry) = @_;
2961 my %env;
2962 foreach my $ned (qw/NAME EMAIL DATE/) {
2963 foreach my $ac (qw/AUTHOR COMMITTER/) {
2964 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2968 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2969 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2970 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2972 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2973 ? $log_entry->{commit_name}
2974 : $log_entry->{name};
2975 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2976 ? $log_entry->{commit_email}
2977 : $log_entry->{email};
2978 \%env;
2981 sub restore_commit_header_env {
2982 my ($env) = @_;
2983 foreach my $ned (qw/NAME EMAIL DATE/) {
2984 foreach my $ac (qw/AUTHOR COMMITTER/) {
2985 my $k = "GIT_${ac}_${ned}";
2986 if (defined $env->{$k}) {
2987 $ENV{$k} = $env->{$k};
2988 } else {
2989 delete $ENV{$k};
2995 sub gc {
2996 command_noisy('gc', '--auto');
2999 sub do_git_commit {
3000 my ($self, $log_entry) = @_;
3001 my $lr = $self->last_rev;
3002 if (defined $lr && $lr >= $log_entry->{revision}) {
3003 die "Last fetched revision of ", $self->refname,
3004 " was r$lr, but we are about to fetch: ",
3005 "r$log_entry->{revision}!\n";
3007 if (my $c = $self->rev_map_get($log_entry->{revision})) {
3008 croak "$log_entry->{revision} = $c already exists! ",
3009 "Why are we refetching it?\n";
3011 my $old_env = set_commit_header_env($log_entry);
3012 my $tree = $log_entry->{tree};
3013 if (!defined $tree) {
3014 $tree = $self->tmp_index_do(sub {
3015 command_oneline('write-tree') });
3017 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3019 my @exec = ('git', 'commit-tree', $tree);
3020 foreach ($self->get_commit_parents($log_entry)) {
3021 push @exec, '-p', $_;
3023 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3024 or croak $!;
3025 binmode $msg_fh;
3027 # we always get UTF-8 from SVN, but we may want our commits in
3028 # a different encoding.
3029 if (my $enc = Git::config('i18n.commitencoding')) {
3030 require Encode;
3031 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3033 print $msg_fh $log_entry->{log} or croak $!;
3034 restore_commit_header_env($old_env);
3035 unless ($self->no_metadata) {
3036 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3037 or croak $!;
3039 $msg_fh->flush == 0 or croak $!;
3040 close $msg_fh or croak $!;
3041 chomp(my $commit = do { local $/; <$out_fh> });
3042 close $out_fh or croak $!;
3043 waitpid $pid, 0;
3044 croak $? if $?;
3045 if ($commit !~ /^$::sha1$/o) {
3046 die "Failed to commit, invalid sha1: $commit\n";
3049 $self->rev_map_set($log_entry->{revision}, $commit, 1);
3051 $self->{last_rev} = $log_entry->{revision};
3052 $self->{last_commit} = $commit;
3053 print "r$log_entry->{revision}" unless $::_q > 1;
3054 if (defined $log_entry->{svm_revision}) {
3055 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
3056 $self->rev_map_set($log_entry->{svm_revision}, $commit,
3057 0, $self->svm_uuid);
3059 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
3060 if (--$_gc_nr == 0) {
3061 $_gc_nr = $_gc_period;
3062 gc();
3064 return $commit;
3067 sub match_paths {
3068 my ($self, $paths, $r) = @_;
3069 return 1 if $self->{path} eq '';
3070 if (my $path = $paths->{"/$self->{path}"}) {
3071 return ($path->{action} eq 'D') ? 0 : 1;
3073 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
3074 if (grep /$self->{path_regex}/, keys %$paths) {
3075 return 1;
3077 my $c = '';
3078 foreach (split m#/#, $self->{path}) {
3079 $c .= "/$_";
3080 next unless ($paths->{$c} &&
3081 ($paths->{$c}->{action} =~ /^[AR]$/));
3082 if ($self->ra->check_path($self->{path}, $r) ==
3083 $SVN::Node::dir) {
3084 return 1;
3087 return 0;
3090 sub find_parent_branch {
3091 my ($self, $paths, $rev) = @_;
3092 return undef unless $self->follow_parent;
3093 unless (defined $paths) {
3094 my $err_handler = $SVN::Error::handler;
3095 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3096 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3097 sub { $paths = $_[0] });
3098 $SVN::Error::handler = $err_handler;
3100 return undef unless defined $paths;
3102 # look for a parent from another branch:
3103 my @b_path_components = split m#/#, $self->{path};
3104 my @a_path_components;
3105 my $i;
3106 while (@b_path_components) {
3107 $i = $paths->{'/'.join('/', @b_path_components)};
3108 last if $i && defined $i->{copyfrom_path};
3109 unshift(@a_path_components, pop(@b_path_components));
3111 return undef unless defined $i && defined $i->{copyfrom_path};
3112 my $branch_from = $i->{copyfrom_path};
3113 if (@a_path_components) {
3114 print STDERR "branch_from: $branch_from => ";
3115 $branch_from .= '/'.join('/', @a_path_components);
3116 print STDERR $branch_from, "\n";
3118 my $r = $i->{copyfrom_rev};
3119 my $repos_root = $self->ra->{repos_root};
3120 my $url = $self->ra->{url};
3121 my $new_url = $url . $branch_from;
3122 print STDERR "Found possible branch point: ",
3123 "$new_url => ", $self->full_url, ", $r\n"
3124 unless $::_q > 1;
3125 $branch_from =~ s#^/##;
3126 my $gs = $self->other_gs($new_url, $url,
3127 $branch_from, $r, $self->{ref_id});
3128 my ($r0, $parent) = $gs->find_rev_before($r, 1);
3130 my ($base, $head);
3131 if (!defined $r0 || !defined $parent) {
3132 ($base, $head) = parse_revision_argument(0, $r);
3133 } else {
3134 if ($r0 < $r) {
3135 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3136 0, 1, sub { $base = $_[1] - 1 });
3139 if (defined $base && $base <= $r) {
3140 $gs->fetch($base, $r);
3142 ($r0, $parent) = $gs->find_rev_before($r, 1);
3144 if (defined $r0 && defined $parent) {
3145 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3146 unless $::_q > 1;
3147 my $ed;
3148 if ($self->ra->can_do_switch) {
3149 $self->assert_index_clean($parent);
3150 print STDERR "Following parent with do_switch\n"
3151 unless $::_q > 1;
3152 # do_switch works with svn/trunk >= r22312, but that
3153 # is not included with SVN 1.4.3 (the latest version
3154 # at the moment), so we can't rely on it
3155 $self->{last_rev} = $r0;
3156 $self->{last_commit} = $parent;
3157 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
3158 $gs->ra->gs_do_switch($r0, $rev, $gs,
3159 $self->full_url, $ed)
3160 or die "SVN connection failed somewhere...\n";
3161 } elsif ($self->ra->trees_match($new_url, $r0,
3162 $self->full_url, $rev)) {
3163 print STDERR "Trees match:\n",
3164 " $new_url\@$r0\n",
3165 " ${\$self->full_url}\@$rev\n",
3166 "Following parent with no changes\n"
3167 unless $::_q > 1;
3168 $self->tmp_index_do(sub {
3169 command_noisy('read-tree', $parent);
3171 $self->{last_commit} = $parent;
3172 } else {
3173 print STDERR "Following parent with do_update\n"
3174 unless $::_q > 1;
3175 $ed = SVN::Git::Fetcher->new($self);
3176 $self->ra->gs_do_update($rev, $rev, $self, $ed)
3177 or die "SVN connection failed somewhere...\n";
3179 print STDERR "Successfully followed parent\n" unless $::_q > 1;
3180 return $self->make_log_entry($rev, [$parent], $ed);
3182 return undef;
3185 sub do_fetch {
3186 my ($self, $paths, $rev) = @_;
3187 my $ed;
3188 my ($last_rev, @parents);
3189 if (my $lc = $self->last_commit) {
3190 # we can have a branch that was deleted, then re-added
3191 # under the same name but copied from another path, in
3192 # which case we'll have multiple parents (we don't
3193 # want to break the original ref, nor lose copypath info):
3194 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3195 push @{$log_entry->{parents}}, $lc;
3196 return $log_entry;
3198 $ed = SVN::Git::Fetcher->new($self);
3199 $last_rev = $self->{last_rev};
3200 $ed->{c} = $lc;
3201 @parents = ($lc);
3202 } else {
3203 $last_rev = $rev;
3204 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3205 return $log_entry;
3207 $ed = SVN::Git::Fetcher->new($self);
3209 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
3210 die "SVN connection failed somewhere...\n";
3212 $self->make_log_entry($rev, \@parents, $ed);
3215 sub mkemptydirs {
3216 my ($self, $r) = @_;
3218 sub scan {
3219 my ($r, $empty_dirs, $line) = @_;
3220 if (defined $r && $line =~ /^r(\d+)$/) {
3221 return 0 if $1 > $r;
3222 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3223 $empty_dirs->{$1} = 1;
3224 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3225 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3226 delete @$empty_dirs{@d};
3228 1; # continue
3231 my %empty_dirs = ();
3232 my $gz_file = "$self->{dir}/unhandled.log.gz";
3233 if (-f $gz_file) {
3234 if (!$can_compress) {
3235 warn "Compress::Zlib could not be found; ",
3236 "empty directories in $gz_file will not be read\n";
3237 } else {
3238 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3239 die "Unable to open $gz_file: $!\n";
3240 my $line;
3241 while ($gz->gzreadline($line) > 0) {
3242 scan($r, \%empty_dirs, $line) or last;
3244 $gz->gzclose;
3248 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3249 binmode $fh or croak "binmode: $!";
3250 while (<$fh>) {
3251 scan($r, \%empty_dirs, $_) or last;
3253 close $fh;
3256 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
3257 foreach my $d (sort keys %empty_dirs) {
3258 $d = uri_decode($d);
3259 $d =~ s/$strip//;
3260 next unless length($d);
3261 next if -d $d;
3262 if (-e $d) {
3263 warn "$d exists but is not a directory\n";
3264 } else {
3265 print "creating empty directory: $d\n";
3266 mkpath([$d]);
3271 sub get_untracked {
3272 my ($self, $ed) = @_;
3273 my @out;
3274 my $h = $ed->{empty};
3275 foreach (sort keys %$h) {
3276 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
3277 push @out, " $act: " . uri_encode($_);
3278 warn "W: $act: $_\n";
3280 foreach my $t (qw/dir_prop file_prop/) {
3281 $h = $ed->{$t} or next;
3282 foreach my $path (sort keys %$h) {
3283 my $ppath = $path eq '' ? '.' : $path;
3284 foreach my $prop (sort keys %{$h->{$path}}) {
3285 next if $SKIP_PROP{$prop};
3286 my $v = $h->{$path}->{$prop};
3287 my $t_ppath_prop = "$t: " .
3288 uri_encode($ppath) . ' ' .
3289 uri_encode($prop);
3290 if (defined $v) {
3291 push @out, " +$t_ppath_prop " .
3292 uri_encode($v);
3293 } else {
3294 push @out, " -$t_ppath_prop";
3299 foreach my $t (qw/absent_file absent_directory/) {
3300 $h = $ed->{$t} or next;
3301 foreach my $parent (sort keys %$h) {
3302 foreach my $path (sort @{$h->{$parent}}) {
3303 push @out, " $t: " .
3304 uri_encode("$parent/$path");
3305 warn "W: $t: $parent/$path ",
3306 "Insufficient permissions?\n";
3310 \@out;
3313 sub get_tz {
3314 # some systmes don't handle or mishandle %z, so be creative.
3315 my $t = shift || time;
3316 my $gm = timelocal(gmtime($t));
3317 my $sign = qw( + + - )[ $t <=> $gm ];
3318 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3321 # parse_svn_date(DATE)
3322 # --------------------
3323 # Given a date (in UTC) from Subversion, return a string in the format
3324 # "<TZ Offset> <local date/time>" that Git will use.
3326 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
3327 # is true we'll convert it to the local timezone instead.
3328 sub parse_svn_date {
3329 my $date = shift || return '+0000 1970-01-01 00:00:00';
3330 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
3331 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
3332 croak "Unable to parse date: $date\n";
3333 my $parsed_date; # Set next.
3335 if ($Git::SVN::_localtime) {
3336 # Translate the Subversion datetime to an epoch time.
3337 # Begin by switching ourselves to $date's timezone, UTC.
3338 my $old_env_TZ = $ENV{TZ};
3339 $ENV{TZ} = 'UTC';
3341 my $epoch_in_UTC =
3342 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3344 # Determine our local timezone (including DST) at the
3345 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3346 # value of TZ, if any, at the time we were run.
3347 if (defined $Git::SVN::Log::TZ) {
3348 $ENV{TZ} = $Git::SVN::Log::TZ;
3349 } else {
3350 delete $ENV{TZ};
3353 my $our_TZ = get_tz();
3355 # This converts $epoch_in_UTC into our local timezone.
3356 my ($sec, $min, $hour, $mday, $mon, $year,
3357 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3359 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3360 $our_TZ, $year + 1900, $mon + 1,
3361 $mday, $hour, $min, $sec);
3363 # Reset us to the timezone in effect when we entered
3364 # this routine.
3365 if (defined $old_env_TZ) {
3366 $ENV{TZ} = $old_env_TZ;
3367 } else {
3368 delete $ENV{TZ};
3370 } else {
3371 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3374 return $parsed_date;
3377 sub other_gs {
3378 my ($self, $new_url, $url,
3379 $branch_from, $r, $old_ref_id) = @_;
3380 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
3381 unless ($gs) {
3382 my $ref_id = $old_ref_id;
3383 $ref_id =~ s/\@\d+-*$//;
3384 $ref_id .= "\@$r";
3385 # just grow a tail if we're not unique enough :x
3386 $ref_id .= '-' while find_ref($ref_id);
3387 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3388 if ($u =~ s#^\Q$url\E(/|$)##) {
3389 $p = $u;
3390 $u = $url;
3391 $repo_id = $self->{repo_id};
3393 while (1) {
3394 # It is possible to tag two different subdirectories at
3395 # the same revision. If the url for an existing ref
3396 # does not match, we must either find a ref with a
3397 # matching url or create a new ref by growing a tail.
3398 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3399 my (undef, $max_commit) = $gs->rev_map_max(1);
3400 last if (!$max_commit);
3401 my ($url) = ::cmt_metadata($max_commit);
3402 last if ($url eq $gs->metadata_url);
3403 $ref_id .= '-';
3405 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3410 sub call_authors_prog {
3411 my ($orig_author) = @_;
3412 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3413 my $author = `$::_authors_prog $orig_author`;
3414 if ($? != 0) {
3415 die "$::_authors_prog failed with exit code $?\n"
3417 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3418 my ($name, $email) = ($1, $2);
3419 $email = undef if length $2 == 0;
3420 return [$name, $email];
3421 } else {
3422 die "Author: $orig_author: $::_authors_prog returned "
3423 . "invalid author format: $author\n";
3427 sub check_author {
3428 my ($author) = @_;
3429 if (!defined $author || length $author == 0) {
3430 $author = '(no author)';
3432 if (!defined $::users{$author}) {
3433 if (defined $::_authors_prog) {
3434 $::users{$author} = call_authors_prog($author);
3435 } elsif (defined $::_authors) {
3436 die "Author: $author not defined in $::_authors file\n";
3439 $author;
3442 sub find_extra_svk_parents {
3443 my ($self, $ed, $tickets, $parents) = @_;
3444 # aha! svk:merge property changed...
3445 my @tickets = split "\n", $tickets;
3446 my @known_parents;
3447 for my $ticket ( @tickets ) {
3448 my ($uuid, $path, $rev) = split /:/, $ticket;
3449 if ( $uuid eq $self->ra_uuid ) {
3450 my $url = $self->{url};
3451 my $repos_root = $url;
3452 my $branch_from = $path;
3453 $branch_from =~ s{^/}{};
3454 my $gs = $self->other_gs($repos_root."/".$branch_from,
3455 $url,
3456 $branch_from,
3457 $rev,
3458 $self->{ref_id});
3459 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3460 # wahey! we found it, but it might be
3461 # an old one (!)
3462 push @known_parents, [ $rev, $commit ];
3466 # Ordering matters; highest-numbered commit merge tickets
3467 # first, as they may account for later merge ticket additions
3468 # or changes.
3469 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3470 for my $parent ( @known_parents ) {
3471 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3472 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3473 my $new;
3474 while ( <$msg_fh> ) {
3475 $new=1;last;
3477 command_close_pipe($msg_fh, $ctx);
3478 if ( $new ) {
3479 print STDERR
3480 "Found merge parent (svk:merge ticket): $parent\n";
3481 push @$parents, $parent;
3486 sub lookup_svn_merge {
3487 my $uuid = shift;
3488 my $url = shift;
3489 my $merge = shift;
3491 my ($source, $revs) = split ":", $merge;
3492 my $path = $source;
3493 $path =~ s{^/}{};
3494 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3495 if ( !$gs ) {
3496 warn "Couldn't find revmap for $url$source\n";
3497 return;
3499 my @ranges = split ",", $revs;
3500 my ($tip, $tip_commit);
3501 my @merged_commit_ranges;
3502 # find the tip
3503 for my $range ( @ranges ) {
3504 my ($bottom, $top) = split "-", $range;
3505 $top ||= $bottom;
3506 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3507 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3509 unless ($top_commit and $bottom_commit) {
3510 warn "W:unknown path/rev in svn:mergeinfo "
3511 ."dirprop: $source:$range\n";
3512 next;
3515 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3516 push @merged_commit_ranges,
3517 "$bottom_commit^..$top_commit";
3518 } else {
3519 push @merged_commit_ranges, "$top_commit";
3522 if ( !defined $tip or $top > $tip ) {
3523 $tip = $top;
3524 $tip_commit = $top_commit;
3527 return ($tip_commit, @merged_commit_ranges);
3530 sub _rev_list {
3531 my ($msg_fh, $ctx) = command_output_pipe(
3532 "rev-list", @_,
3534 my @rv;
3535 while ( <$msg_fh> ) {
3536 chomp;
3537 push @rv, $_;
3539 command_close_pipe($msg_fh, $ctx);
3540 @rv;
3543 sub check_cherry_pick {
3544 my $base = shift;
3545 my $tip = shift;
3546 my $parents = shift;
3547 my @ranges = @_;
3548 my %commits = map { $_ => 1 }
3549 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
3550 for my $range ( @ranges ) {
3551 delete @commits{_rev_list($range, "--")};
3553 for my $commit (keys %commits) {
3554 if (has_no_changes($commit)) {
3555 delete $commits{$commit};
3558 return (keys %commits);
3561 sub has_no_changes {
3562 my $commit = shift;
3564 my @revs = split / /, command_oneline(
3565 qw(rev-list --parents -1 -m), $commit);
3567 # Commits with no parents, e.g. the start of a partial branch,
3568 # have changes by definition.
3569 return 1 if (@revs < 2);
3571 # Commits with multiple parents, e.g a merge, have no changes
3572 # by definition.
3573 return 0 if (@revs > 2);
3575 return (command_oneline("rev-parse", "$commit^{tree}") eq
3576 command_oneline("rev-parse", "$commit~1^{tree}"));
3579 # The GIT_DIR environment variable is not always set until after the command
3580 # line arguments are processed, so we can't memoize in a BEGIN block.
3582 my $memoized = 0;
3584 sub memoize_svn_mergeinfo_functions {
3585 return if $memoized;
3586 $memoized = 1;
3588 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3589 mkpath([$cache_path]) unless -d $cache_path;
3591 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3592 "$cache_path/lookup_svn_merge.db", 'nstore';
3593 memoize 'lookup_svn_merge',
3594 SCALAR_CACHE => 'FAULT',
3595 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3598 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3599 "$cache_path/check_cherry_pick.db", 'nstore';
3600 memoize 'check_cherry_pick',
3601 SCALAR_CACHE => 'FAULT',
3602 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3605 tie my %has_no_changes_cache => 'Memoize::Storable',
3606 "$cache_path/has_no_changes.db", 'nstore';
3607 memoize 'has_no_changes',
3608 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3609 LIST_CACHE => 'FAULT',
3613 sub unmemoize_svn_mergeinfo_functions {
3614 return if not $memoized;
3615 $memoized = 0;
3617 Memoize::unmemoize 'lookup_svn_merge';
3618 Memoize::unmemoize 'check_cherry_pick';
3619 Memoize::unmemoize 'has_no_changes';
3622 Memoize::memoize 'Git::SVN::repos_root';
3625 END {
3626 # Force cache writeout explicitly instead of waiting for
3627 # global destruction to avoid segfault in Storable:
3628 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3629 unmemoize_svn_mergeinfo_functions();
3632 sub parents_exclude {
3633 my $parents = shift;
3634 my @commits = @_;
3635 return unless @commits;
3637 my @excluded;
3638 my $excluded;
3639 do {
3640 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3641 $excluded = command_oneline(@cmd);
3642 if ( $excluded ) {
3643 my @new;
3644 my $found;
3645 for my $commit ( @commits ) {
3646 if ( $commit eq $excluded ) {
3647 push @excluded, $commit;
3648 $found++;
3649 last;
3651 else {
3652 push @new, $commit;
3655 die "saw commit '$excluded' in rev-list output, "
3656 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3657 unless $found;
3658 @commits = @new;
3661 while ($excluded and @commits);
3663 return @excluded;
3667 # note: this function should only be called if the various dirprops
3668 # have actually changed
3669 sub find_extra_svn_parents {
3670 my ($self, $ed, $mergeinfo, $parents) = @_;
3671 # aha! svk:merge property changed...
3673 memoize_svn_mergeinfo_functions();
3675 # We first search for merged tips which are not in our
3676 # history. Then, we figure out which git revisions are in
3677 # that tip, but not this revision. If all of those revisions
3678 # are now marked as merge, we can add the tip as a parent.
3679 my @merges = split "\n", $mergeinfo;
3680 my @merge_tips;
3681 my $url = $self->{url};
3682 my $uuid = $self->ra_uuid;
3683 my %ranges;
3684 for my $merge ( @merges ) {
3685 my ($tip_commit, @ranges) =
3686 lookup_svn_merge( $uuid, $url, $merge );
3687 unless (!$tip_commit or
3688 grep { $_ eq $tip_commit } @$parents ) {
3689 push @merge_tips, $tip_commit;
3690 $ranges{$tip_commit} = \@ranges;
3691 } else {
3692 push @merge_tips, undef;
3696 my %excluded = map { $_ => 1 }
3697 parents_exclude($parents, grep { defined } @merge_tips);
3699 # check merge tips for new parents
3700 my @new_parents;
3701 for my $merge_tip ( @merge_tips ) {
3702 my $spec = shift @merges;
3703 next unless $merge_tip and $excluded{$merge_tip};
3705 my $ranges = $ranges{$merge_tip};
3707 # check out 'new' tips
3708 my $merge_base;
3709 eval {
3710 $merge_base = command_oneline(
3711 "merge-base",
3712 @$parents, $merge_tip,
3715 if ($@) {
3716 die "An error occurred during merge-base"
3717 unless $@->isa("Git::Error::Command");
3719 warn "W: Cannot find common ancestor between ".
3720 "@$parents and $merge_tip. Ignoring merge info.\n";
3721 next;
3724 # double check that there are no missing non-merge commits
3725 my (@incomplete) = check_cherry_pick(
3726 $merge_base, $merge_tip,
3727 $parents,
3728 @$ranges,
3731 if ( @incomplete ) {
3732 warn "W:svn cherry-pick ignored ($spec) - missing "
3733 .@incomplete." commit(s) (eg $incomplete[0])\n";
3734 } else {
3735 warn
3736 "Found merge parent (svn:mergeinfo prop): ",
3737 $merge_tip, "\n";
3738 push @new_parents, $merge_tip;
3742 # cater for merges which merge commits from multiple branches
3743 if ( @new_parents > 1 ) {
3744 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3745 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3746 next if $i == $j;
3747 next unless $new_parents[$i];
3748 next unless $new_parents[$j];
3749 my $revs = command_oneline(
3750 "rev-list", "-1",
3751 "$new_parents[$i]..$new_parents[$j]",
3753 if ( !$revs ) {
3754 undef($new_parents[$j]);
3759 push @$parents, grep { defined } @new_parents;
3762 sub make_log_entry {
3763 my ($self, $rev, $parents, $ed) = @_;
3764 my $untracked = $self->get_untracked($ed);
3766 my @parents = @$parents;
3767 my $ps = $ed->{path_strip} || "";
3768 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3769 my $props = $ed->{dir_prop}{$path};
3770 if ( $props->{"svk:merge"} ) {
3771 $self->find_extra_svk_parents
3772 ($ed, $props->{"svk:merge"}, \@parents);
3774 if ( $props->{"svn:mergeinfo"} ) {
3775 $self->find_extra_svn_parents
3776 ($ed,
3777 $props->{"svn:mergeinfo"},
3778 \@parents);
3782 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3783 print $un "r$rev\n" or croak $!;
3784 print $un $_, "\n" foreach @$untracked;
3785 my %log_entry = ( parents => \@parents, revision => $rev,
3786 log => '');
3788 my $headrev;
3789 my $logged = delete $self->{logged_rev_props};
3790 if (!$logged || $self->{-want_revprops}) {
3791 my $rp = $self->ra->rev_proplist($rev);
3792 foreach (sort keys %$rp) {
3793 my $v = $rp->{$_};
3794 if (/^svn:(author|date|log)$/) {
3795 $log_entry{$1} = $v;
3796 } elsif ($_ eq 'svm:headrev') {
3797 $headrev = $v;