Merge branch 'master' of https://github.com/git-l10n/git-po
[git/git.git] / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
d48b2841 4use 5.008;
3397f9df
EW
5use warnings;
6use strict;
7use vars qw/ $AUTHOR $VERSION
ffe256f9 8 $sha1 $sha1_short $_revision $_repository
36db1edd 9 $_q $_authors $_authors_prog %users/;
3397f9df 10$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 11$VERSION = '@@GIT_VERSION@@';
13ccd6d4 12
15153451
BS
13# From which subdir have we been invoked?
14my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16} || '';
17
5253dc33 18my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 19$ENV{GIT_DIR} ||= '.git';
9fa00b65 20$Git::SVN::default_repo_id = 'svn';
8b8fc068 21$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 22$Git::SVN::Ra::_log_window_size = 100;
6b48829d 23$Git::SVN::_minimize_url = 'unset';
13ccd6d4 24
184892fb
SS
25if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27}
28
29if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
30 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
31 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
f3a87d92
K
32}
33
f8c9d1d2 34$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 35$ENV{TZ} = 'UTC';
a00439ac 36$| = 1; # unbuffer STDOUT
3397f9df 37
207f1a75 38sub fatal (@) { print STDERR "@_\n"; exit 1 }
6ade9bda
RK
39
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';
43
d32fad2b 44sub _req_svn {
45 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
46 require SVN::Ra;
47 require SVN::Delta;
48 if ($SVN::Core::VERSION lt '1.1.0') {
49 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
50 }
b9c85187 51}
2da9ee08 52my $can_compress = eval { require Compress::Zlib; 1};
d81bf827 53push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
54push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
55push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df 56use Carp qw/croak/;
8d7c4fad 57use Digest::MD5;
3397f9df
EW
58use IO::File qw//;
59use File::Basename qw/dirname basename/;
60use File::Path qw/mkpath/;
36db1edd 61use File::Spec;
2da9ee08 62use File::Find;
512b620b 63use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
968bdf1f 64use IPC::Open3;
336f1714 65use Git;
f5549afd 66use Memoize; # core since 5.8.0, Jul 2002
a5e0cedc 67
336f1714 68BEGIN {
c5f71ad0
SV
69 # import functions from Git into our packages, en masse
70 no strict 'refs';
336f1714 71 foreach (qw/command command_oneline command_noisy command_output_pipe
6ea42032
BB
72 command_input_pipe command_close_pipe
73 command_bidi_pipe command_close_bidi_pipe/) {
c5f71ad0 74 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
8d7c4fad 75 Git::SVN::Migration Git::SVN::Log Git::SVN),
c5f71ad0
SV
76 __PACKAGE__) {
77 *{"${package}::$_"} = \&{"Git::$_"};
78 }
336f1714 79 }
f5549afd
JK
80 Memoize::memoize 'Git::config';
81 Memoize::memoize 'Git::config_bool';
336f1714
EW
82}
83
b9c85187 84my ($SVN);
83e9940a 85
f8c9d1d2
EW
86$sha1 = qr/[a-f\d]{40}/;
87$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 88my ($_stdin, $_help, $_edit,
62244069 89 $_message, $_file, $_branch_dest,
d05d72e0 90 $_template, $_shared,
c2abd83f 91 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
dee41f3e 92 $_merge, $_strategy, $_dry_run, $_local,
4be40381 93 $_prefix, $_no_checkout, $_url, $_verbose,
afd7f1eb 94 $_git_format, $_commit_url, $_tag, $_merge_info, $_interactive);
0bed5eaa 95$Git::SVN::_follow_parent = 1;
40a1530c 96$SVN::Git::Fetcher::_placeholder_filename = ".gitignore";
49750f30 97$_q ||= 0;
706587fc
EW
98my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
99 'config-dir=s' => \$Git::SVN::Ra::config_dir,
edc662f9 100 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
cdb51a13
MO
101 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex,
102 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
0bed5eaa 103my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 104 'authors-file|A=s' => \$_authors,
36db1edd 105 'authors-prog=s' => \$_authors_prog,
ecc712dd 106 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
107 'noMetadata' => \$Git::SVN::_no_metadata,
108 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 109 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 110 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 111 'no-checkout' => \$_no_checkout,
49750f30 112 'quiet|q+' => \$_q,
ecc712dd
EW
113 'repack-flags|repack-args|repack-opts=s' =>
114 \$Git::SVN::_repack_flags,
70ae04e4 115 'use-log-author' => \$Git::SVN::_use_log_author,
6aa9ba14 116 'add-author-from' => \$Git::SVN::_add_author_from,
e82f0d73 117 'localtime' => \$Git::SVN::_localtime,
706587fc 118 %remote_opts );
36f5b1f0 119
62244069 120my ($_trunk, @_tags, @_branches, $_stdlayout);
0dfaf0a4 121my %icv;
dadc6d2a 122my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
62244069
MB
123 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
124 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
8f728fb9 125 'stdlayout|s' => \$_stdlayout,
6b48829d 126 'minimize-url|m!' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
127 'no-metadata' => sub { $icv{noMetadata} = 1 },
128 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
129 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
130 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
3e18ce1a 131 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
dadc6d2a 132 %remote_opts );
27e9fb8d 133my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
134 'rmdir' => \$SVN::Git::Editor::_rmdir,
135 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
136 'l=i' => \$SVN::Git::Editor::_rename_limit,
137 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 138);
9d55b41a 139
3397f9df 140my %cmd = (
2a3240be 141 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 142 { 'revision|r=s' => \$_revision,
905f8b7d 143 'fetch-all|all' => \$_fetch_all,
c2abd83f 144 'parent|p' => \$_fetch_parent,
e98671e5 145 %fc_opts } ],
0425ea90
EW
146 clone => [ \&cmd_clone, "Initialize and fetch revisions",
147 { 'revision|r=s' => \$_revision,
40a1530c
RC
148 'preserve-empty-dirs' =>
149 \$SVN::Git::Fetcher::_preserve_empty_dirs,
150 'placeholder-filename=s' =>
151 \$SVN::Git::Fetcher::_placeholder_filename,
0425ea90 152 %fc_opts, %init_opts } ],
d2866f9e 153 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 154 " (requires URL argument)",
9d55b41a 155 \%init_opts ],
dadc6d2a
EW
156 'multi-init' => [ \&cmd_multi_init,
157 "Deprecated alias for ".
158 "'$0 init -T<trunk> -b<branches> -t<tags>'",
159 \%init_opts ],
d7ad3bed
EW
160 dcommit => [ \&cmd_dcommit,
161 'Commit several diffs to merge with upstream',
3289e86e
EW
162 { 'merge|m|M' => \$_merge,
163 'strategy|s=s' => \$_strategy,
905f8b7d 164 'verbose|v' => \$_verbose,
3289e86e 165 'dry-run|n' => \$_dry_run,
905f8b7d 166 'fetch-all|all' => \$_fetch_all,
ba24e745
EW
167 'commit-url=s' => \$_commit_url,
168 'revision|r=i' => \$_revision,
171af110 169 'no-rebase' => \$_no_rebase,
6abd9332 170 'mergeinfo=s' => \$_merge_info,
afd7f1eb 171 'interactive|i' => \$_interactive,
4b155223 172 %cmt_opts, %fc_opts } ],
5de70efb
FR
173 branch => [ \&cmd_branch,
174 'Create a branch in the SVN repository',
175 { 'message|m=s' => \$_message,
62244069 176 'destination|d=s' => \$_branch_dest,
5de70efb 177 'dry-run|n' => \$_dry_run,
6594f0b7
IM
178 'tag|t' => \$_tag,
179 'username=s' => \$Git::SVN::Prompt::_username,
180 'commit-url=s' => \$_commit_url } ],
5de70efb
FR
181 tag => [ sub { $_tag = 1; cmd_branch(@_) },
182 'Create a tag in the SVN repository',
183 { 'message|m=s' => \$_message,
62244069 184 'destination|d=s' => \$_branch_dest,
6594f0b7
IM
185 'dry-run|n' => \$_dry_run,
186 'username=s' => \$Git::SVN::Prompt::_username,
187 'commit-url=s' => \$_commit_url } ],
1ce255dc
EW
188 'set-tree' => [ \&cmd_set_tree,
189 "Set an SVN repository to a git tree-ish",
e84dc6df 190 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
191 'create-ignore' => [ \&cmd_create_ignore,
192 'Create a .gitignore per svn:ignore',
193 { 'revision|r=i' => \$_revision
194 } ],
6111b934
EW
195 'mkdirs' => [ \&cmd_mkdirs ,
196 "recreate empty directories after a checkout",
197 { 'revision|r=i' => \$_revision } ],
15153451
BS
198 'propget' => [ \&cmd_propget,
199 'Print the value of a property on a file or directory',
200 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
201 'proplist' => [ \&cmd_proplist,
202 'List all properties of a file or directory',
203 { 'revision|r=i' => \$_revision } ],
5969cbe1 204 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 205 { 'revision|r=i' => \$_revision
05b4df31 206 } ],
2d879792
VK
207 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
208 { 'revision|r=i' => \$_revision
209 } ],
1c8443b0 210 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
211 "Deprecated alias for $0 fetch --all",
212 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
213 'migrate' => [ sub { },
214 # no-op, we automatically run this anyways,
706587fc
EW
215 'Migrate configuration/metadata/layout from
216 previous versions of git-svn',
a836a0e1
EW
217 { 'minimize' => \$Git::SVN::Migration::_minimize,
218 %remote_opts } ],
f8c9d1d2
EW
219 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
220 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 221 'revision|r=s' => \$_revision,
f8c9d1d2
EW
222 'verbose|v' => \$Git::SVN::Log::verbose,
223 'incremental' => \$Git::SVN::Log::incremental,
224 'oneline' => \$Git::SVN::Log::oneline,
225 'show-commit' => \$Git::SVN::Log::show_commit,
226 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 227 'authors-file|A=s' => \$_authors,
f8c9d1d2 228 'color' => \$Git::SVN::Log::color,
4dbfe2e9 229 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 230 } ],
222566e4
EW
231 'find-rev' => [ \&cmd_find_rev,
232 "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 233 {} ],
905f8b7d
EW
234 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
235 { 'merge|m|M' => \$_merge,
236 'verbose|v' => \$_verbose,
237 'strategy|s=s' => \$_strategy,
dee41f3e 238 'local|l' => \$_local,
905f8b7d 239 'fetch-all|all' => \$_fetch_all,
7d45e146 240 'dry-run|n' => \$_dry_run,
905f8b7d 241 %fc_opts } ],
44320b9e
EW
242 'commit-diff' => [ \&cmd_commit_diff,
243 'Commit a diff between two trees',
27e9fb8d
EW
244 { 'message|m=s' => \$_message,
245 'file|F=s' => \$_file,
45bf473a 246 'revision|r=s' => \$_revision,
27e9fb8d 247 %cmt_opts } ],
e6fefa92
DK
248 'info' => [ \&cmd_info,
249 "Show info about the latest SVN revision
250 on the current branch",
8b014d71 251 { 'url' => \$_url, } ],
6fb5375e
TS
252 'blame' => [ \&Git::SVN::Log::cmd_blame,
253 "Show what revision and author last modified each line of a file",
4be40381 254 { 'git-format' => \$_git_format } ],
195643f2
BJ
255 'reset' => [ \&cmd_reset,
256 "Undo fetches back to the specified SVN revision",
257 { 'revision|r=s' => \$_revision,
258 'parent|p' => \$_fetch_parent } ],
2da9ee08
RZ
259 'gc' => [ \&cmd_gc,
260 "Compress unhandled.log files in .git/svn and remove " .
261 "index files in .git/svn",
262 {} ],
3397f9df 263);
9d55b41a 264
afd7f1eb
FH
265use Term::ReadLine;
266package FakeTerm;
267sub new {
268 my ($class, $reason) = @_;
269 return bless \$reason, shift;
270}
271sub readline {
272 my $self = shift;
273 die "Cannot use readline on FakeTerm: $$self";
274}
275package main;
276
277my $term = eval {
278 $ENV{"GIT_SVN_NOTTY"}
279 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
280 : new Term::ReadLine 'git-svn';
281};
282if ($@) {
283 $term = new FakeTerm "$@: going non-interactive";
284}
285
3397f9df
EW
286my $cmd;
287for (my $i = 0; $i < @ARGV; $i++) {
288 if (defined $cmd{$ARGV[$i]}) {
289 $cmd = $ARGV[$i];
290 splice @ARGV, $i, 1;
291 last;
9a8c92ac
BJ
292 } elsif ($ARGV[$i] eq 'help') {
293 $cmd = $ARGV[$i+1];
294 usage(0);
3397f9df
EW
295 }
296};
297
540424b2
EW
298# make sure we're always running at the top-level working directory
299unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
300 unless (-d $ENV{GIT_DIR}) {
301 if ($git_dir_user_set) {
302 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
303 "but it is not a directory\n";
304 }
305 my $git_dir = delete $ENV{GIT_DIR};
fe4003f6
DM
306 my $cdup = undef;
307 git_cmd_try {
308 $cdup = command_oneline(qw/rev-parse --show-cdup/);
309 $git_dir = '.' unless ($cdup);
310 chomp $cdup if ($cdup);
311 $cdup = "." unless ($cdup && length $cdup);
312 } "Already at toplevel, but $git_dir not found\n";
5253dc33
EW
313 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
314 unless (-d $git_dir) {
315 die "$git_dir still not found after going to ",
316 "'$cdup'\n";
317 }
318 $ENV{GIT_DIR} = $git_dir;
319 }
ffe256f9 320 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
5253dc33 321}
f4dd334b
GH
322
323my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
324
1a30582b 325read_git_config(\%opts);
222566e4
EW
326if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
327 Getopt::Long::Configure('pass_through');
328}
87182b17 329my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
f4dd334b
GH
330 'minimize-connections' => \$Git::SVN::Migration::_minimize,
331 'id|i=s' => \$Git::SVN::default_ref_id,
332 'svn-remote|remote|R=s' => sub {
333 $Git::SVN::no_reuse_existing = 1;
334 $Git::SVN::default_repo_id = $_[1] });
335exit 1 if (!$rv && $cmd && $cmd ne 'log');
336
337usage(0) if $_help;
338version() if $_version;
339usage(1) unless defined $cmd;
340load_authors() if $_authors;
36db1edd
ML
341if (defined $_authors_prog) {
342 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
343}
f4dd334b 344
0425ea90 345unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
346 Git::SVN::Migration::migration_check();
347}
ecc712dd 348Git::SVN::init_vars();
b805b44a
EW
349eval {
350 Git::SVN::verify_remotes_sanity();
351 $cmd{$cmd}->[0]->(@ARGV);
352};
353fatal $@ if $@;
1e889ef3 354post_fetch_checkout();
3397f9df
EW
355exit 0;
356
357####################### primary functions ######################
358sub usage {
359 my $exit = shift || 0;
360 my $fd = $exit ? \*STDERR : \*STDOUT;
361 print $fd <<"";
362git-svn - bidirectional operations between a single Subversion tree and git
1b1dd23f 363Usage: git svn <command> [options] [arguments]\n
448c81b4
EW
364
365 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
366
367 foreach (sort keys %cmd) {
448c81b4 368 next if $cmd && $cmd ne $_;
a836a0e1 369 next if /^multi-/; # don't show deprecated commands
b203b769 370 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 371 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
372 # mixed-case options are for .git/config only
373 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 374 # prints out arguments as they should be passed:
b8c92cad 375 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 376 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
377 "--$_" : "-$_" }
378 split /\|/,$_)," $x\n";
379 }
3397f9df
EW
380 }
381 print $fd <<"";
448c81b4
EW
382\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
383arbitrary identifier if you're tracking multiple SVN branches/repositories in
384one git repository and want to keep them separate. See git-svn(1) for more
385information.
3397f9df
EW
386
387 exit $exit;
388}
389
551ce28f 390sub version {
b0779246 391 ::_req_svn();
7d60ab2c 392 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
393 exit 0;
394}
395
afd7f1eb
FH
396sub ask {
397 my ($prompt, %arg) = @_;
398 my $valid_re = $arg{valid_re};
399 my $default = $arg{default};
400 my $resp;
401 my $i = 0;
402
403 if ( !( defined($term->IN)
404 && defined( fileno($term->IN) )
405 && defined( $term->OUT )
406 && defined( fileno($term->OUT) ) ) ){
407 return defined($default) ? $default : undef;
408 }
409
410 while ($i++ < 10) {
411 $resp = $term->readline($prompt);
412 if (!defined $resp) { # EOF
413 print "\n";
414 return defined $default ? $default : undef;
415 }
416 if ($resp eq '' and defined $default) {
417 return $default;
418 }
419 if (!defined $valid_re or $resp =~ /$valid_re/) {
420 return $resp;
421 }
422 }
423 return undef;
424}
425
8164b652
EW
426sub do_git_init_db {
427 unless (-d $ENV{GIT_DIR}) {
428 my @init_db = ('init');
429 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
430 if (defined $_shared) {
431 if ($_shared =~ /[a-z]/) {
432 push @init_db, "--shared=$_shared";
433 } else {
434 push @init_db, "--shared";
435 }
436 }
8164b652 437 command_noisy(@init_db);
ffe256f9 438 $_repository = Git->repository(Repository => ".git");
8164b652 439 }
0dfaf0a4
EW
440 my $set;
441 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
442 foreach my $i (keys %icv) {
443 die "'$set' and '$i' cannot both be set\n" if $set;
444 next unless defined $icv{$i};
445 command_noisy('config', "$pfx.$i", $icv{$i});
446 $set = $i;
447 }
cdb51a13
MO
448 my $ignore_paths_regex = \$SVN::Git::Fetcher::_ignore_regex;
449 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
450 if defined $$ignore_paths_regex;
451 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
452 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
453 if defined $$ignore_refs_regex;
40a1530c
RC
454
455 if (defined $SVN::Git::Fetcher::_preserve_empty_dirs) {
456 my $fname = \$SVN::Git::Fetcher::_placeholder_filename;
457 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
458 command_noisy('config', "$pfx.placeholder-filename", $$fname);
459 }
8164b652
EW
460}
461
dadc6d2a
EW
462sub init_subdir {
463 my $repo_path = shift or return;
464 mkpath([$repo_path]) unless -d $repo_path;
465 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 466 $ENV{GIT_DIR} = '.git';
ffe256f9 467 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
dadc6d2a
EW
468}
469
0425ea90
EW
470sub cmd_clone {
471 my ($url, $path) = @_;
472 if (!defined $path &&
62244069 473 (defined $_trunk || @_branches || @_tags ||
8f728fb9 474 defined $_stdlayout) &&
0425ea90
EW
475 $url !~ m#^[a-z\+]+://#) {
476 $path = $url;
477 }
0425ea90 478 $path = basename($url) if !defined $path || !length $path;
2bc35dcb 479 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
f30603fc 480 cmd_init($url, $path);
2bc35dcb
AV
481 command_oneline('config', 'svn.authorsfile', $authors_absolute)
482 if $_authors;
f5841509 483 Git::SVN::fetch_all($Git::SVN::default_repo_id);
0425ea90
EW
484}
485
d2866f9e 486sub cmd_init {
8f728fb9 487 if (defined $_stdlayout) {
488 $_trunk = 'trunk' if (!defined $_trunk);
62244069
MB
489 @_tags = 'tags' if (! @_tags);
490 @_branches = 'branches' if (! @_branches);
8f728fb9 491 }
62244069 492 if (defined $_trunk || @_branches || @_tags) {
dadc6d2a 493 return cmd_multi_init(@_);
03e0ea87 494 }
dadc6d2a
EW
495 my $url = shift or die "SVN repository location required ",
496 "as a command-line argument\n";
50ff2366 497 $url = canonicalize_url($url);
dadc6d2a 498 init_subdir(@_);
8164b652 499 do_git_init_db();
03e0ea87 500
6b48829d
EW
501 if ($Git::SVN::_minimize_url eq 'unset') {
502 $Git::SVN::_minimize_url = 0;
503 }
504
706587fc 505 Git::SVN->init($url);
3397f9df
EW
506}
507
2a3240be 508sub cmd_fetch {
e98671e5
EW
509 if (grep /^\d+=./, @_) {
510 die "'<rev>=<commit>' fetch arguments are ",
511 "no longer supported.\n";
07a1c950 512 }
e98671e5
EW
513 my ($remote) = @_;
514 if (@_ > 1) {
c2abd83f 515 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
e98671e5 516 }
4d0157d6 517 $Git::SVN::no_reuse_existing = undef;
c2abd83f
JM
518 if ($_fetch_parent) {
519 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
520 unless ($gs) {
521 die "Unable to determine upstream SVN information from ",
522 "working tree history\n";
523 }
524 # just fetch, don't checkout.
525 $_no_checkout = 'true';
526 $_fetch_all ? $gs->fetch_all : $gs->fetch;
527 } elsif ($_fetch_all) {
e98671e5
EW
528 cmd_multi_fetch();
529 } else {
c2abd83f 530 $remote ||= $Git::SVN::default_repo_id;
e98671e5 531 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 532 }
2a3240be
EW
533}
534
1ce255dc 535sub cmd_set_tree {
3397f9df
EW
536 my (@commits) = @_;
537 if ($_stdin || !@commits) {
538 print "Reading from stdin...\n";
539 @commits = ();
540 while (<STDIN>) {
1ca72aef 541 if (/\b($sha1_short)\b/o) {
3397f9df
EW
542 unshift @commits, $1;
543 }
544 }
545 }
546 my @revs;
8de010ad 547 foreach my $c (@commits) {
aef4e921 548 my @tmp = command('rev-parse',$c);
8de010ad
EW
549 if (scalar @tmp == 1) {
550 push @revs, $tmp[0];
551 } elsif (scalar @tmp > 1) {
aef4e921 552 push @revs, reverse(command('rev-list',@tmp));
8de010ad 553 } else {
207f1a75 554 fatal "Failed to rev-parse $c";
8de010ad 555 }
3397f9df 556 }
1ce255dc
EW
557 my $gs = Git::SVN->new;
558 my ($r_last, $cmt_last) = $gs->last_rev_commit;
559 $gs->fetch;
97f6987a 560 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
561 fatal "There are new revisions that were fetched ",
562 "and need to be merged (or acknowledged) ",
563 "before committing.\nlast rev: $r_last\n",
207f1a75 564 " current: $gs->{last_rev}";
a5e0cedc 565 }
1ce255dc
EW
566 $gs->set_tree($_) foreach @revs;
567 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 568 unlink $gs->{index};
a5e0cedc 569}
8f22562c 570
1e5814f3
BJ
571sub split_merge_info_range {
572 my ($range) = @_;
573 if ($range =~ /(\d+)-(\d+)/) {
574 return (int($1), int($2));
575 } else {
576 return (int($range), int($range));
577 }
578}
579
580sub combine_ranges {
581 my ($in) = @_;
582
583 my @fnums = ();
584 my @arr = split(/,/, $in);
585 for my $element (@arr) {
586 my ($start, $end) = split_merge_info_range($element);
587 push @fnums, $start;
588 }
589
590 my @sorted = @arr [ sort {
591 $fnums[$a] <=> $fnums[$b]
592 } 0..$#arr ];
593
594 my @return = ();
595 my $last = -1;
596 my $first = -1;
597 for my $element (@sorted) {
598 my ($start, $end) = split_merge_info_range($element);
599
600 if ($last == -1) {
601 $first = $start;
602 $last = $end;
603 next;
604 }
605 if ($start <= $last+1) {
606 if ($end > $last) {
607 $last = $end;
608 }
609 next;
610 }
611 if ($first == $last) {
612 push @return, "$first";
613 } else {
614 push @return, "$first-$last";
615 }
616 $first = $start;
617 $last = $end;
618 }
619
620 if ($first != -1) {
621 if ($first == $last) {
622 push @return, "$first";
623 } else {
624 push @return, "$first-$last";
625 }
626 }
627
628 return join(',', @return);
629}
630
631sub merge_revs_into_hash {
632 my ($hash, $minfo) = @_;
633 my @lines = split(' ', $minfo);
634
635 for my $line (@lines) {
636 my ($branchpath, $revs) = split(/:/, $line);
637
638 if (exists($hash->{$branchpath})) {
639 # Merge the two revision sets
640 my $combined = "$hash->{$branchpath},$revs";
641 $hash->{$branchpath} = combine_ranges($combined);
642 } else {
643 # Just do range combining for consolidation
644 $hash->{$branchpath} = combine_ranges($revs);
645 }
646 }
647}
648
649sub merge_merge_info {
650 my ($mergeinfo_one, $mergeinfo_two) = @_;
651 my %result_hash = ();
652
653 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
654 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
655
656 my $result = '';
657 # Sort below is for consistency's sake
658 for my $branchname (sort keys(%result_hash)) {
659 my $revlist = $result_hash{$branchname};
660 $result .= "$branchname:$revlist\n"
661 }
662 return $result;
663}
664
665sub populate_merge_info {
666 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
667
668 my %parentshash;
669 read_commit_parents(\%parentshash, $d);
670 my @parents = @{$parentshash{$d}};
671 if ($#parents > 0) {
672 # Merge commit
673 my $all_parents_ok = 1;
674 my $aggregate_mergeinfo = '';
675 my $rooturl = $gs->repos_root;
676
677 if (defined($rewritten_parent)) {
678 # Replace first parent with newly-rewritten version
679 shift @parents;
680 unshift @parents, $rewritten_parent;
681 }
682
683 foreach my $parent (@parents) {
684 my ($branchurl, $svnrev, $paruuid) =
685 cmt_metadata($parent);
686
687 unless (defined($svnrev)) {
688 # Should have been caught be preflight check
689 fatal "merge commit $d has ancestor $parent, but that change "
690 ."does not have git-svn metadata!";
691 }
0e7e30f5 692 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
1e5814f3
BJ
693 fatal "commit $parent git-svn metadata changed mid-run!";
694 }
695 my $branchpath = $1;
696
697 my $ra = Git::SVN::Ra->new($branchurl);
698 my (undef, undef, $props) =
699 $ra->get_dir(canonicalize_path("."), $svnrev);
700 my $par_mergeinfo = $props->{'svn:mergeinfo'};
701 unless (defined $par_mergeinfo) {
702 $par_mergeinfo = '';
703 }
704 # Merge previous mergeinfo values
705 $aggregate_mergeinfo =
706 merge_merge_info($aggregate_mergeinfo,
707 $par_mergeinfo, 0);
708
709 next if $parent eq $parents[0]; # Skip first parent
710 # Add new changes being placed in tree by merge
711 my @cmd = (qw/rev-list --reverse/,
712 $parent, qw/--not/);
713 foreach my $par (@parents) {
714 unless ($par eq $parent) {
715 push @cmd, $par;
716 }
717 }
718 my @revsin = ();
719 my ($revlist, $ctx) = command_output_pipe(@cmd);
720 while (<$revlist>) {
721 my $irev = $_;
722 chomp $irev;
723 my (undef, $csvnrev, undef) =
724 cmt_metadata($irev);
725 unless (defined $csvnrev) {
726 # A child is missing SVN annotations...
727 # this might be OK, or might not be.
728 warn "W:child $irev is merged into revision "
729 ."$d but does not have git-svn metadata. "
730 ."This means git-svn cannot determine the "
731 ."svn revision numbers to place into the "
732 ."svn:mergeinfo property. You must ensure "
733 ."a branch is entirely committed to "
734 ."SVN before merging it in order for "
735 ."svn:mergeinfo population to function "
736 ."properly";
737 }
738 push @revsin, $csvnrev;
739 }
740 command_close_pipe($revlist, $ctx);
741
742 last unless $all_parents_ok;
743
744 # We now have a list of all SVN revnos which are
745 # merged by this particular parent. Integrate them.
746 next if $#revsin == -1;
747 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
748 $aggregate_mergeinfo =
749 merge_merge_info($aggregate_mergeinfo,
750 $newmergeinfo, 1);
751 }
752 if ($all_parents_ok and $aggregate_mergeinfo) {
753 return $aggregate_mergeinfo;
754 }
755 }
756
757 return undef;
758}
759
d7ad3bed
EW
760sub cmd_dcommit {
761 my $head = shift;
181264ad 762 command_noisy(qw/update-index --refresh/);
c8cfa3e4 763 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 764 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 765 . "or stash them with `git stash'.\n";
d7ad3bed 766 $head ||= 'HEAD';
5eec27e3
TR
767
768 my $old_head;
769 if ($head ne 'HEAD') {
770 $old_head = eval {
771 command_oneline([qw/symbolic-ref -q HEAD/])
772 };
773 if ($old_head) {
774 $old_head =~ s{^refs/heads/}{};
775 } else {
776 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
777 }
778 command(['checkout', $head], STDERR => 0);
779 }
780
a8ae2623 781 my @refs;
5eec27e3 782 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
2cb61105
TR
783 unless ($gs) {
784 die "Unable to determine upstream SVN information from ",
785 "$head history.\nPerhaps the repository is empty.";
786 }
0df84059
PO
787
788 if (defined $_commit_url) {
789 $url = $_commit_url;
790 } else {
791 $url = eval { command_oneline('config', '--get',
792 "svn-remote.$gs->{repo_id}.commiturl") };
793 if (!$url) {
12a296bc 794 $url = $gs->full_pushurl
0df84059
PO
795 }
796 }
797
ba24e745 798 my $last_rev = $_revision if defined $_revision;
59b0c24d
MM
799 if ($url) {
800 print "Committing to $url ...\n";
801 }
733a65aa 802 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
803 if ($_no_rebase && scalar(@$linear_refs) > 1) {
804 warn "Attempting to commit more than one change while ",
805 "--no-rebase is enabled.\n",
806 "If these changes depend on each other, re-running ",
7dfa16b9 807 "without --no-rebase may be required."
751eb395 808 }
afd7f1eb
FH
809
810 if (defined $_interactive){
811 my $ask_default = "y";
812 foreach my $d (@$linear_refs){
813 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
814 while (<$fh>){
815 print $_;
816 }
817 command_close_pipe($fh, $ctx);
818 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
819 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
820 default => $ask_default);
821 die "Commit this patch reply required" unless defined $_;
822 if (/^[nq]/i) {
823 exit(0);
824 } elsif (/^a/i) {
825 last;
826 }
827 }
828 }
829
711521e2 830 my $expect_url = $url;
1e5814f3
BJ
831
832 my $push_merge_info = eval {
833 command_oneline(qw/config --get svn.pushmergeinfo/)
834 };
835 if (not defined($push_merge_info)
836 or $push_merge_info eq "false"
837 or $push_merge_info eq "no"
838 or $push_merge_info eq "never") {
839 $push_merge_info = 0;
840 }
841
842 unless (defined($_merge_info) || ! $push_merge_info) {
843 # Preflight check of changes to ensure no issues with mergeinfo
844 # This includes check for uncommitted-to-SVN parents
845 # (other than the first parent, which we will handle),
846 # information from different SVN repos, and paths
847 # which are not underneath this repository root.
848 my $rooturl = $gs->repos_root;
849 foreach my $d (@$linear_refs) {
850 my %parentshash;
851 read_commit_parents(\%parentshash, $d);
852 my @realparents = @{$parentshash{$d}};
853 if ($#realparents > 0) {
854 # Merge commit
855 shift @realparents; # Remove/ignore first parent
856 foreach my $parent (@realparents) {
857 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
858 unless (defined $paruuid) {
859 # A parent is missing SVN annotations...
860 # abort the whole operation.
861 fatal "$parent is merged into revision $d, "
862 ."but does not have git-svn metadata. "
863 ."Either dcommit the branch or use a "
864 ."local cherry-pick, FF merge, or rebase "
865 ."instead of an explicit merge commit.";
866 }
867
868 unless ($paruuid eq $uuid) {
869 # Parent has SVN metadata from different repository
870 fatal "merge parent $parent for change $d has "
871 ."git-svn uuid $paruuid, while current change "
872 ."has uuid $uuid!";
873 }
874
0e7e30f5 875 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
1e5814f3
BJ
876 # This branch is very strange indeed.
877 fatal "merge parent $parent for $d is on branch "
878 ."$branchurl, which is not under the "
879 ."git-svn root $rooturl!";
880 }
881 }
882 }
883 }
884 }
885
886 my $rewritten_parent;
711521e2 887 Git::SVN::remove_username($expect_url);
98c4ab32
BJ
888 if (defined($_merge_info)) {
889 $_merge_info =~ tr{ }{\n};
890 }
c74d9acf
EW
891 while (1) {
892 my $d = shift @$linear_refs or last;
45bf473a
EW
893 unless (defined $last_rev) {
894 (undef, $last_rev, undef) = cmt_metadata("$d~1");
895 unless (defined $last_rev) {
d7ad3bed 896 fatal "Unable to extract revision information ",
207f1a75 897 "from commit $d~1";
45bf473a
EW
898 }
899 }
b22d4497
EW
900 if ($_dry_run) {
901 print "diff-tree $d~1 $d\n";
902 } else {
751eb395 903 my $cmt_rev;
1e5814f3
BJ
904
905 unless (defined($_merge_info) || ! $push_merge_info) {
906 $_merge_info = populate_merge_info($d, $gs,
907 $uuid,
908 $linear_refs,
909 $rewritten_parent);
910 }
911
d7ad3bed 912 my %ed_opts = ( r => $last_rev,
61395354 913 log => get_commit_entry($d)->{log},
ba24e745 914 ra => Git::SVN::Ra->new($url),
3caf320b
KA
915 config => SVN::Core::config_get_config(
916 $Git::SVN::Ra::config_dir
917 ),
61395354
EW
918 tree_a => "$d~1",
919 tree_b => $d,
920 editor_cb => sub {
921 print "Committed r$_[0]\n";
751eb395
EW
922 $cmt_rev = $_[0];
923 },
6abd9332 924 mergeinfo => $_merge_info,
a8ae2623 925 svn_path => '');
61395354 926 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 927 print "No changes\n$d~1 == $d\n";
733a65aa 928 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 929 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 930 $parents->{$d};
d7ad3bed 931 }
751eb395 932 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 933 $last_rev = $cmt_rev;
751eb395
EW
934 next if $_no_rebase;
935
936 # we always want to rebase against the current HEAD,
937 # not any head that was passed to us
c74d9acf 938 my @diff = command('diff-tree', $d,
751eb395
EW
939 $gs->refname, '--');
940 my @finish;
941 if (@diff) {
942 @finish = rebase_cmd();
c74d9acf 943 print STDERR "W: $d and ", $gs->refname,
751eb395 944 " differ, using @finish:\n",
c74d9acf 945 join("\n", @diff), "\n";
751eb395
EW
946 } else {
947 print "No changes between current HEAD and ",
948 $gs->refname,
949 "\nResetting to the latest ",
950 $gs->refname, "\n";
951 @finish = qw/reset --mixed/;
952 }
953 command_noisy(@finish, $gs->refname);
1e5814f3
BJ
954
955 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
956
c74d9acf
EW
957 if (@diff) {
958 @refs = ();
959 my ($url_, $rev_, $uuid_, $gs_) =
5eec27e3 960 working_head_info('HEAD', \@refs);
c74d9acf
EW
961 my ($linear_refs_, $parents_) =
962 linearize_history($gs_, \@refs);
963 if (scalar(@$linear_refs) !=
964 scalar(@$linear_refs_)) {
965 fatal "# of revisions changed ",
966 "\nbefore:\n",
967 join("\n", @$linear_refs),
968 "\n\nafter:\n",
969 join("\n", @$linear_refs_), "\n",
970 'If you are attempting to commit ',
971 "merges, try running:\n\t",
972 'git rebase --interactive',
973 '--preserve-merges ',
974 $gs->refname,
975 "\nBefore dcommitting";
976 }
711521e2 977 if ($url_ ne $expect_url) {
c03c1f79
AG
978 if ($url_ eq $gs->metadata_url) {
979 print
980 "Accepting rewritten URL:",
981 " $url_\n";
982 } else {
983 fatal
984 "URL mismatch after rebase:",
985 " $url_ != $expect_url";
986 }
c74d9acf
EW
987 }
988 if ($uuid_ ne $uuid) {
989 fatal "uuid mismatch after rebase: ",
990 "$uuid_ != $uuid";
991 }
992 # remap parents
993 my (%p, @l, $i);
994 for ($i = 0; $i < scalar @$linear_refs; $i++) {
995 my $new = $linear_refs_->[$i] or next;
996 $p{$new} =
997 $parents->{$linear_refs->[$i]};
998 push @l, $new;
999 }
1000 $parents = \%p;
1001 $linear_refs = \@l;
1002 }
b22d4497
EW
1003 }
1004 }
5eec27e3
TR
1005
1006 if ($old_head) {
1007 my $new_head = command_oneline(qw/rev-parse HEAD/);
1008 my $new_is_symbolic = eval {
1009 command_oneline(qw/symbolic-ref -q HEAD/);
1010 };
1011 if ($new_is_symbolic) {
1012 print "dcommitted the branch ", $head, "\n";
1013 } else {
1014 print "dcommitted on a detached HEAD because you gave ",
1015 "a revision argument.\n",
1016 "The rewritten commit is: ", $new_head, "\n";
1017 }
1018 command(['checkout', $old_head], STDERR => 0);
1019 }
1020
3157dd9e 1021 unlink $gs->{index};
b22d4497
EW
1022}
1023
5de70efb
FR
1024sub cmd_branch {
1025 my ($branch_name, $head) = @_;
1026
1027 unless (defined $branch_name && length $branch_name) {
1028 die(($_tag ? "tag" : "branch") . " name required\n");
1029 }
1030 $head ||= 'HEAD';
1031
150d38c4 1032 my (undef, $rev, undef, $gs) = working_head_info($head);
12a296bc 1033 my $src = $gs->full_pushurl;
5de70efb 1034
a0fbc87c 1035 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
62244069
MB
1036 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1037 my $glob;
1038 if ($#{$allglobs} == 0) {
1039 $glob = $allglobs->[0];
1040 } else {
1041 unless(defined $_branch_dest) {
1042 die "Multiple ",
1043 $_tag ? "tag" : "branch",
1044 " paths defined for Subversion repository.\n",
1045 "You must specify where you want to create the ",
1046 $_tag ? "tag" : "branch",
1047 " with the --destination argument.\n";
1048 }
1049 foreach my $g (@{$allglobs}) {
f7050599
EW
1050 # SVN::Git::Editor could probably be moved to Git.pm..
1051 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
1052 if ($_branch_dest =~ /$re/) {
62244069
MB
1053 $glob = $g;
1054 last;
1055 }
1056 }
1057 unless (defined $glob) {
eaa14ff8
EW
1058 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1059 foreach my $g (@{$allglobs}) {
1060 $g->{path}->{left} =~ /$dest_re/ or next;
1061 if (defined $glob) {
1062 die "Ambiguous destination: ",
1063 $_branch_dest, "\nmatches both '",
1064 $glob->{path}->{left}, "' and '",
1065 $g->{path}->{left}, "'\n";
1066 }
1067 $glob = $g;
1068 }
1069 unless (defined $glob) {
1070 die "Unknown ",
1071 $_tag ? "tag" : "branch",
1072 " destination $_branch_dest\n";
1073 }
62244069
MB
1074 }
1075 }
5de70efb 1076 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
99bacd6c
IM
1077 my $url;
1078 if (defined $_commit_url) {
1079 $url = $_commit_url;
1080 } else {
1081 $url = eval { command_oneline('config', '--get',
1082 "svn-remote.$gs->{repo_id}.commiturl") };
1083 if (!$url) {
12a296bc 1084 $url = $remote->{pushurl} || $remote->{url};
99bacd6c
IM
1085 }
1086 }
1087 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
5de70efb 1088
a83b91e7
IM
1089 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1090 $src=~s/^http:/https:/;
1091 }
1092
d32fad2b 1093 ::_req_svn();
1094
5de70efb
FR
1095 my $ctx = SVN::Client->new(
1096 auth => Git::SVN::Ra::_auth_providers(),
1097 log_msg => sub {
1098 ${ $_[0] } = defined $_message
1099 ? $_message
1100 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1101 . $branch_name;
1102 },
1103 );
1104
1105 eval {
1106 $ctx->ls($dst, 'HEAD', 0);
1107 } and die "branch ${branch_name} already exists\n";
1108
1109 print "Copying ${src} at r${rev} to ${dst}...\n";
1110 $ctx->copy($src, $rev, $dst)
1111 unless $_dry_run;
1112
1113 $gs->fetch_all;
1114}
1115
26e60160 1116sub cmd_find_rev {
ea14e6c5
MAL
1117 my $revision_or_hash = shift or die "SVN or git revision required ",
1118 "as a command-line argument\n";
26e60160
AR
1119 my $result;
1120 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
1121 my $head = shift;
1122 $head ||= 'HEAD';
1123 my @refs;
63c56022 1124 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
b3cb7e45
AR
1125 unless ($gs) {
1126 die "Unable to determine upstream SVN information from ",
1127 "$head history\n";
26e60160 1128 }
b3cb7e45 1129 my $desired_revision = substr($revision_or_hash, 1);
63c56022 1130 $result = $gs->rev_map_get($desired_revision, $uuid);
26e60160
AR
1131 } else {
1132 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1133 $result = $rev;
1134 }
1135 print "$result\n" if $result;
1136}
1137
55f9d7a7
MH
1138sub auto_create_empty_directories {
1139 my ($gs) = @_;
1140 my $var = eval { command_oneline('config', '--get', '--bool',
1141 "svn-remote.$gs->{repo_id}.automkdirs") };
1142 # By default, create empty directories by consulting the unhandled log,
1143 # but allow setting it to 'false' to skip it.
1144 return !($var && $var eq 'false');
1145}
1146
905f8b7d
EW
1147sub cmd_rebase {
1148 command_noisy(qw/update-index --refresh/);
13c823fb
EW
1149 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1150 unless ($gs) {
905f8b7d
EW
1151 die "Unable to determine upstream SVN information from ",
1152 "working tree history\n";
1153 }
7d45e146
SF
1154 if ($_dry_run) {
1155 print "Remote Branch: " . $gs->refname . "\n";
1156 print "SVN URL: " . $url . "\n";
1157 return;
1158 }
905f8b7d
EW
1159 if (command(qw/diff-index HEAD --/)) {
1160 print STDERR "Cannot rebase with uncommited changes:\n";
1161 command_noisy('status');
1162 exit 1;
1163 }
dee41f3e 1164 unless ($_local) {
cec0d5a3
SG
1165 # rebase will checkout for us, so no need to do it explicitly
1166 $_no_checkout = 'true';
dee41f3e
EW
1167 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1168 }
905f8b7d 1169 command_noisy(rebase_cmd(), $gs->refname);
55f9d7a7
MH
1170 if (auto_create_empty_directories($gs)) {
1171 $gs->mkemptydirs;
1172 }
905f8b7d
EW
1173}
1174
5969cbe1 1175sub cmd_show_ignore {
13c823fb
EW
1176 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1177 $gs ||= Git::SVN->new;
5969cbe1 1178 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
01bdab84
BS
1179 $gs->prop_walk($gs->{path}, $r, sub {
1180 my ($gs, $path, $props) = @_;
1181 print STDOUT "\n# $path\n";
1182 my $s = $props->{'svn:ignore'} or return;
1183 $s =~ s/[\r\n]+/\n/g;
a7d72544 1184 $s =~ s/^\n+//;
01bdab84
BS
1185 chomp $s;
1186 $s =~ s#^#$path#gm;
1187 print STDOUT "$s\n";
1188 });
a5e0cedc
EW
1189}
1190
2d879792
VK
1191sub cmd_show_externals {
1192 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1193 $gs ||= Git::SVN->new;
1194 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1195 $gs->prop_walk($gs->{path}, $r, sub {
1196 my ($gs, $path, $props) = @_;
1197 print STDOUT "\n# $path\n";
1198 my $s = $props->{'svn:externals'} or return;
1199 $s =~ s/[\r\n]+/\n/g;
1200 chomp $s;
1201 $s =~ s#^#$path#gm;
1202 print STDOUT "$s\n";
1203 });
1204}
1205
d05ddec5
BS
1206sub cmd_create_ignore {
1207 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1208 $gs ||= Git::SVN->new;
1209 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1210 $gs->prop_walk($gs->{path}, $r, sub {
1211 my ($gs, $path, $props) = @_;
1212 # $path is of the form /path/to/dir/
7d9fd459
BG
1213 $path = '.' . $path;
1214 # SVN can have attributes on empty directories,
1215 # which git won't track
1216 mkpath([$path]) unless -d $path;
1217 my $ignore = $path . '.gitignore';
d05ddec5
BS
1218 my $s = $props->{'svn:ignore'} or return;
1219 open(GITIGNORE, '>', $ignore)
207f1a75 1220 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5 1221 $s =~ s/[\r\n]+/\n/g;
a7d72544 1222 $s =~ s/^\n+//;
d05ddec5
BS
1223 chomp $s;
1224 # Prefix all patterns so that the ignore doesn't apply
1225 # to sub-directories.
1226 $s =~ s#^#/#gm;
1227 print GITIGNORE "$s\n";
1228 close(GITIGNORE)
207f1a75 1229 or fatal("Failed to close `$ignore': $!");
c4c66b26 1230 command_noisy('add', '-f', $ignore);
d05ddec5
BS
1231 });
1232}
1233
6111b934
EW
1234sub cmd_mkdirs {
1235 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1236 $gs ||= Git::SVN->new;
1237 $gs->mkemptydirs($_revision);
1238}
1239
b2b3ada7
DK
1240sub canonicalize_path {
1241 my ($path) = @_;
e6fefa92
DK
1242 my $dot_slash_added = 0;
1243 if (substr($path, 0, 1) ne "/") {
1244 $path = "./" . $path;
1245 $dot_slash_added = 1;
1246 }
b2b3ada7
DK
1247 # File::Spec->canonpath doesn't collapse x/../y into y (for a
1248 # good reason), so let's do this manually.
1249 $path =~ s#/+#/#g;
1250 $path =~ s#/\.(?:/|$)#/#g;
1251 $path =~ s#/[^/]+/\.\.##g;
1252 $path =~ s#/$##g;
e6fefa92 1253 $path =~ s#^\./## if $dot_slash_added;
2fe403e7
GP
1254 $path =~ s#^/##;
1255 $path =~ s#^\.$##;
b2b3ada7
DK
1256 return $path;
1257}
1258
50ff2366
UD
1259sub canonicalize_url {
1260 my ($url) = @_;
1261 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
1262 return $url;
1263}
1264
15153451
BS
1265# get_svnprops(PATH)
1266# ------------------
51e057cf 1267# Helper for cmd_propget and cmd_proplist below.
15153451
BS
1268sub get_svnprops {
1269 my $path = shift;
1270 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1271 $gs ||= Git::SVN->new;
1272
1273 # prefix THE PATH by the sub-directory from which the user
1274 # invoked us.
1275 $path = $cmd_dir_prefix . $path;
207f1a75 1276 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
1277 my $is_dir = -d $path ? 1 : 0;
1278 $path = $gs->{path} . '/' . $path;
1279
1280 # canonicalize the path (otherwise libsvn will abort or fail to
1281 # find the file)
b2b3ada7 1282 $path = canonicalize_path($path);
15153451
BS
1283
1284 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1285 my $props;
1286 if ($is_dir) {
1287 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1288 }
1289 else {
1290 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1291 }
1292 return $props;
1293}
1294
1295# cmd_propget (PROP, PATH)
1296# ------------------------
1297# Print the SVN property PROP for PATH.
1298sub cmd_propget {
1299 my ($prop, $path) = @_;
1300 $path = '.' if not defined $path;
1301 usage(1) if not defined $prop;
1302 my $props = get_svnprops($path);
1303 if (not defined $props->{$prop}) {
207f1a75 1304 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
1305 }
1306 print $props->{$prop} . "\n";
1307}
1308
51e057cf
BS
1309# cmd_proplist (PATH)
1310# -------------------
1311# Print the list of SVN properties for PATH.
1312sub cmd_proplist {
1313 my $path = shift;
1314 $path = '.' if not defined $path;
1315 my $props = get_svnprops($path);
1316 print "Properties on '$path':\n";
1317 foreach (sort keys %{$props}) {
1318 print " $_\n";
1319 }
1320}
1321
8164b652 1322sub cmd_multi_init {
9d55b41a 1323 my $url = shift;
62244069 1324 unless (defined $_trunk || @_branches || @_tags) {
98327e58 1325 usage(1);
9d55b41a 1326 }
dc431666 1327
8164b652 1328 $_prefix = '' unless defined $_prefix;
dadc6d2a 1329 if (defined $url) {
50ff2366 1330 $url = canonicalize_url($url);
dadc6d2a
EW
1331 init_subdir(@_);
1332 }
f30603fc 1333 do_git_init_db();
98327e58 1334 if (defined $_trunk) {
b4b33600 1335 $_trunk =~ s#^/+##;
6f5748e1 1336 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
706587fc
EW
1337 # try both old-style and new-style lookups:
1338 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 1339 unless ($gs_trunk) {
706587fc
EW
1340 my ($trunk_url, $trunk_path) =
1341 complete_svn_url($url, $_trunk);
1342 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1343 undef, $trunk_ref);
98327e58 1344 }
c35b96e7 1345 }
62244069 1346 return unless @_branches || @_tags;
e7db67e6 1347 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
62244069
MB
1348 foreach my $path (@_branches) {
1349 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1350 }
1351 foreach my $path (@_tags) {
1352 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1353 }
9d55b41a
EW
1354}
1355
1c8443b0 1356sub cmd_multi_fetch {
4d0157d6 1357 $Git::SVN::no_reuse_existing = undef;
0af9c9f9
EW
1358 my $remotes = Git::SVN::read_all_remotes();
1359 foreach my $repo_id (sort keys %$remotes) {
db03cd24 1360 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
1361 Git::SVN::fetch_all($repo_id, $remotes);
1362 }
9d55b41a 1363 }
9d55b41a
EW
1364}
1365
44320b9e
EW
1366# this command is special because it requires no metadata
1367sub cmd_commit_diff {
1368 my ($ta, $tb, $url) = @_;
1369 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 1370 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 1371 fatal($usage) if (!defined $ta || !defined $tb);
d72ab8c8 1372 my $svn_path = '';
44320b9e
EW
1373 if (!defined $url) {
1374 my $gs = eval { Git::SVN->new };
1375 if (!$gs) {
1376 fatal("Needed URL or usable git-svn --id in ",
1377 "the command-line\n", $usage);
1378 }
1379 $url = $gs->{url};
d3a840dc 1380 $svn_path = $gs->{path};
44320b9e
EW
1381 }
1382 unless (defined $_revision) {
1383 fatal("-r|--revision is a required argument\n", $usage);
1384 }
1385 if (defined $_message && defined $_file) {
1386 fatal("Both --message/-m and --file/-F specified ",
1387 "for the commit message.\n",
207f1a75 1388 "I have no idea what you mean");
44320b9e
EW
1389 }
1390 if (defined $_file) {
1391 $_message = file_to_s($_file);
1392 } else {
1393 $_message ||= get_commit_entry($tb)->{log};
1394 }
1395 my $ra ||= Git::SVN::Ra->new($url);
1396 my $r = $_revision;
1397 if ($r eq 'HEAD') {
1398 $r = $ra->get_latest_revnum;
1399 } elsif ($r !~ /^\d+$/) {
1400 die "revision argument: $r not understood by git-svn\n";
1401 }
61395354
EW
1402 my %ed_opts = ( r => $r,
1403 log => $_message,
1404 ra => $ra,
1405 tree_a => $ta,
1406 tree_b => $tb,
1407 editor_cb => sub { print "Committed r$_[0]\n" },
1408 svn_path => $svn_path );
1409 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
1410 print "No changes\n$ta == $tb\n";
1411 }
44320b9e
EW
1412}
1413
05427b91
TR
1414sub escape_uri_only {
1415 my ($uri) = @_;
1416 my @tmp;
1417 foreach (split m{/}, $uri) {
6a004d3f 1418 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
05427b91
TR
1419 push @tmp, $_;
1420 }
1421 join('/', @tmp);
1422}
1423
1424sub escape_url {
1425 my ($url) = @_;
1426 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1427 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1428 $url = "$scheme://$domain$uri";
1429 }
1430 $url;
1431}
1432
e6fefa92 1433sub cmd_info {
bd2d4f96 1434 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
edde9112 1435 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
bd2d4f96 1436 if (exists $_[1]) {
e6fefa92
DK
1437 die "Too many arguments specified\n";
1438 }
1439
1440 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1441
1442 if (!$file_type && !$diff_status) {
2cf3e3ac
TR
1443 print STDERR "svn: '$path' is not under version control\n";
1444 exit 1;
e6fefa92
DK
1445 }
1446
1447 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1448 unless ($gs) {
1449 die "Unable to determine upstream SVN information from ",
1450 "working tree history\n";
1451 }
bd2d4f96
EW
1452
1453 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1454 $path = "." if $path eq "";
1455
edde9112 1456 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
e6fefa92 1457
8b014d71 1458 if ($_url) {
05427b91 1459 print escape_url($full_url), "\n";
8b014d71
DK
1460 return;
1461 }
1462
e6fefa92
DK
1463 my $result = "Path: $path\n";
1464 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
05427b91 1465 $result .= "URL: " . escape_url($full_url) . "\n";
e6fefa92 1466
a5460eb7
EW
1467 eval {
1468 my $repos_root = $gs->repos_root;
1469 Git::SVN::remove_username($repos_root);
05427b91 1470 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
a5460eb7
EW
1471 };
1472 if ($@) {
1473 $result .= "Repository Root: (offline)\n";
1474 }
b91a8a3e 1475 ::_req_svn();
22ba47f5
MK
1476 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1477 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
e6fefa92
DK
1478 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1479
1480 $result .= "Node Kind: " .
1481 ($file_type eq "dir" ? "directory" : "file") . "\n";
1482
1483 my $schedule = $diff_status eq "A"
1484 ? "add"
1485 : ($diff_status eq "D" ? "delete" : "normal");
1486 $result .= "Schedule: $schedule\n";
1487
1488 if ($diff_status eq "A") {
1489 print $result, "\n";
1490 return;
1491 }
1492
1493 my ($lc_author, $lc_rev, $lc_date_utc);
edde9112 1494 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
e6fefa92
DK
1495 my $log = command_output_pipe(@args);
1496 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1497 while (<$log>) {
1498 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1499 $lc_author = $1;
1500 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1501 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1502 (undef, $lc_rev, undef) = ::extract_metadata($1);
1503 }
1504 }
1505 close $log;
1506
1507 Git::SVN::Log::set_local_timezone();
1508
1509 $result .= "Last Changed Author: $lc_author\n";
1510 $result .= "Last Changed Rev: $lc_rev\n";
1511 $result .= "Last Changed Date: " .
1512 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1513
1514 if ($file_type ne "dir") {
1515 my $text_last_updated_date =
1516 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1517 $result .=
1518 "Text Last Updated: " .
1519 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1520 "\n";
1521 my $checksum;
1522 if ($diff_status eq "D") {
1523 my ($fh, $ctx) =
1524 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1525 if ($file_type eq "link") {
1526 my $file_name = <$fh>;
8d7c4fad 1527 $checksum = md5sum("link $file_name");
e6fefa92 1528 } else {
8d7c4fad 1529 $checksum = md5sum($fh);
e6fefa92
DK
1530 }
1531 command_close_pipe($fh, $ctx);
1532 } elsif ($file_type eq "link") {
1533 my $file_name =
1534 command(qw(cat-file blob), "HEAD:$path");
1535 $checksum =
8d7c4fad 1536 md5sum("link " . $file_name);
e6fefa92
DK
1537 } else {
1538 open FILE, "<", $path or die $!;
8d7c4fad 1539 $checksum = md5sum(\*FILE);
e6fefa92
DK
1540 close FILE or die $!;
1541 }
1542 $result .= "Checksum: " . $checksum . "\n";
1543 }
1544
1545 print $result, "\n";
1546}
1547
195643f2
BJ
1548sub cmd_reset {
1549 my $target = shift || $_revision or die "SVN revision required\n";
1550 $target = $1 if $target =~ /^r(\d+)$/;
1551 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1552 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1553 unless ($gs) {
1554 die "Unable to determine upstream SVN information from ".
1555 "history\n";
1556 }
1557 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
70ee0b77 1558 die "Cannot find SVN revision $target\n" unless defined($c);
195643f2
BJ
1559 $gs->rev_map_set($r, $c, 'reset', $uuid);
1560 print "r$r = $c ($gs->{ref_id})\n";
1561}
1562
2da9ee08
RZ
1563sub cmd_gc {
1564 if (!$can_compress) {
1565 warn "Compress::Zlib could not be found; unhandled.log " .
1566 "files will not be compressed.\n";
1567 }
1568 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1569}
1570
3397f9df
EW
1571########################### utility functions #########################
1572
905f8b7d
EW
1573sub rebase_cmd {
1574 my @cmd = qw/rebase/;
1575 push @cmd, '-v' if $_verbose;
1576 push @cmd, qw/--merge/ if $_merge;
1577 push @cmd, "--strategy=$_strategy" if $_strategy;
1578 @cmd;
1579}
1580
1e889ef3
EW
1581sub post_fetch_checkout {
1582 return if $_no_checkout;
1583 my $gs = $Git::SVN::_head or return;
1584 return if verify_ref('refs/heads/master^0');
1585
b186a261
EW
1586 # look for "trunk" ref if it exists
1587 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1588 my $fetch = $remote->{fetch};
1589 if ($fetch) {
1590 foreach my $p (keys %$fetch) {
1591 basename($fetch->{$p}) eq 'trunk' or next;
1592 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1593 last;
1594 }
1595 }
1596
1e889ef3
EW
1597 my $valid_head = verify_ref('HEAD^0');
1598 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1599 return if ($valid_head || !verify_ref('HEAD^0'));
1600
1601 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1602 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1603 return if -f $index;
1604
7ae3df8c 1605 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
1606 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1607 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1608 print STDERR "Checked out HEAD:\n ",
1609 $gs->full_url, " r", $gs->last_rev, "\n";
55f9d7a7
MH
1610 if (auto_create_empty_directories($gs)) {
1611 $gs->mkemptydirs($gs->last_rev);
1612 }
1e889ef3
EW
1613}
1614
98327e58
EW
1615sub complete_svn_url {
1616 my ($url, $path) = @_;
1617 $path =~ s#/+$##;
98327e58 1618 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
1619 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1620 fatal("E: '$path' is not a complete URL ",
207f1a75 1621 "and a separate URL is not specified");
98327e58 1622 }
706587fc 1623 return ($url, $path);
98327e58 1624 }
706587fc 1625 return ($path, '');
98327e58
EW
1626}
1627
9d55b41a 1628sub complete_url_ls_init {
706587fc
EW
1629 my ($ra, $repo_path, $switch, $pfx) = @_;
1630 unless ($repo_path) {
9d55b41a
EW
1631 print STDERR "W: $switch not specified\n";
1632 return;
1633 }
706587fc
EW
1634 $repo_path =~ s#/+$##;
1635 if ($repo_path =~ m#^[a-z\+]+://#) {
1636 $ra = Git::SVN::Ra->new($repo_path);
1637 $repo_path = '';
e7db67e6 1638 } else {
706587fc 1639 $repo_path =~ s#^/+##;
e7db67e6 1640 unless ($ra) {
706587fc 1641 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 1642 "and a separate URL is not specified");
8164b652 1643 }
e7db67e6 1644 }
706587fc 1645 my $url = $ra->{url};
b4d57e5e
EW
1646 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1647 my $k = "svn-remote.$gs->{repo_id}.url";
1648 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1649 if ($orig_url && ($orig_url ne $gs->{url})) {
1650 die "$k already set: $orig_url\n",
1651 "wanted to set to: $gs->{url}\n";
88cf4107 1652 }
b4d57e5e 1653 command_oneline('config', $k, $gs->{url}) unless $orig_url;
0b2af457 1654 my $remote_path = "$gs->{path}/$repo_path";
5268f9ed 1655 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
b4d57e5e
EW
1656 $remote_path =~ s#/+#/#g;
1657 $remote_path =~ s#^/##g;
ed0b9d43 1658 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
1659 my ($n) = ($switch =~ /^--(\w+)/);
1660 if (length $pfx && $pfx !~ m#/$#) {
1661 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 1662 }
570d35c2 1663 command_noisy('config',
62244069 1664 '--add',
570d35c2
MG
1665 "svn-remote.$gs->{repo_id}.$n",
1666 "$remote_path:refs/remotes/$pfx*" .
1667 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
9d55b41a
EW
1668}
1669
aef4e921
EW
1670sub verify_ref {
1671 my ($ref) = @_;
2c5c1d53
EW
1672 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1673 { STDERR => 0 }); };
aef4e921
EW
1674}
1675
a5e0cedc 1676sub get_tree_from_treeish {
cf52b8f0 1677 my ($treeish) = @_;
44320b9e 1678 # $treeish can be a symbolic ref, too:
aef4e921 1679 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
1680 my $expected;
1681 while ($type eq 'tag') {
aef4e921 1682 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
1683 }
1684 if ($type eq 'commit') {
aef4e921
EW
1685 $expected = (grep /^tree /, command(qw/cat-file commit/,
1686 $treeish))[0];
44320b9e 1687 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
1688 die "Unable to get tree from $treeish\n" unless $expected;
1689 } elsif ($type eq 'tree') {
1690 $expected = $treeish;
1691 } else {
1692 die "$treeish is a $type, expected tree, tag or commit\n";
1693 }
a5e0cedc
EW
1694 return $expected;
1695}
1696
44320b9e
EW
1697sub get_commit_entry {
1698 my ($treeish) = shift;
1699 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1700 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1701 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1702 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1703
44320b9e 1704 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1705 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1706 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1707 $type, $treeish);
3397f9df 1708 my $in_msg = 0;
6aa9ba14
AP
1709 my $author;
1710 my $saw_from = 0;
328eb9b3 1711 my $msgbuf = "";
3397f9df
EW
1712 while (<$msg_fh>) {
1713 if (!$in_msg) {
1714 $in_msg = 1 if (/^\s*$/);
6aa9ba14 1715 $author = $1 if (/^author (.*>)/);
df746c5a 1716 } elsif (/^git-svn-id: /) {
44320b9e
EW
1717 # skip this for now, we regenerate the
1718 # correct one on re-fetch anyways
1719 # TODO: set *:merge properties or like...
3397f9df 1720 } else {
6aa9ba14
AP
1721 if (/^From:/ || /^Signed-off-by:/) {
1722 $saw_from = 1;
1723 }
328eb9b3 1724 $msgbuf .= $_;
3397f9df
EW
1725 }
1726 }
328eb9b3 1727 $msgbuf =~ s/\s+$//s;
6aa9ba14
AP
1728 if ($Git::SVN::_add_author_from && defined($author)
1729 && !$saw_from) {
328eb9b3 1730 $msgbuf .= "\n\nFrom: $author";
6aa9ba14 1731 }
328eb9b3 1732 print $log_fh $msgbuf or croak $!;
aef4e921 1733 command_close_pipe($msg_fh, $ctx);
3397f9df 1734 }
44320b9e 1735 close $log_fh or croak $!;
3397f9df
EW
1736
1737 if ($_edit || ($type eq 'tree')) {
b4479f07
JN
1738 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1739 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
3397f9df 1740 }
44320b9e 1741 rename $commit_editmsg, $commit_msg or croak $!;
16fc08e2 1742 {
b510df8a 1743 require Encode;
16fc08e2
EW
1744 # SVN requires messages to be UTF-8 when entering the repo
1745 local $/;
1746 open $log_fh, '<', $commit_msg or croak $!;
1747 binmode $log_fh;
1748 chomp($log_entry{log} = <$log_fh>);
1749
b510df8a
EW
1750 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1751 my $msg = $log_entry{log};
1752
1753 eval { $msg = Encode::decode($enc, $msg, 1) };
1754 if ($@) {
1755 die "Could not decode as $enc:\n", $msg,
1756 "\nPerhaps you need to set i18n.commitencoding\n";
16fc08e2 1757 }
b510df8a
EW
1758
1759 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1760 die "Could not encode as UTF-8:\n$msg\n" if $@;
1761
1762 $log_entry{log} = $msg;
1763
16fc08e2
EW
1764 close $log_fh or croak $!;
1765 }
44320b9e
EW
1766 unlink $commit_msg;
1767 \%log_entry;
a5e0cedc
EW
1768}
1769
3397f9df
EW
1770sub s_to_file {
1771 my ($str, $file, $mode) = @_;
1772 open my $fd,'>',$file or croak $!;
1773 print $fd $str,"\n" or croak $!;
1774 close $fd or croak $!;
1775 chmod ($mode &~ umask, $file) if (defined $mode);
1776}
1777
1778sub file_to_s {
1779 my $file = shift;
1780 open my $fd,'<',$file or croak "$!: file: $file\n";
1781 local $/;
1782 my $ret = <$fd>;
1783 close $fd or croak $!;
1784 $ret =~ s/\s*$//s;
1785 return $ret;
1786}
1787
eeb0abe0
EW
1788# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1789sub load_authors {
1790 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1791 my $log = $cmd eq 'log';
eeb0abe0
EW
1792 while (<$authors>) {
1793 chomp;
575d025c 1794 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1795 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1796 if ($log) {
1797 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1798 } else {
1799 $users{$user} = [$name, $email];
1800 }
79bb8d88
EW
1801 }
1802 close $authors or croak $!;
1803}
1804
e0d10e1c 1805# convert GetOpt::Long specs for use by git-config
1a30582b 1806sub read_git_config {
b8c92cad 1807 my $opts = shift;
97ae0911 1808 my @config_only;
b8c92cad 1809 foreach my $o (keys %$opts) {
97ae0911
EW
1810 # if we have mixedCase and a long option-only, then
1811 # it's a config-only variable that we don't need for
1812 # the command-line.
1813 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1814 my $v = $opts->{$o};
97ae0911 1815 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1816 $key =~ s/-//g;
225f1d0c 1817 my $arg = 'git config';
b8c92cad
EW
1818 $arg .= ' --int' if ($o =~ /[:=]i$/);
1819 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1820 if (ref $v eq 'ARRAY') {
1821 chomp(my @tmp = `$arg --get-all svn.$key`);
1822 @$v = @tmp if @tmp;
1823 } else {
1824 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1825 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1826 $$v = $tmp;
1827 }
1828 }
1829 }
97ae0911 1830 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1831}
1832
79bb8d88 1833sub extract_metadata {
c1927a85 1834 my $id = shift or return (undef, undef, undef);
3dfab993 1835 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
b3e95936 1836 \s([a-f\d\-]+)$/ix);
e70dc780 1837 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1838 # some of the original repositories I made had
82e5a82f 1839 # identifiers like this:
b3e95936 1840 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
79bb8d88
EW
1841 }
1842 return ($url, $rev, $uuid);
1843}
1844
c1927a85
EW
1845sub cmt_metadata {
1846 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1847 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1848}
1849
6ea42032
BB
1850sub cmt_sha2rev_batch {
1851 my %s2r;
1852 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1853 my $list = shift;
1854
1855 foreach my $sha (@{$list}) {
1856 my $first = 1;
1857 my $size = 0;
1858 print $out $sha, "\n";
1859
1860 while (my $line = <$in>) {
1861 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1862 last;
1863 } elsif ($first &&
1864 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1865 $first = 0;
1866 $size = $1;
1867 next;
1868 } elsif ($line =~ /^(git-svn-id: )/) {
1869 my (undef, $rev, undef) =
1870 extract_metadata($line);
1871 $s2r{$sha} = $rev;
1872 }
1873
1874 $size -= length($line);
1875 last if ($size == 0);
1876 }
1877 }
1878
1879 command_close_bidi_pipe($pid, $in, $out, $ctx);
1880
1881 return \%s2r;
1882}
1883
905f8b7d
EW
1884sub working_head_info {
1885 my ($head, $refs) = @_;
83cf21f9 1886 my @args = qw/rev-list --first-parent --pretty=medium/;
05b4df31 1887 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1888 my $hash;
40cb8f8f 1889 my %max;
3dfab993
SV
1890 while (<$fh>) {
1891 if ( m{^commit ($::sha1)$} ) {
1892 unshift @$refs, $hash if $hash and $refs;
1893 $hash = $1;
1894 next;
1895 }
1896 next unless s{^\s*(git-svn-id:)}{$1};
1897 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1898 if (defined $url && defined $rev) {
40cb8f8f 1899 next if $max{$url} and $max{$url} < $rev;
13c823fb 1900 if (my $gs = Git::SVN->find_by_url($url)) {
63c56022 1901 my $c = $gs->rev_map_get($rev, $uuid);
b03c7a63 1902 if ($c && $c eq $hash) {
13c823fb
EW
1903 close $fh; # break the pipe
1904 return ($url, $rev, $uuid, $gs);
40cb8f8f 1905 } else {
060610c5 1906 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1907 }
1908 }
1909 }
905f8b7d 1910 }
13c823fb
EW
1911 command_close_pipe($fh, $ctx);
1912 (undef, undef, undef, undef);
905f8b7d
EW
1913}
1914
733a65aa
EW
1915sub read_commit_parents {
1916 my ($parents, $c) = @_;
7b02b85a
EW
1917 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1918 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1919 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1920}
1921
1922sub linearize_history {
1923 my ($gs, $refs) = @_;
1924 my %parents;
1925 foreach my $c (@$refs) {
1926 read_commit_parents(\%parents, $c);
1927 }
1928
1929 my @linear_refs;
1930 my %skip = ();
1931 my $last_svn_commit = $gs->last_commit;
1932 foreach my $c (reverse @$refs) {
1933 next if $c eq $last_svn_commit;
1934 last if $skip{$c};
1935
1936 unshift @linear_refs, $c;
1937 $skip{$c} = 1;
1938
1939 # we only want the first parent to diff against for linear
1940 # history, we save the rest to inject when we finalize the
1941 # svn commit
1942 my $fp_a = verify_ref("$c~1");
1943 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1944 if (!$fp_a || !$fp_b) {
1945 die "Commit $c\n",
1946 "has no parent commit, and therefore ",
1947 "nothing to diff against.\n",
1948 "You should be working from a repository ",
1949 "originally created by git-svn\n";
1950 }
1951 if ($fp_a ne $fp_b) {
1952 die "$c~1 = $fp_a, however parsing commit $c ",
1953 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1954 }
1955
1956 foreach my $p (@{$parents{$c}}) {
1957 $skip{$p} = 1;
1958 }
1959 }
1960 (\@linear_refs, \%parents);
1961}
1962
e6fefa92
DK
1963sub find_file_type_and_diff_status {
1964 my ($path) = @_;
107cee50 1965 return ('dir', '') if $path eq '';
e6fefa92
DK
1966
1967 my $diff_output =
1968 command_oneline(qw(diff --cached --name-status --), $path) || "";
1969 my $diff_status = (split(' ', $diff_output))[0] || "";
1970
1971 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1972
1973 return (undef, undef) if !$diff_status && !$ls_tree;
1974
1975 if ($diff_status eq "A") {
1976 return ("link", $diff_status) if -l $path;
1977 return ("dir", $diff_status) if -d $path;
1978 return ("file", $diff_status);
1979 }
1980
1981 my $mode = (split(' ', $ls_tree))[0] || "";
1982
1983 return ("link", $diff_status) if $mode eq "120000";
1984 return ("dir", $diff_status) if $mode eq "040000";
1985 return ("file", $diff_status);
1986}
1987
b2b3ada7
DK
1988sub md5sum {
1989 my $arg = shift;
1990 my $ref = ref $arg;
1991 my $md5 = Digest::MD5->new();
0b19138b 1992 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
b2b3ada7
DK
1993 $md5->addfile($arg) or croak $!;
1994 } elsif ($ref eq 'SCALAR') {
1995 $md5->add($$arg) or croak $!;
1996 } elsif (!$ref) {
1997 $md5->add($arg) or croak $!;
1998 } else {
1999 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
2000 }
2001 return $md5->hexdigest();
2002}
2003
2da9ee08
RZ
2004sub gc_directory {
2005 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
2006 my $out_filename = $_ . ".gz";
2007 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2008 binmode $in_fh;
2009 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2010 die "Unable to open $out_filename: $!\n";
2011
2012 my $res;
2013 while ($res = sysread($in_fh, my $str, 1024)) {
2014 $gz->gzwrite($str) or
2015 die "Unable to write: ".$gz->gzerror()."!\n";
2016 }
2017 unlink $_ or die "unlink $File::Find::name: $!\n";
2018 } elsif (-f $_ && basename($_) eq "index") {
2019 unlink $_ or die "unlink $_: $!\n";
2020 }
2021}
2022
9b981fc6
EW
2023package Git::SVN;
2024use strict;
2025use warnings;
060610c5
EW
2026use Fcntl qw/:DEFAULT :seek/;
2027use constant rev_map_fmt => 'NH40';
ecc712dd 2028use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 2029 $_repack $_repack_flags $_use_svm_props $_head
70ae04e4 2030 $_use_svnsync_props $no_reuse_existing $_minimize_url
e82f0d73 2031 $_use_log_author $_add_author_from $_localtime/;
9b981fc6
EW
2032use Carp qw/croak/;
2033use File::Path qw/mkpath/;
373274f9 2034use File::Copy qw/copy/;
9b981fc6 2035use IPC::Open3;
6aa17fc6 2036use Time::Local;
7d944c33 2037use Memoize; # core since 5.8.0, Jul 2002
8bff7c53 2038use Memoize::Storable;
037a98cd 2039use POSIX qw(:signal_h);
9b981fc6 2040
94bc914c
KW
2041my ($_gc_nr, $_gc_period);
2042
9b981fc6
EW
2043# properties that we do not log:
2044my %SKIP_PROP;
2045BEGIN {
2046 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
2047 svn:special svn:executable
2048 svn:entry:committed-rev
2049 svn:entry:last-author
2050 svn:entry:uuid
2051 svn:entry:committed-date/;
91b03282
EW
2052
2053 # some options are read globally, but can be overridden locally
2054 # per [svn-remote "..."] section. Command-line options will *NOT*
2055 # override options set in an [svn-remote "..."] section
c5f71ad0
SV
2056 no strict 'refs';
2057 for my $option (qw/follow_parent no_metadata use_svm_props
2058 use_svnsync_props/) {
2059 my $key = $option;
91b03282 2060 $key =~ tr/_//d;
c5f71ad0
SV
2061 my $prop = "-$option";
2062 *$option = sub {
2063 my ($self) = @_;
2064 return $self->{$prop} if exists $self->{$prop};
2065 my $k = "svn-remote.$self->{repo_id}.$key";
2066 eval { command_oneline(qw/config --get/, $k) };
2067 if ($@) {
2068 $self->{$prop} = ${"Git::SVN::_$option"};
91b03282 2069 } else {
c5f71ad0
SV
2070 my $v = command_oneline(qw/config --bool/,$k);
2071 $self->{$prop} = $v eq 'false' ? 0 : 1;
91b03282 2072 }
c5f71ad0
SV
2073 return $self->{$prop};
2074 }
91b03282 2075 }
9b981fc6
EW
2076}
2077
0b19138b 2078
321b1842
EW
2079my (%LOCKFILES, %INDEX_FILES);
2080END {
2081 unlink keys %LOCKFILES if %LOCKFILES;
2082 unlink keys %INDEX_FILES if %INDEX_FILES;
2083}
373274f9 2084
4bb9ed04
EW
2085sub resolve_local_globs {
2086 my ($url, $fetch, $glob_spec) = @_;
2087 return unless defined $glob_spec;
2088 my $ref = $glob_spec->{ref};
2089 my $path = $glob_spec->{path};
6f5748e1
AB
2090 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
2091 next unless m#^$ref->{regex}$#;
4bb9ed04 2092 my $p = $1;
bf655fd7
RE
2093 my $pathname = desanitize_refname($path->full_path($p));
2094 my $refname = desanitize_refname($ref->full_path($p));
4bb9ed04
EW
2095 if (my $existing = $fetch->{$pathname}) {
2096 if ($existing ne $refname) {
2097 die "Refspec conflict:\n",
6f5748e1
AB
2098 "existing: $existing\n",
2099 " globbed: $refname\n";
4bb9ed04 2100 }
6f5748e1 2101 my $u = (::cmt_metadata("$refname"))[0];
4e9f6cc7 2102 $u =~ s!^\Q$url\E(/|$)!! or die
6f5748e1 2103 "$refname: '$url' not found in '$u'\n";
4bb9ed04
EW
2104 if ($pathname ne $u) {
2105 warn "W: Refspec glob conflict ",
6f5748e1 2106 "(ref: $refname):\n",
4bb9ed04
EW
2107 "expected path: $pathname\n",
2108 " real path: $u\n",
2109 "Continuing ahead with $u\n";
2110 next;
2111 }
2112 } else {
4bb9ed04
EW
2113 $fetch->{$pathname} = $refname;
2114 }
2115 }
2116}
2117
e98671e5
EW
2118sub parse_revision_argument {
2119 my ($base, $head) = @_;
2120 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
2121 return ($base, $head);
2122 }
2123 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
2124 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
2125 return ($head, $head) if ($::_revision eq 'HEAD');
2126 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
2127 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
2128 die "revision argument: $::_revision not understood by git-svn\n";
2129}
2130
0af9c9f9 2131sub fetch_all {
4bb9ed04 2132 my ($repo_id, $remotes) = @_;
905f8b7d
EW
2133 if (ref $repo_id) {
2134 my $gs = $repo_id;
2135 $repo_id = undef;
2136 $repo_id = $gs->{repo_id};
2137 }
2138 $remotes ||= read_all_remotes();
7447b4bc
EW
2139 my $remote = $remotes->{$repo_id} or
2140 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 2141 my $fetch = $remote->{fetch};
7447b4bc 2142 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 2143 my (@gs, @globs);
0af9c9f9 2144 my $ra = Git::SVN::Ra->new($url);
26a62d57 2145 my $uuid = $ra->get_uuid;
0af9c9f9 2146 my $head = $ra->get_latest_revnum;
577e9fca
EW
2147
2148 # ignore errors, $head revision may not even exist anymore
2149 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
2150 warn "W: $@\n" if $@;
2151
28710f74 2152 my $base = defined $fetch ? $head : 0;
e518192f
EW
2153
2154 # read the max revs for wildcard expansion (branches/*, tags/*)
2155 foreach my $t (qw/branches tags/) {
2156 defined $remote->{$t} or next;
62244069
MB
2157 push @globs, @{$remote->{$t}};
2158
93f2689c
EW
2159 my $max_rev = eval { tmp_config(qw/--int --get/,
2160 "svn-remote.$repo_id.${t}-maxRev") };
2161 if (defined $max_rev && ($max_rev < $base)) {
2162 $base = $max_rev;
d6d3346b
EW
2163 } elsif (!defined $max_rev) {
2164 $base = 0;
e518192f
EW
2165 }
2166 }
2167
db03cd24
EW
2168 if ($fetch) {
2169 foreach my $p (sort keys %$fetch) {
2170 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
060610c5 2171 my $lr = $gs->rev_map_max;
db03cd24
EW
2172 if (defined $lr) {
2173 $base = $lr if ($lr < $base);
2174 }
2175 push @gs, $gs;
0af9c9f9 2176 }
0af9c9f9 2177 }
e98671e5
EW
2178
2179 ($base, $head) = parse_revision_argument($base, $head);
e518192f 2180 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
2181}
2182
47e39c55
EW
2183sub read_all_remotes {
2184 my $r = {};
63c56022
JA
2185 my $use_svm_props = eval { command_oneline(qw/config --bool
2186 svn.useSvmProps/) };
2187 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
ffd5c8e4 2188 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
8b8fc068 2189 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
6f5748e1
AB
2190 if (m!^(.+)\.fetch=$svn_refspec$!) {
2191 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
2192 die("svn-remote.$remote: remote ref '$remote_ref' "
2193 . "must start with 'refs/'\n")
2194 unless $remote_ref =~ m{^refs/};
46cb16fb 2195 $local_ref = uri_decode($local_ref);
46cf98ba 2196 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
63c56022
JA
2197 $r->{$remote}->{svm} = {} if $use_svm_props;
2198 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
2199 $r->{$1}->{svm} = {};
47e39c55
EW
2200 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
2201 $r->{$1}->{url} = $2;
12a296bc
AS
2202 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
2203 $r->{$1}->{pushurl} = $2;
cdb51a13
MO
2204 } elsif (m!^(.+)\.ignore-refs=\s*(.*)\s*$!) {
2205 $r->{$1}->{ignore_refs_regex} = $2;
6f5748e1
AB
2206 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
2207 my ($remote, $t, $local_ref, $remote_ref) =
2208 ($1, $2, $3, $4);
2209 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
2210 . "must start with 'refs/'\n")
2211 unless $remote_ref =~ m{^refs/};
46cb16fb 2212 $local_ref = uri_decode($local_ref);
62244069 2213 my $rs = {
6f5748e1
AB
2214 t => $t,
2215 remote => $remote,
07576208
JS
2216 path => Git::SVN::GlobSpec->new($local_ref, 1),
2217 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
4bb9ed04
EW
2218 if (length($rs->{ref}->{right}) != 0) {
2219 die "The '*' glob character must be the last ",
6f5748e1 2220 "character of '$remote_ref'\n";
4bb9ed04 2221 }
6f5748e1 2222 push @{ $r->{$remote}->{$t} }, $rs;
47e39c55
EW
2223 }
2224 }
63c56022
JA
2225
2226 map {
2227 if (defined $r->{$_}->{svm}) {
2228 my $svm;
2229 eval {
2230 my $section = "svn-remote.$_";
2231 $svm = {
2232 source => tmp_config('--get',
2233 "$section.svm-source"),
2234 replace => tmp_config('--get',
2235 "$section.svm-replace"),
2236 }
2237 };
2238 $r->{$_}->{svm} = $svm;
2239 }
2240 } keys %$r;
2241
cdb51a13
MO
2242 foreach my $remote (keys %$r) {
2243 foreach ( grep { defined $_ }
2244 map { $r->{$remote}->{$_} } qw(branches tags) ) {
2245 foreach my $rs ( @$_ ) {
2246 $rs->{ignore_refs_regex} =
2247 $r->{$remote}->{ignore_refs_regex};
2248 }
2249 }
2250 }
2251
47e39c55
EW
2252 $r;
2253}
2254
ecc712dd 2255sub init_vars {
94bc914c 2256 $_gc_nr = $_gc_period = 1000;
af788a6e
KW
2257 if (defined $_repack || defined $_repack_flags) {
2258 warn "Repack options are obsolete; they have no effect.\n";
2259 }
ecc712dd
EW
2260}
2261
b805b44a 2262sub verify_remotes_sanity {
536c4b09 2263 return unless -d $ENV{GIT_DIR};
b805b44a
EW
2264 my %seen;
2265 foreach (command(qw/config -l/)) {
2266 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
2267 if ($seen{$1}) {
2268 die "Remote ref refs/remote/$1 is tracked by",
2269 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
2270 "Please resolve this ambiguity in ",
2271 "your git configuration file before ",
2272 "continuing\n";
2273 }
2274 $seen{$1} = $_;
2275 }
2276 }
2277}
2278
e6434f87
EW
2279sub find_existing_remote {
2280 my ($url, $remotes) = @_;
befc9adc 2281 return undef if $no_reuse_existing;
e6434f87
EW
2282 my $existing;
2283 foreach my $repo_id (keys %$remotes) {
2284 my $u = $remotes->{$repo_id}->{url} or next;
2285 next if $u ne $url;
2286 $existing = $repo_id;
2287 last;
2288 }
2289 $existing;
2290}
b805b44a 2291
e6434f87 2292sub init_remote_config {
d8115c51 2293 my ($self, $url, $no_write) = @_;
e6434f87
EW
2294 $url =~ s!/+$!!; # strip trailing slash
2295 my $r = read_all_remotes();
2296 my $existing = find_existing_remote($url, $r);
2297 if ($existing) {
e518192f
EW
2298 unless ($no_write) {
2299 print STDERR "Using existing ",
2300 "[svn-remote \"$existing\"]\n";
2301 }
e6434f87 2302 $self->{repo_id} = $existing;
4a1bb4c3 2303 } elsif ($_minimize_url) {
e6434f87
EW
2304 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
2305 $existing = find_existing_remote($min_url, $r);
2306 if ($existing) {
e518192f
EW
2307 unless ($no_write) {
2308 print STDERR "Using existing ",
2309 "[svn-remote \"$existing\"]\n";
2310 }
e6434f87
EW
2311 $self->{repo_id} = $existing;
2312 }
2313 if ($min_url ne $url) {
e518192f
EW
2314 unless ($no_write) {
2315 print STDERR "Using higher level of URL: ",
2316 "$url => $min_url\n";
2317 }
e6434f87
EW
2318 my $old_path = $self->{path};
2319 $self->{path} = $url;
4e9f6cc7 2320 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
2321 if (length $old_path) {
2322 $self->{path} .= "/$old_path";
2323 }
2324 $url = $min_url;
2325 }
2326 }
2327 my $orig_url;
2328 if (!$existing) {
b805b44a 2329 # verify that we aren't overwriting anything:
e6434f87 2330 $orig_url = eval {
706587fc 2331 command_oneline('config', '--get',
e6434f87 2332 "svn-remote.$self->{repo_id}.url")
706587fc 2333 };
b805b44a 2334 if ($orig_url && ($orig_url ne $url)) {
e6434f87 2335 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
2336 "$orig_url\nwanted to set to: $url\n";
2337 }
9b981fc6 2338 }
e6434f87 2339 my ($xrepo_id, $xpath) = find_ref($self->refname);
6f5748e1 2340 if (!$no_write && defined $xpath) {
e6434f87 2341 die "svn-remote.$xrepo_id.fetch already set to track ",
6f5748e1 2342 "$xpath:", $self->refname, "\n";
e6434f87 2343 }
d8115c51
EW
2344 unless ($no_write) {
2345 command_noisy('config',
2346 "svn-remote.$self->{repo_id}.url", $url);
46cf98ba 2347 $self->{path} =~ s{^/}{};
5268f9ed 2348 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
d8115c51
EW
2349 command_noisy('config', '--add',
2350 "svn-remote.$self->{repo_id}.fetch",
2351 "$self->{path}:".$self->refname);
2352 }
9b981fc6 2353 $self->{url} = $url;
e6434f87
EW
2354}
2355
a8ae2623
EW
2356sub find_by_url { # repos_root and, path are optional
2357 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 2358
1a97a506 2359 return undef unless defined $full_url;
56973d20
AR
2360 remove_username($full_url);
2361 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
2362 my $remotes = read_all_remotes();
2363 if (defined $full_url && defined $repos_root && !defined $path) {
2364 $path = $full_url;
2365 $path =~ s#^\Q$repos_root\E(?:/|$)##;
2366 }
2367 foreach my $repo_id (keys %$remotes) {
2368 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 2369 remove_username($u);
a8ae2623
EW
2370 next if defined $repos_root && $repos_root ne $u;
2371
2372 my $fetch = $remotes->{$repo_id}->{fetch} || {};
62244069
MB
2373 foreach my $t (qw/branches tags/) {
2374 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
2375 resolve_local_globs($u, $fetch, $globspec);
2376 }
a8ae2623
EW
2377 }
2378 my $p = $path;
0bb91d9a 2379 my $rwr = rewrite_root({repo_id => $repo_id});
63c56022
JA
2380 my $svm = $remotes->{$repo_id}->{svm}
2381 if defined $remotes->{$repo_id}->{svm};
a8ae2623
EW
2382 unless (defined $p) {
2383 $p = $full_url;
0bb91d9a 2384 my $z = $u;
63c56022 2385 my $prefix = '';
0bb91d9a
JG
2386 if ($rwr) {
2387 $z = $rwr;
1b7e543a 2388 remove_username($z);
63c56022
JA
2389 } elsif (defined $svm) {
2390 $z = $svm->{source};
2391 $prefix = $svm->{replace};
2392 $prefix =~ s#^\Q$u\E(?:/|$)##;
2393 $prefix =~ s#/$##;
0bb91d9a 2394 }
63c56022 2395 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
a8ae2623
EW
2396 }
2397 foreach my $f (keys %$fetch) {
2398 next if $f ne $p;
2399 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2400 }
2401 }
2402 undef;
2403}
2404
e6434f87 2405sub init {
d8115c51 2406 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
2407 my $self = _new($class, $repo_id, $ref_id, $path);
2408 if (defined $url) {
d8115c51 2409 $self->init_remote_config($url, $no_write);
e6434f87 2410 }
9b981fc6
EW
2411 $self;
2412}
2413
706587fc
EW
2414sub find_ref {
2415 my ($ref_id) = @_;
2416 foreach (command(qw/config -l/)) {
2417 next unless m!^svn-remote\.(.+)\.fetch=
ffd5c8e4 2418 \s*(.*?)\s*:\s*(.+?)\s*$!x;
706587fc
EW
2419 my ($repo_id, $path, $ref) = ($1, $2, $3);
2420 if ($ref eq $ref_id) {
2421 $path = '' if ($path =~ m#^\./?#);
2422 return ($repo_id, $path);
2423 }
2424 }
2425 (undef, undef, undef);
2426}
2427
9b981fc6 2428sub new {
706587fc
EW
2429 my ($class, $ref_id, $repo_id, $path) = @_;
2430 if (defined $ref_id && !defined $repo_id && !defined $path) {
2431 ($repo_id, $path) = find_ref($ref_id);
2432 if (!defined $repo_id) {
2433 die "Could not find a \"svn-remote.*.fetch\" key ",
2434 "in the repository configuration matching: ",
6f5748e1 2435 "$ref_id\n";
706587fc
EW
2436 }
2437 }
2438 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
2439 if (!defined $self->{path} || !length $self->{path}) {
2440 my $fetch = command_oneline('config', '--get',
2441 "svn-remote.$repo_id.fetch",
6f5748e1 2442 ":$ref_id\$") or
8b8fc068 2443 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
6f5748e1 2444 "\":$ref_id\$\" in config\n";
8b8fc068
EW
2445 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2446 }
b1a954a3
EW
2447 $self->{path} =~ s{/+}{/}g;
2448 $self->{path} =~ s{\A/}{};
2449 $self->{path} =~ s{/\z}{};
706587fc
EW
2450 $self->{url} = command_oneline('config', '--get',
2451 "svn-remote.$repo_id.url") or
2452 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
12a296bc
AS
2453 $self->{pushurl} = eval { command_oneline('config', '--get',
2454 "svn-remote.$repo_id.pushurl") };
d6d3346b 2455 $self->rebuild;
9b981fc6
EW
2456 $self;
2457}
2458
bf655fd7 2459sub refname {
6f5748e1 2460 my ($refname) = $_[0]->{ref_id} ;
bf655fd7
RE
2461
2462 # It cannot end with a slash /, we'll throw up on this because
2463 # SVN can't have directories with a slash in their name, either:
2464 if ($refname =~ m{/$}) {
2465 die "ref: '$refname' ends with a trailing slash, this is ",
2466 "not permitted by git nor Subversion\n";
2467 }
2468
2469 # It cannot have ASCII control character space, tilde ~, caret ^,
2470 # colon :, question-mark ?, asterisk *, space, or open bracket [
2471 # anywhere.
2472 #
2473 # Additionally, % must be escaped because it is used for escaping
2474 # and we want our escaped refname to be reversible
2475 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2476
2477 # no slash-separated component can begin with a dot .
2478 # /.* becomes /%2E*
2479 $refname =~ s{/\.}{/%2E}g;
2480
2481 # It cannot have two consecutive dots .. anywhere
2482 # .. becomes %2E%2E
2483 $refname =~ s{\.\.}{%2E%2E}g;
2484
73d41955
TS
2485 # trailing dots and .lock are not allowed
2486 # .$ becomes %2E and .lock becomes %2Elock
2487 $refname =~ s{\.(?=$|lock$)}{%2E};
2488
2489 # the sequence @{ is used to access the reflog
2490 # @{ becomes %40{
2491 $refname =~ s{\@\{}{%40\{}g;
2492
bf655fd7
RE
2493 return $refname;
2494}
2495
2496sub desanitize_refname {
2497 my ($refname) = @_;
2498 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2499 return $refname;
2500}
9b981fc6 2501
26a62d57
EW
2502sub svm_uuid {
2503 my ($self) = @_;
2504 return $self->{svm}->{uuid} if $self->svm;
2505 $self->ra;
2506 unless ($self->{svm}) {
2507 die "SVM UUID not cached, and reading remotely failed\n";
2508 }
2509 $self->{svm}->{uuid};
2510}
8a49ee97 2511
26a62d57
EW
2512sub svm {
2513 my ($self) = @_;
2514 return $self->{svm} if $self->{svm};
2515 my $svm;
8a49ee97
EW
2516 # see if we have it in our config, first:
2517 eval {
26a62d57
EW
2518 my $section = "svn-remote.$self->{repo_id}";
2519 $svm = {
93f2689c
EW
2520 source => tmp_config('--get', "$section.svm-source"),
2521 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 2522 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
2523 }
2524 };
befc9adc
EW
2525 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2526 $self->{svm} = $svm;
2527 }
26a62d57
EW
2528 $self->{svm};
2529}
2530
2531sub _set_svm_vars {
2532 my ($self, $ra) = @_;
db03cd24
EW
2533 return $ra if $self->svm;
2534
2535 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 2536 "(svm:source, svm:uuid) ",
db03cd24
EW
2537 "from the following URLs:\n" );
2538 sub read_svm_props {
befc9adc
EW
2539 my ($self, $ra, $path, $r) = @_;
2540 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 2541 my $src = $props->{'svm:source'};
db03cd24 2542 my $uuid = $props->{'svm:uuid'};
befc9adc 2543 return undef if (!$src || !$uuid);
26a62d57 2544
befc9adc 2545 chomp($src, $uuid);
26a62d57 2546
b3e95936 2547 $uuid =~ m{^[0-9a-f\-]{30,}$}i
db03cd24 2548 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
2549
2550 # the '!' is used to mark the repos_root!/relative/path
2551 $src =~ s{/?!/?}{/};
db03cd24 2552 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 2553 # username is of no interest
8a49ee97 2554 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 2555
befc9adc
EW
2556 my $replace = $ra->{url};
2557 $replace .= "/$path" if length $path;
2558
db03cd24 2559 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
2560 tmp_config("$section.svm-source", $src);
2561 tmp_config("$section.svm-replace", $replace);
2562 tmp_config("$section.svm-uuid", $uuid);
2563 $self->{svm} = {
2564 source => $src,
2565 uuid => $uuid,
2566 replace => $replace
2567 };
db03cd24
EW
2568 }
2569
2570 my $r = $ra->get_latest_revnum;
2571 my $path = $self->{path};
befc9adc 2572 my %tried;
db03cd24 2573 while (length $path) {
befc9adc
EW
2574 unless ($tried{"$self->{url}/$path"}) {
2575 return $ra if $self->read_svm_props($ra, $path, $r);
2576 $tried{"$self->{url}/$path"} = 1;
db03cd24 2577 }
befc9adc 2578 $path =~ s#/?[^/]+$##;
8a49ee97 2579 }
befc9adc
EW
2580 die "Path: '$path' should be ''\n" if $path ne '';
2581 return $ra if $self->read_svm_props($ra, $path, $r);
2582 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
2583
2584 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 2585 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
2586 }
2587
2588 # nope, make sure we're connected to the repository root:
2589 my $ok;
2590 my @tried_b;
2591 $path = $ra->{svn_path};
db03cd24
EW
2592 $ra = Git::SVN::Ra->new($ra->{repos_root});
2593 while (length $path) {
befc9adc
EW
2594 unless ($tried{"$ra->{url}/$path"}) {
2595 $ok = $self->read_svm_props($ra, $path, $r);
2596 last if $ok;
2597 $tried{"$ra->{url}/$path"} = 1;
2598 }
2599 $path =~ s#/?[^/]+$##;
db03cd24 2600 }
befc9adc
EW
2601 die "Path: '$path' should be ''\n" if $path ne '';
2602 $ok ||= $self->read_svm_props($ra, $path, $r);
2603 $tried{"$ra->{url}/$path"} = 1;
db03cd24 2604 if (!$ok) {
befc9adc 2605 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
2606 }
2607 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
2608}
2609
62e349d2
EW
2610sub svnsync {
2611 my ($self) = @_;
2612 return $self->{svnsync} if $self->{svnsync};
2613
2614 if ($self->no_metadata) {
2615 die "Can't have both 'noMetadata' and ",
2616 "'useSvnsyncProps' options set!\n";
2617 }
2618 if ($self->rewrite_root) {
2619 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2620 "options set!\n";
2621 }
3e18ce1a
JS
2622 if ($self->rewrite_uuid) {
2623 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2624 "options set!\n";
2625 }
62e349d2
EW
2626
2627 my $svnsync;
2628 # see if we have it in our config, first:
2629 eval {
2630 my $section = "svn-remote.$self->{repo_id}";
98fa5b68
EW
2631
2632 my $url = tmp_config('--get', "$section.svnsync-url");
2633 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2634 die "doesn't look right - svn:sync-from-url is '$url'\n";
2635
2636 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
b3e95936 2637 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
98fa5b68
EW
2638 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2639
2640 $svnsync = { url => $url, uuid => $uuid }
62e349d2
EW
2641 };
2642 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2643 return $self->{svnsync} = $svnsync;
2644 }
2645
2646 my $err = "useSvnsyncProps set, but failed to read " .
2647 "svnsync property: svn:sync-from-";
2648 my $rp = $self->ra->rev_proplist(0);
2649
2650 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
98fa5b68 2651 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
62e349d2
EW
2652 die "doesn't look right - svn:sync-from-url is '$url'\n";
2653
2654 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
b3e95936 2655 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
62e349d2
EW
2656 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2657
2658 my $section = "svn-remote.$self->{repo_id}";
2659 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2660 tmp_config('--add', "$section.svnsync-url", $url);
2661 return $self->{svnsync} = { url => $url, uuid => $uuid };
2662}
2663
26a62d57
EW
2664# this allows us to memoize our SVN::Ra UUID locally and avoid a
2665# remote lookup (useful for 'git svn log').
2666sub ra_uuid {
2667 my ($self) = @_;
2668 unless ($self->{ra_uuid}) {
2669 my $key = "svn-remote.$self->{repo_id}.uuid";
2670 my $uuid = eval { tmp_config('--get', $key) };
b3e95936 2671 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
26a62d57
EW
2672 $self->{ra_uuid} = $uuid;
2673 } else {
2674 die "ra_uuid called without URL\n" unless $self->{url};
2675 $self->{ra_uuid} = $self->ra->get_uuid;
2676 tmp_config('--add', $key, $self->{ra_uuid});
2677 }
2678 }
2679 $self->{ra_uuid};
2680}
2681
a5460eb7
EW
2682sub _set_repos_root {
2683 my ($self, $repos_root) = @_;
2684 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2685 $repos_root ||= $self->ra->{repos_root};
2686 tmp_config($k, $repos_root);
2687 $repos_root;
2688}
2689
2690sub repos_root {
2691 my ($self) = @_;
2692 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2693 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2694}
2695
9b981fc6
EW
2696sub ra {
2697 my ($self) = shift;
8a49ee97 2698 my $ra = Git::SVN::Ra->new($self->{url});
a5460eb7 2699 $self->_set_repos_root($ra->{repos_root});
91b03282
EW
2700 if ($self->use_svm_props && !$self->{svm}) {
2701 if ($self->no_metadata) {
97ae0911
EW
2702 die "Can't have both 'noMetadata' and ",
2703 "'useSvmProps' options set!\n";
62e349d2
EW
2704 } elsif ($self->use_svnsync_props) {
2705 die "Can't have both 'useSvnsyncProps' and ",
2706 "'useSvmProps' options set!\n";
91b03282 2707 }
26a62d57 2708 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
2709 $self->{-want_revprops} = 1;
2710 }
2711 $ra;
9b981fc6
EW
2712}
2713
01bdab84
BS
2714# prop_walk(PATH, REV, SUB)
2715# -------------------------
2716# Recursively traverse PATH at revision REV and invoke SUB for each
2717# directory that contains a SVN property. SUB will be invoked as
2718# follows: &SUB(gs, path, props); where `gs' is this instance of
2719# Git::SVN, `path' the path to the directory where the properties
2720# `props' were found. The `path' will be relative to point of checkout,
2721# that is, if url://repo/trunk is the current Git branch, and that
2722# directory contains a sub-directory `d', SUB will be invoked with `/d/'
2723# as `path' (note the trailing `/').
2724sub prop_walk {
2725 my ($self, $path, $rev, $sub) = @_;
2726
35cda061 2727 $path =~ s#^/##;
01bdab84
BS
2728 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2729 $path =~ s#^/*#/#g;
9b981fc6 2730 my $p = $path;
01bdab84
BS
2731 # Strip the irrelevant part of the path.
2732 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2733 # Ensure the path is terminated by a `/'.
2734 $p =~ s#/*$#/#;
2735
2736 # The properties contain all the internal SVN stuff nobody
2737 # (usually) cares about.
2738 my $interesting_props = 0;
2739 foreach (keys %{$props}) {
2740 # If it doesn't start with `svn:', it must be a
2741 # user-defined property.
2742 ++$interesting_props and next if $_ !~ /^svn:/;
2743 # FIXME: Fragile, if SVN adds new public properties,
2744 # this needs to be updated.
2745 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2746 |eol-style|mime-type
2747 |externals|needs-lock)$/x;
2748 }
2749 &$sub($self, $p, $props) if $interesting_props;
2750
9b981fc6 2751 foreach (sort keys %$dirent) {
0dc03d6a 2752 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
b7166cce 2753 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
9b981fc6
EW
2754 }
2755}
2756
3ebe8df7
EW
2757sub last_rev { ($_[0]->last_rev_commit)[0] }
2758sub last_commit { ($_[0]->last_rev_commit)[1] }
2759
9b981fc6
EW
2760# returns the newest SVN revision number and newest commit SHA1
2761sub last_rev_commit {
2762 my ($self) = @_;
2763 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2764 return ($self->{last_rev}, $self->{last_commit});
2765 }
d2866f9e 2766 my $c = ::verify_ref($self->refname.'^0');
91b03282 2767 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 2768 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
2769 if (defined $rev) {
2770 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2771 return ($rev, $c);
2772 }
2773 }
060610c5
EW
2774 my $map_path = $self->map_path;
2775 unless (-e $map_path) {
26a62d57
EW
2776 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2777 return (undef, undef);
2778 }
66ab84b9 2779 my ($rev, $commit) = $self->rev_map_max(1);
060610c5
EW
2780 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2781 return ($rev, $commit);
9b981fc6
EW
2782}
2783
3ebe8df7
EW
2784sub get_fetch_range {
2785 my ($self, $min, $max) = @_;
2786 $max ||= $self->ra->get_latest_revnum;
060610c5 2787 $min ||= $self->rev_map_max;
3ebe8df7 2788 (++$min, $max);
9b981fc6
EW
2789}
2790
8a49ee97 2791sub tmp_config {
93f2689c 2792 my (@args) = @_;
b7e5348c
EW
2793 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2794 my $config = "$ENV{GIT_DIR}/svn/.metadata";
38570a47 2795 if (! -f $config && -f $old_def_config) {
b7e5348c
EW
2796 rename $old_def_config, $config or
2797 die "Failed rename $old_def_config => $config: $!\n";
2798 }
8a49ee97 2799 my $old_config = $ENV{GIT_CONFIG};
93f2689c 2800 $ENV{GIT_CONFIG} = $config;
8a49ee97 2801 $@ = undef;
b4d57e5e
EW
2802 my @ret = eval {
2803 unless (-f $config) {
2804 mkfile($config);
2805 open my $fh, '>', $config or
2806 die "Can't open $config: $!\n";
2807 print $fh "; This file is used internally by ",
2808 "git-svn\n" or die
2809 "Couldn't write to $config: $!\n";
2810 print $fh "; You should not have to edit it\n" or
2811 die "Couldn't write to $config: $!\n";
2812 close $fh or die "Couldn't close $config: $!\n";
2813 }
2814 command('config', @args);
2815 };
8a49ee97
EW
2816 my $err = $@;
2817 if (defined $old_config) {
2818 $ENV{GIT_CONFIG} = $old_config;
2819 } else {
2820 delete $ENV{GIT_CONFIG};
2821 }
2822 die $err if $err;
2823 wantarray ? @ret : $ret[0];
2824}
2825
9b981fc6
EW
2826sub tmp_index_do {
2827 my ($self, $sub) = @_;
2828 my $old_index = $ENV{GIT_INDEX_FILE};
2829 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 2830 $@ = undef;
b4d57e5e
EW
2831 my @ret = eval {
2832 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2833 mkpath([$dir]) unless -d $dir;
2834 &$sub;
2835 };
8a49ee97
EW
2836 my $err = $@;
2837 if (defined $old_index) {
9b981fc6
EW
2838 $ENV{GIT_INDEX_FILE} = $old_index;
2839 } else {
2840 delete $ENV{GIT_INDEX_FILE};
2841 }
8a49ee97 2842 die $err if $err;
9b981fc6
EW
2843 wantarray ? @ret : $ret[0];
2844}
2845
2846sub assert_index_clean {
2847 my ($self, $treeish) = @_;
2848
2849 $self->tmp_index_do(sub {
2850 command_noisy('read-tree', $treeish) unless -e $self->{index};
2851 my $x = command_oneline('write-tree');
2852 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2853 /^tree ($::sha1)/mo);
e8d120bd
EW
2854 return if $y eq $x;
2855
2856 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2857 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2858 command_noisy('read-tree', $treeish);
9b981fc6
EW
2859 $x = command_oneline('write-tree');
2860 if ($y ne $x) {
2861 ::fatal "trees ($treeish) $y != $x\n",
207f1a75 2862 "Something is seriously wrong...";
9b981fc6
EW
2863 }
2864 });
2865}
2866
2867sub get_commit_parents {
0af9c9f9 2868 my ($self, $log_entry) = @_;
9b981fc6 2869 my (%seen, @ret, @tmp);
0af9c9f9
EW
2870 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2871 if (my $ip = $self->{inject_parents}) {
2872 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2873 push @tmp, $commit;
9b981fc6
EW
2874 }
2875 }
d2866f9e 2876 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
2877 push @tmp, $cur;
2878 }
733a65aa
EW
2879 if (my $ipd = $self->{inject_parents_dcommit}) {
2880 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2881 push @tmp, @$commit;
2882 }
2883 }
44320b9e 2884 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
2885 while (my $p = shift @tmp) {
2886 next if $seen{$p};
2887 $seen{$p} = 1;
2888 push @ret, $p;
9b981fc6
EW
2889 }
2890 @ret;
2891}
2892
aea736cc
EW
2893sub rewrite_root {
2894 my ($self) = @_;
2895 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2896 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2897 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2898 if ($rwr) {
2899 $rwr =~ s#/+$##;
2900 if ($rwr !~ m#^[a-z\+]+://#) {
2901 die "$rwr is not a valid URL (key: $k)\n";
2902 }
2903 }
2904 $self->{-rewrite_root} = $rwr;
2905}
2906
3e18ce1a
JS
2907sub rewrite_uuid {
2908 my ($self) = @_;
2909 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2910 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2911 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2912 if ($rwid) {
2913 $rwid =~ s#/+$##;
2914 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2915 die "$rwid is not a valid UUID (key: $k)\n";
2916 }
2917 }
2918 $self->{-rewrite_uuid} = $rwid;
2919}
2920
aea736cc
EW
2921sub metadata_url {
2922 my ($self) = @_;
2923 ($self->rewrite_root || $self->{url}) .
2924 (length $self->{path} ? '/' . $self->{path} : '');
2925}
2926
706587fc 2927sub full_url {
9b981fc6 2928 my ($self) = @_;
5d3b7cd5 2929 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
2930}
2931
12a296bc
AS
2932sub full_pushurl {
2933 my ($self) = @_;
2934 if ($self->{pushurl}) {
2935 return $self->{pushurl} . (length $self->{path} ? '/' .
2936 $self->{path} : '');
2937 } else {
2938 return $self->full_url;
2939 }
2940}
ad94802a
EW
2941
2942sub set_commit_header_env {
2943 my ($log_entry) = @_;
2944 my %env;
2945 foreach my $ned (qw/NAME EMAIL DATE/) {
2946 foreach my $ac (qw/AUTHOR COMMITTER/) {
2947 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2948 }
9b981fc6 2949 }
ad94802a 2950
70ae04e4
AW
2951 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2952 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
44320b9e 2953 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 2954
70ae04e4
AW
2955 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2956 ? $log_entry->{commit_name}
2957 : $log_entry->{name};
2958 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2959 ? $log_entry->{commit_email}
2960 : $log_entry->{email};
ad94802a
EW
2961 \%env;
2962}
70ae04e4 2963
ad94802a
EW
2964sub restore_commit_header_env {
2965 my ($env) = @_;
2966 foreach my $ned (qw/NAME EMAIL DATE/) {
2967 foreach my $ac (qw/AUTHOR COMMITTER/) {
2968 my $k = "GIT_${ac}_${ned}";
2969 if (defined $env->{$k}) {
2970 $ENV{$k} = $env->{$k};
2971 } else {
2972 delete $ENV{$k};
2973 }
2974 }
2975 }
2976}
2977
94bc914c
KW
2978sub gc {
2979 command_noisy('gc', '--auto');
2980};
2981
ad94802a
EW
2982sub do_git_commit {
2983 my ($self, $log_entry) = @_;
2984 my $lr = $self->last_rev;
2985 if (defined $lr && $lr >= $log_entry->{revision}) {
2986 die "Last fetched revision of ", $self->refname,
2987 " was r$lr, but we are about to fetch: ",
2988 "r$log_entry->{revision}!\n";
2989 }
2990 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2991 croak "$log_entry->{revision} = $c already exists! ",
2992 "Why are we refetching it?\n";
2993 }
2994 my $old_env = set_commit_header_env($log_entry);
44320b9e 2995 my $tree = $log_entry->{tree};
9b981fc6
EW
2996 if (!defined $tree) {
2997 $tree = $self->tmp_index_do(sub {
2998 command_oneline('write-tree') });
2999 }
3000 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
3001
e855bfc0 3002 my @exec = ('git', 'commit-tree', $tree);
0af9c9f9 3003 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
3004 push @exec, '-p', $_;
3005 }
3006 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
3007 or croak $!;
16fc08e2
EW
3008 binmode $msg_fh;
3009
3010 # we always get UTF-8 from SVN, but we may want our commits in
3011 # a different encoding.
3012 if (my $enc = Git::config('i18n.commitencoding')) {
3013 require Encode;
3014 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
3015 }
44320b9e 3016 print $msg_fh $log_entry->{log} or croak $!;
ad94802a 3017 restore_commit_header_env($old_env);
91b03282 3018 unless ($self->no_metadata) {
8a49ee97
EW
3019 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
3020 or croak $!;
9760adcc 3021 }
9b981fc6
EW
3022 $msg_fh->flush == 0 or croak $!;
3023 close $msg_fh or croak $!;
3024 chomp(my $commit = do { local $/; <$out_fh> });
3025 close $out_fh or croak $!;
3026 waitpid $pid, 0;
3027 croak $? if $?;
3028 if ($commit !~ /^$::sha1$/o) {
3029 die "Failed to commit, invalid sha1: $commit\n";
3030 }
3031
060610c5 3032 $self->rev_map_set($log_entry->{revision}, $commit, 1);
9b981fc6 3033
44320b9e 3034 $self->{last_rev} = $log_entry->{revision};
9b981fc6 3035 $self->{last_commit} = $commit;
49750f30 3036 print "r$log_entry->{revision}" unless $::_q > 1;
8a49ee97 3037 if (defined $log_entry->{svm_revision}) {
49750f30 3038 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
060610c5 3039 $self->rev_map_set($log_entry->{svm_revision}, $commit,
26a62d57 3040 0, $self->svm_uuid);
8a49ee97 3041 }
49750f30 3042 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
94bc914c
KW
3043 if (--$_gc_nr == 0) {
3044 $_gc_nr = $_gc_period;
3045 gc();
3046 }
9b981fc6
EW
3047 return $commit;
3048}
3049
fbcc1737
EW
3050sub match_paths {
3051 my ($self, $paths, $r) = @_;
4e9f6cc7 3052 return 1 if $self->{path} eq '';
d542aedb
EW
3053 if (my $path = $paths->{"/$self->{path}"}) {
3054 return ($path->{action} eq 'D') ? 0 : 1;
3055 }
0b2af457 3056 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
3057 if (grep /$self->{path_regex}/, keys %$paths) {
3058 return 1;
3059 }
3060 my $c = '';
3061 foreach (split m#/#, $self->{path}) {
3062 $c .= "/$_";
74a81227
EW
3063 next unless ($paths->{$c} &&
3064 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
3065 if ($self->ra->check_path($self->{path}, $r) ==
3066 $SVN::Node::dir) {
fbcc1737
EW
3067 return 1;
3068 }
3069 }
3070 return 0;
3071}
3072
15710b6f
EW
3073sub find_parent_branch {
3074 my ($self, $paths, $rev) = @_;
91b03282 3075 return undef unless $self->follow_parent;
e5a0b240 3076 unless (defined $paths) {
c7eba716
EW
3077 my $err_handler = $SVN::Error::handler;
3078 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
3c49a035
MN
3079 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
3080 sub { $paths = $_[0] });
c7eba716 3081 $SVN::Error::handler = $err_handler;
e5a0b240
EW
3082 }
3083 return undef unless defined $paths;
15710b6f
EW
3084
3085 # look for a parent from another branch:
0b2af457 3086 my @b_path_components = split m#/#, $self->{path};
7f578c55
EW
3087 my @a_path_components;
3088 my $i;
3089 while (@b_path_components) {
3090 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 3091 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
3092 unshift(@a_path_components, pop(@b_path_components));
3093 }
74a81227
EW
3094 return undef unless defined $i && defined $i->{copyfrom_path};
3095 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
3096 if (@a_path_components) {
3097 print STDERR "branch_from: $branch_from => ";
3098 $branch_from .= '/'.join('/', @a_path_components);
3099 print STDERR $branch_from, "\n";
3100 }
3ebe8df7 3101 my $r = $i->{copyfrom_rev};
15710b6f
EW
3102 my $repos_root = $self->ra->{repos_root};
3103 my $url = $self->ra->{url};
0b2af457 3104 my $new_url = $url . $branch_from;
15710b6f 3105 print STDERR "Found possible branch point: ",
85886162
SA
3106 "$new_url => ", $self->full_url, ", $r\n"
3107 unless $::_q > 1;
15710b6f 3108 $branch_from =~ s#^/##;
0b2af457 3109 my $gs = $self->other_gs($new_url, $url,
8e3f9b17 3110 $branch_from, $r, $self->{ref_id});
15710b6f 3111 my ($r0, $parent) = $gs->find_rev_before($r, 1);
553589f7
DM
3112 {
3113 my ($base, $head);
3114 if (!defined $r0 || !defined $parent) {
3115 ($base, $head) = parse_revision_argument(0, $r);
3116 } else {
3117 if ($r0 < $r) {
3118 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
3119 0, 1, sub { $base = $_[1] - 1 });
3120 }
3121 }
3122 if (defined $base && $base <= $r) {
d627de6b
EW
3123 $gs->fetch($base, $r);
3124 }
553589f7 3125 ($r0, $parent) = $gs->find_rev_before($r, 1);
15710b6f 3126 }
ef70de96 3127 if (defined $r0 && defined $parent) {
85886162
SA
3128 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
3129 unless $::_q > 1;
15710b6f
EW
3130 my $ed;
3131 if ($self->ra->can_do_switch) {
2e5e2480 3132 $self->assert_index_clean($parent);
85886162
SA
3133 print STDERR "Following parent with do_switch\n"
3134 unless $::_q > 1;
15710b6f 3135 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 3136 # is not included with SVN 1.4.3 (the latest version
15710b6f 3137 # at the moment), so we can't rely on it
83c2fcff 3138 $self->{last_rev} = $r0;
15710b6f 3139 $self->{last_commit} = $parent;
8841b37f 3140 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
8a603774 3141 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
3142 $self->full_url, $ed)
3143 or die "SVN connection failed somewhere...\n";
9ff74e95
SW
3144 } elsif ($self->ra->trees_match($new_url, $r0,
3145 $self->full_url, $rev)) {
3146 print STDERR "Trees match:\n",
3147 " $new_url\@$r0\n",
3148 " ${\$self->full_url}\@$rev\n",
85886162
SA
3149 "Following parent with no changes\n"
3150 unless $::_q > 1;
9ff74e95
SW
3151 $self->tmp_index_do(sub {
3152 command_noisy('read-tree', $parent);
3153 });
3154 $self->{last_commit} = $parent;
15710b6f 3155 } else {
85886162
SA
3156 print STDERR "Following parent with do_update\n"
3157 unless $::_q > 1;
15710b6f 3158 $ed = SVN::Git::Fetcher->new($self);
8a603774 3159 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
3160 or die "SVN connection failed somewhere...\n";
3161 }
85886162 3162 print STDERR "Successfully followed parent\n" unless $::_q > 1;
15710b6f
EW
3163 return $self->make_log_entry($rev, [$parent], $ed);
3164 }
15710b6f
EW
3165 return undef;
3166}
3167
9b981fc6 3168sub do_fetch {
706587fc 3169 my ($self, $paths, $rev) = @_;
15710b6f 3170 my $ed;
9b981fc6 3171 my ($last_rev, @parents);
b9dffd8c
EW
3172 if (my $lc = $self->last_commit) {
3173 # we can have a branch that was deleted, then re-added
3174 # under the same name but copied from another path, in
3175 # which case we'll have multiple parents (we don't
3176 # want to break the original ref, nor lose copypath info):
3177 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3178 push @{$log_entry->{parents}}, $lc;
3179 return $log_entry;
3180 }
15710b6f 3181 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 3182 $last_rev = $self->{last_rev};
b9dffd8c
EW
3183 $ed->{c} = $lc;
3184 @parents = ($lc);
9b981fc6
EW
3185 } else {
3186 $last_rev = $rev;
15710b6f
EW
3187 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
3188 return $log_entry;
3189 }
3190 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 3191 }
8a603774 3192 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
3193 die "SVN connection failed somewhere...\n";
3194 }
3195 $self->make_log_entry($rev, \@parents, $ed);
3196}
3197
6111b934
EW
3198sub mkemptydirs {
3199 my ($self, $r) = @_;
a5b80d92
EW
3200
3201 sub scan {
3202 my ($r, $empty_dirs, $line) = @_;
3203 if (defined $r && $line =~ /^r(\d+)$/) {
3204 return 0 if $1 > $r;
3205 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
3206 $empty_dirs->{$1} = 1;
3207 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
3208 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
3209 delete @$empty_dirs{@d};
3210 }
3211 1; # continue
3212 };
3213
6111b934 3214 my %empty_dirs = ();
a5b80d92
EW
3215 my $gz_file = "$self->{dir}/unhandled.log.gz";
3216 if (-f $gz_file) {
3217 if (!$can_compress) {
3218 warn "Compress::Zlib could not be found; ",
3219 "empty directories in $gz_file will not be read\n";
3220 } else {
3221 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
3222 die "Unable to open $gz_file: $!\n";
3223 my $line;
3224 while ($gz->gzreadline($line) > 0) {
3225 scan($r, \%empty_dirs, $line) or last;
3226 }
3227 $gz->gzclose;
3228 }
3229 }
6111b934 3230
a5b80d92
EW
3231 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
3232 binmode $fh or croak "binmode: $!";
3233 while (<$fh>) {
3234 scan($r, \%empty_dirs, $_) or last;
6111b934 3235 }
a5b80d92 3236 close $fh;
6111b934 3237 }
9be30eed
EW
3238
3239 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
6111b934
EW
3240 foreach my $d (sort keys %empty_dirs) {
3241 $d = uri_decode($d);
9be30eed 3242 $d =~ s/$strip//;
7c42e390 3243 next unless length($d);
6111b934 3244 next if -d $d;
7c42e390 3245 if (-e $d) {
6111b934
EW
3246 warn "$d exists but is not a directory\n";
3247 } else {
3248 print "creating empty directory: $d\n";
3249 mkpath([$d]);
3250 }
3251 }
3252}
3253
97f6987a
EW
3254sub get_untracked {
3255 my ($self, $ed) = @_;
3256 my @out;
3257 my $h = $ed->{empty};
9b981fc6
EW
3258 foreach (sort keys %$h) {
3259 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 3260 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
3261 warn "W: $act: $_\n";
3262 }
3263 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 3264 $h = $ed->{$t} or next;
9b981fc6
EW
3265 foreach my $path (sort keys %$h) {
3266 my $ppath = $path eq '' ? '.' : $path;
3267 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 3268 next if $SKIP_PROP{$prop};
9b981fc6 3269 my $v = $h->{$path}->{$prop};
97f6987a
EW
3270 my $t_ppath_prop = "$t: " .
3271 uri_encode($ppath) . ' ' .
3272 uri_encode($prop);
9b981fc6 3273 if (defined $v) {
97f6987a
EW
3274 push @out, " +$t_ppath_prop " .
3275 uri_encode($v);
9b981fc6 3276 } else {
97f6987a 3277 push @out, " -$t_ppath_prop";
9b981fc6
EW
3278 }
3279 }
3280 }
3281 }
3282 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 3283 $h = $ed->{$t} or next;
9b981fc6
EW
3284 foreach my $parent (sort keys %$h) {
3285 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
3286 push @out, " $t: " .
3287 uri_encode("$parent/$path");
9b981fc6
EW
3288 warn "W: $t: $parent/$path ",
3289 "Insufficient permissions?\n";
3290 }
3291 }
3292 }
97f6987a 3293 \@out;
9b981fc6
EW
3294}
3295
6aa17fc6
WYC
3296sub get_tz {
3297 # some systmes don't handle or mishandle %z, so be creative.
3298 my $t = shift || time;
3299 my $gm = timelocal(gmtime($t));
3300 my $sign = qw( + + - )[ $t <=> $gm ];
3301 return sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
3302}
3303
e82f0d73
PH
3304# parse_svn_date(DATE)
3305# --------------------
3306# Given a date (in UTC) from Subversion, return a string in the format
3307# "<TZ Offset> <local date/time>" that Git will use.
3308#
3309# By default the parsed date will be in UTC; if $Git::SVN::_localtime
3310# is true we'll convert it to the local timezone instead.
1c8443b0
EW
3311sub parse_svn_date {
3312 my $date = shift || return '+0000 1970-01-01 00:00:00';
3313 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
b94ead75 3314 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1c8443b0 3315 croak "Unable to parse date: $date\n";
e82f0d73
PH
3316 my $parsed_date; # Set next.
3317
3318 if ($Git::SVN::_localtime) {
3319 # Translate the Subversion datetime to an epoch time.
3320 # Begin by switching ourselves to $date's timezone, UTC.
3321 my $old_env_TZ = $ENV{TZ};
3322 $ENV{TZ} = 'UTC';
3323
3324 my $epoch_in_UTC =
3325 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
3326
3327 # Determine our local timezone (including DST) at the
3328 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
3329 # value of TZ, if any, at the time we were run.
3330 if (defined $Git::SVN::Log::TZ) {
3331 $ENV{TZ} = $Git::SVN::Log::TZ;
3332 } else {
3333 delete $ENV{TZ};
3334 }
3335
6aa17fc6 3336 my $our_TZ = get_tz();
e82f0d73
PH
3337
3338 # This converts $epoch_in_UTC into our local timezone.
3339 my ($sec, $min, $hour, $mday, $mon, $year,
3340 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
3341
3342 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
3343 $our_TZ, $year + 1900, $mon + 1,
3344 $mday, $hour, $min, $sec);
3345
3346 # Reset us to the timezone in effect when we entered
3347 # this routine.
3348 if (defined $old_env_TZ) {
3349 $ENV{TZ} = $old_env_TZ;
3350 } else {
3351 delete $ENV{TZ};
3352 }
3353 } else {
3354 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
3355 }
3356
3357 return $parsed_date;
1c8443b0
EW
3358}
3359
8e3f9b17 3360sub other_gs {
0b2af457 3361 my ($self, $new_url, $url,
8e3f9b17 3362 $branch_from, $r, $old_ref_id) = @_;
0b2af457 3363 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
8e3f9b17
SV
3364 unless ($gs) {
3365 my $ref_id = $old_ref_id;
54fb7f9b 3366 $ref_id =~ s/\@\d+-*$//;
8e3f9b17
SV
3367 $ref_id .= "\@$r";
3368 # just grow a tail if we're not unique enough :x
3369 $ref_id .= '-' while find_ref($ref_id);
8e3f9b17
SV
3370 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
3371 if ($u =~ s#^\Q$url\E(/|$)##) {
3372 $p = $u;
3373 $u = $url;
3374 $repo_id = $self->{repo_id};
3375 }
3235b705
DK
3376 while (1) {
3377 # It is possible to tag two different subdirectories at
3378 # the same revision. If the url for an existing ref
3379 # does not match, we must either find a ref with a
3380 # matching url or create a new ref by growing a tail.
3381 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
3382 my (undef, $max_commit) = $gs->rev_map_max(1);
3383 last if (!$max_commit);
3384 my ($url) = ::cmt_metadata($max_commit);
85f022e9 3385 last if ($url eq $gs->metadata_url);
3235b705
DK
3386 $ref_id .= '-';
3387 }
3388 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
8e3f9b17
SV
3389 }
3390 $gs
3391}
3392
36db1edd
ML
3393sub call_authors_prog {
3394 my ($orig_author) = @_;
d3d7d47e 3395 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
36db1edd
ML
3396 my $author = `$::_authors_prog $orig_author`;
3397 if ($? != 0) {
3398 die "$::_authors_prog failed with exit code $?\n"
3399 }
3400 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3401 my ($name, $email) = ($1, $2);
3402 $email = undef if length $2 == 0;
3403 return [$name, $email];
3404 } else {
3405 die "Author: $orig_author: $::_authors_prog returned "
3406 . "invalid author format: $author\n";
3407 }
3408}
3409
1c8443b0
EW
3410sub check_author {
3411 my ($author) = @_;
3412 if (!defined $author || length $author == 0) {
3413 $author = '(no author)';
36db1edd
ML
3414 }
3415 if (!defined $::users{$author}) {
3416 if (defined $::_authors_prog) {
3417 $::users{$author} = call_authors_prog($author);
3418 } elsif (defined $::_authors) {
3419 die "Author: $author not defined in $::_authors file\n";
3420 }
1c8443b0
EW
3421 }
3422 $author;
3423}
3424
f1264bd6
SV
3425sub find_extra_svk_parents {
3426 my ($self, $ed, $tickets, $parents) = @_;
3427 # aha! svk:merge property changed...
3428 my @tickets = split "\n", $tickets;
3429 my @known_parents;
3430 for my $ticket ( @tickets ) {
3431 my ($uuid, $path, $rev) = split /:/, $ticket;
3432 if ( $uuid eq $self->ra_uuid ) {
bf60fff8 3433 my $url = $self->{url};
f1264bd6
SV
3434 my $repos_root = $url;
3435 my $branch_from = $path;
3436 $branch_from =~ s{^/}{};
3437 my $gs = $self->other_gs($repos_root."/".$branch_from,
3438 $url,
3439 $branch_from,
3440 $rev,
3441 $self->{ref_id});
3442 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3443 # wahey! we found it, but it might be
3444 # an old one (!)
e9e4c8b7 3445 push @known_parents, [ $rev, $commit ];
f1264bd6
SV
3446 }
3447 }
3448 }
e9e4c8b7
AV
3449 # Ordering matters; highest-numbered commit merge tickets
3450 # first, as they may account for later merge ticket additions
3451 # or changes.
3452 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
f1264bd6
SV
3453 for my $parent ( @known_parents ) {
3454 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3455 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3456 my $new;
3457 while ( <$msg_fh> ) {
3458 $new=1;last;
3459 }
3460 command_close_pipe($msg_fh, $ctx);
3461 if ( $new ) {
3462 print STDERR
3463 "Found merge parent (svk:merge ticket): $parent\n";
3464 push @$parents, $parent;
3465 }
3466 }
3467}
3468
7d944c33
SV
3469sub lookup_svn_merge {
3470 my $uuid = shift;
3471 my $url = shift;
3472 my $merge = shift;
3473
3474 my ($source, $revs) = split ":", $merge;
3475 my $path = $source;
3476 $path =~ s{^/}{};
3477 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3478 if ( !$gs ) {
3479 warn "Couldn't find revmap for $url$source\n";
3480 return;
3481 }
3482 my @ranges = split ",", $revs;
3483 my ($tip, $tip_commit);
3484 my @merged_commit_ranges;
3485 # find the tip
3486 for my $range ( @ranges ) {
3487 my ($bottom, $top) = split "-", $range;
3488 $top ||= $bottom;
33973a5b
SV
3489 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3490 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
7d944c33
SV
3491
3492 unless ($top_commit and $bottom_commit) {
3493 warn "W:unknown path/rev in svn:mergeinfo "
3494 ."dirprop: $source:$range\n";
3495 next;
3496 }
3497
124b70a2
MH
3498 if (scalar(command('rev-parse', "$bottom_commit^@"))) {
3499 push @merged_commit_ranges,
3500 "$bottom_commit^..$top_commit";
3501 } else {
3502 push @merged_commit_ranges, "$top_commit";
3503 }
7d944c33
SV
3504
3505 if ( !defined $tip or $top > $tip ) {
3506 $tip = $top;
3507 $tip_commit = $top_commit;
3508 }
3509 }
3510 return ($tip_commit, @merged_commit_ranges);
3511}
7a955a53
SV
3512
3513sub _rev_list {
3514 my ($msg_fh, $ctx) = command_output_pipe(
3515 "rev-list", @_,
3516 );
3517 my @rv;
3518 while ( <$msg_fh> ) {
3519 chomp;
3520 push @rv, $_;
3521 }
3522 command_close_pipe($msg_fh, $ctx);
3523 @rv;
3524}
3525
3526sub check_cherry_pick {
3527 my $base = shift;
3528 my $tip = shift;
a3c75056 3529 my $parents = shift;
7a955a53
SV
3530 my @ranges = @_;
3531 my %commits = map { $_ => 1 }
eabd73a3 3532 _rev_list("--no-merges", $tip, "--not", $base, @$parents, "--");
7a955a53 3533 for my $range ( @ranges ) {
eabd73a3 3534 delete @commits{_rev_list($range, "--")};
7a955a53 3535 }
1cef6500
AM
3536 for my $commit (keys %commits) {
3537 if (has_no_changes($commit)) {
3538 delete $commits{$commit};
3539 }
3540 }
7a955a53
SV
3541 return (keys %commits);
3542}
3543
1cef6500
AM
3544sub has_no_changes {
3545 my $commit = shift;
3546
3547 my @revs = split / /, command_oneline(
3548 qw(rev-list --parents -1 -m), $commit);
3549
3550 # Commits with no parents, e.g. the start of a partial branch,
3551 # have changes by definition.
3552 return 1 if (@revs < 2);
3553
3554 # Commits with multiple parents, e.g a merge, have no changes
3555 # by definition.
3556 return 0 if (@revs > 2);
3557
3558 return (command_oneline("rev-parse", "$commit^{tree}") eq
3559 command_oneline("rev-parse", "$commit~1^{tree}"));
3560}
3561
8bff7c53
AM
3562# The GIT_DIR environment variable is not always set until after the command
3563# line arguments are processed, so we can't memoize in a BEGIN block.
3564{
3565 my $memoized = 0;
3566
3567 sub memoize_svn_mergeinfo_functions {
3568 return if $memoized;
3569 $memoized = 1;
3570
3571 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3572<