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