]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
git-svn: factor out _collapse_dotdot function
[thirdparty/git.git] / git-svn.perl
CommitLineData
0754e089 1#!/usr/bin/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
e96cdba1
MS
13use Carp qw/croak/;
14use Digest::MD5;
15use IO::File qw//;
16use File::Basename qw/dirname basename/;
17use File::Path qw/mkpath/;
18use File::Spec;
19use File::Find;
20use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
21use IPC::Open3;
22use Memoize;
23
29499c0b 24use Git::SVN;
e96cdba1
MS
25use Git::SVN::Editor;
26use Git::SVN::Fetcher;
27use Git::SVN::Ra;
28use Git::SVN::Prompt;
b74fda1c 29use Git::SVN::Log;
b772cb99 30use Git::SVN::Migration;
c2768fa1 31
91e6e0c5
MS
32use Git::SVN::Utils qw(
33 fatal
34 can_compress
35 canonicalize_path
36 canonicalize_url
37);
38
b0e75250
MS
39use Git qw(
40 git_cmd_try
41 command
42 command_oneline
43 command_noisy
44 command_output_pipe
45 command_close_pipe
46 command_bidi_pipe
47 command_close_bidi_pipe
48);
49
e96cdba1
MS
50BEGIN {
51 Memoize::memoize 'Git::config';
52 Memoize::memoize 'Git::config_bool';
53}
54
b0e75250 55
15153451
BS
56# From which subdir have we been invoked?
57my $cmd_dir_prefix = eval {
58 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
59} || '';
60
5253dc33 61my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 62$ENV{GIT_DIR} ||= '.git';
6af1db44 63$Git::SVN::Ra::_log_window_size = 100;
13ccd6d4 64
184892fb
SS
65if (! exists $ENV{SVN_SSH} && exists $ENV{GIT_SSH}) {
66 $ENV{SVN_SSH} = $ENV{GIT_SSH};
67}
68
69if (exists $ENV{SVN_SSH} && $^O eq 'msys') {
70 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
71 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
f3a87d92
K
72}
73
f8c9d1d2 74$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 75$ENV{TZ} = 'UTC';
a00439ac 76$| = 1; # unbuffer STDOUT
3397f9df 77
6ade9bda
RK
78# All SVN commands do it. Otherwise we may die on SIGPIPE when the remote
79# repository decides to close the connection which we expect to be kept alive.
80$SIG{PIPE} = 'IGNORE';
81
f760c903
JH
82# Given a dot separated version number, "subtract" it from
83# the SVN::Core::VERSION; non-negaitive return means the SVN::Core
84# is at least at the version the caller asked for.
85sub compare_svn_version {
86 my (@ours) = split(/\./, $SVN::Core::VERSION);
87 my (@theirs) = split(/\./, $_[0]);
88 my ($i, $diff);
89
90 for ($i = 0; $i < @ours && $i < @theirs; $i++) {
91 $diff = $ours[$i] - $theirs[$i];
92 return $diff if ($diff);
93 }
94 return 1 if ($i < @ours);
95 return -1 if ($i < @theirs);
96 return 0;
97}
98
d32fad2b 99sub _req_svn {
100 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
101 require SVN::Ra;
102 require SVN::Delta;
f760c903 103 if (::compare_svn_version('1.1.0') < 0) {
d32fad2b 104 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
105 }
b9c85187 106}
c2768fa1 107
f8c9d1d2
EW
108$sha1 = qr/[a-f\d]{40}/;
109$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 110my ($_stdin, $_help, $_edit,
62244069 111 $_message, $_file, $_branch_dest,
d05d72e0 112 $_template, $_shared,
c2abd83f 113 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
b64e1f58 114 $_merge, $_strategy, $_preserve_merges, $_dry_run, $_local,
4be40381 115 $_prefix, $_no_checkout, $_url, $_verbose,
2c96a6c3 116 $_commit_url, $_tag, $_merge_info, $_interactive);
0f80aa03
MS
117
118# This is a refactoring artifact so Git::SVN can get at this git-svn switch.
119sub opt_prefix { return $_prefix || '' }
120
72827aa4 121$Git::SVN::Fetcher::_placeholder_filename = ".gitignore";
49750f30 122$_q ||= 0;
706587fc
EW
123my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
124 'config-dir=s' => \$Git::SVN::Ra::config_dir,
edc662f9 125 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
72827aa4 126 'ignore-paths=s' => \$Git::SVN::Fetcher::_ignore_regex,
cdb51a13 127 'ignore-refs=s' => \$Git::SVN::Ra::_ignore_refs_regex );
0bed5eaa 128my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 129 'authors-file|A=s' => \$_authors,
36db1edd 130 'authors-prog=s' => \$_authors_prog,
ecc712dd 131 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
132 'noMetadata' => \$Git::SVN::_no_metadata,
133 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 134 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 135 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 136 'no-checkout' => \$_no_checkout,
49750f30 137 'quiet|q+' => \$_q,
ecc712dd
EW
138 'repack-flags|repack-args|repack-opts=s' =>
139 \$Git::SVN::_repack_flags,
70ae04e4 140 'use-log-author' => \$Git::SVN::_use_log_author,
6aa9ba14 141 'add-author-from' => \$Git::SVN::_add_author_from,
e82f0d73 142 'localtime' => \$Git::SVN::_localtime,
706587fc 143 %remote_opts );
36f5b1f0 144
62244069 145my ($_trunk, @_tags, @_branches, $_stdlayout);
0dfaf0a4 146my %icv;
dadc6d2a 147my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
62244069
MB
148 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
149 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
8f728fb9 150 'stdlayout|s' => \$_stdlayout,
6b48829d 151 'minimize-url|m!' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
152 'no-metadata' => sub { $icv{noMetadata} = 1 },
153 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
154 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
155 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
3e18ce1a 156 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
dadc6d2a 157 %remote_opts );
27e9fb8d 158my %cmt_opts = ( 'edit|e' => \$_edit,
72827aa4
JN
159 'rmdir' => \$Git::SVN::Editor::_rmdir,
160 'find-copies-harder' => \$Git::SVN::Editor::_find_copies_harder,
161 'l=i' => \$Git::SVN::Editor::_rename_limit,
162 'copy-similarity|C=i'=> \$Git::SVN::Editor::_cp_similarity
27e9fb8d 163);
9d55b41a 164
3397f9df 165my %cmd = (
2a3240be 166 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 167 { 'revision|r=s' => \$_revision,
905f8b7d 168 'fetch-all|all' => \$_fetch_all,
c2abd83f 169 'parent|p' => \$_fetch_parent,
e98671e5 170 %fc_opts } ],
0425ea90
EW
171 clone => [ \&cmd_clone, "Initialize and fetch revisions",
172 { 'revision|r=s' => \$_revision,
40a1530c 173 'preserve-empty-dirs' =>
72827aa4 174 \$Git::SVN::Fetcher::_preserve_empty_dirs,
40a1530c 175 'placeholder-filename=s' =>
72827aa4 176 \$Git::SVN::Fetcher::_placeholder_filename,
0425ea90 177 %fc_opts, %init_opts } ],
d2866f9e 178 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 179 " (requires URL argument)",
9d55b41a 180 \%init_opts ],
dadc6d2a
EW
181 'multi-init' => [ \&cmd_multi_init,
182 "Deprecated alias for ".
183 "'$0 init -T<trunk> -b<branches> -t<tags>'",
184 \%init_opts ],
d7ad3bed
EW
185 dcommit => [ \&cmd_dcommit,
186 'Commit several diffs to merge with upstream',
3289e86e
EW
187 { 'merge|m|M' => \$_merge,
188 'strategy|s=s' => \$_strategy,
905f8b7d 189 'verbose|v' => \$_verbose,
3289e86e 190 'dry-run|n' => \$_dry_run,
905f8b7d 191 'fetch-all|all' => \$_fetch_all,
ba24e745
EW
192 'commit-url=s' => \$_commit_url,
193 'revision|r=i' => \$_revision,
171af110 194 'no-rebase' => \$_no_rebase,
6abd9332 195 'mergeinfo=s' => \$_merge_info,
afd7f1eb 196 'interactive|i' => \$_interactive,
4b155223 197 %cmt_opts, %fc_opts } ],
5de70efb
FR
198 branch => [ \&cmd_branch,
199 'Create a branch in the SVN repository',
200 { 'message|m=s' => \$_message,
62244069 201 'destination|d=s' => \$_branch_dest,
5de70efb 202 'dry-run|n' => \$_dry_run,
6594f0b7
IM
203 'tag|t' => \$_tag,
204 'username=s' => \$Git::SVN::Prompt::_username,
205 'commit-url=s' => \$_commit_url } ],
5de70efb
FR
206 tag => [ sub { $_tag = 1; cmd_branch(@_) },
207 'Create a tag in the SVN repository',
208 { 'message|m=s' => \$_message,
62244069 209 'destination|d=s' => \$_branch_dest,
6594f0b7
IM
210 'dry-run|n' => \$_dry_run,
211 'username=s' => \$Git::SVN::Prompt::_username,
212 'commit-url=s' => \$_commit_url } ],
1ce255dc
EW
213 'set-tree' => [ \&cmd_set_tree,
214 "Set an SVN repository to a git tree-ish",
e84dc6df 215 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
216 'create-ignore' => [ \&cmd_create_ignore,
217 'Create a .gitignore per svn:ignore',
218 { 'revision|r=i' => \$_revision
219 } ],
6111b934
EW
220 'mkdirs' => [ \&cmd_mkdirs ,
221 "recreate empty directories after a checkout",
222 { 'revision|r=i' => \$_revision } ],
15153451
BS
223 'propget' => [ \&cmd_propget,
224 'Print the value of a property on a file or directory',
225 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
226 'proplist' => [ \&cmd_proplist,
227 'List all properties of a file or directory',
228 { 'revision|r=i' => \$_revision } ],
5969cbe1 229 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 230 { 'revision|r=i' => \$_revision
05b4df31 231 } ],
2d879792
VK
232 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
233 { 'revision|r=i' => \$_revision
234 } ],
1c8443b0 235 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
236 "Deprecated alias for $0 fetch --all",
237 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
238 'migrate' => [ sub { },
239 # no-op, we automatically run this anyways,
706587fc
EW
240 'Migrate configuration/metadata/layout from
241 previous versions of git-svn',
a836a0e1
EW
242 { 'minimize' => \$Git::SVN::Migration::_minimize,
243 %remote_opts } ],
f8c9d1d2
EW
244 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
245 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 246 'revision|r=s' => \$_revision,
f8c9d1d2
EW
247 'verbose|v' => \$Git::SVN::Log::verbose,
248 'incremental' => \$Git::SVN::Log::incremental,
249 'oneline' => \$Git::SVN::Log::oneline,
250 'show-commit' => \$Git::SVN::Log::show_commit,
251 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 252 'authors-file|A=s' => \$_authors,
f8c9d1d2 253 'color' => \$Git::SVN::Log::color,
4dbfe2e9 254 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 255 } ],
222566e4
EW
256 'find-rev' => [ \&cmd_find_rev,
257 "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 258 {} ],
905f8b7d
EW
259 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
260 { 'merge|m|M' => \$_merge,
261 'verbose|v' => \$_verbose,
262 'strategy|s=s' => \$_strategy,
dee41f3e 263 'local|l' => \$_local,
905f8b7d 264 'fetch-all|all' => \$_fetch_all,
7d45e146 265 'dry-run|n' => \$_dry_run,
b64e1f58 266 'preserve-merges|p' => \$_preserve_merges,
905f8b7d 267 %fc_opts } ],
44320b9e
EW
268 'commit-diff' => [ \&cmd_commit_diff,
269 'Commit a diff between two trees',
27e9fb8d
EW
270 { 'message|m=s' => \$_message,
271 'file|F=s' => \$_file,
45bf473a 272 'revision|r=s' => \$_revision,
27e9fb8d 273 %cmt_opts } ],
e6fefa92
DK
274 'info' => [ \&cmd_info,
275 "Show info about the latest SVN revision
276 on the current branch",
8b014d71 277 { 'url' => \$_url, } ],
6fb5375e
TS
278 'blame' => [ \&Git::SVN::Log::cmd_blame,
279 "Show what revision and author last modified each line of a file",
2c96a6c3 280 { 'git-format' => \$Git::SVN::Log::_git_format } ],
195643f2
BJ
281 'reset' => [ \&cmd_reset,
282 "Undo fetches back to the specified SVN revision",
283 { 'revision|r=s' => \$_revision,
284 'parent|p' => \$_fetch_parent } ],
2da9ee08
RZ
285 'gc' => [ \&cmd_gc,
286 "Compress unhandled.log files in .git/svn and remove " .
287 "index files in .git/svn",
288 {} ],
3397f9df 289);
9d55b41a 290
afd7f1eb
FH
291use Term::ReadLine;
292package FakeTerm;
293sub new {
294 my ($class, $reason) = @_;
295 return bless \$reason, shift;
296}
297sub readline {
298 my $self = shift;
299 die "Cannot use readline on FakeTerm: $$self";
300}
301package main;
302
303my $term = eval {
304 $ENV{"GIT_SVN_NOTTY"}
305 ? new Term::ReadLine 'git-svn', \*STDIN, \*STDOUT
306 : new Term::ReadLine 'git-svn';
307};
308if ($@) {
309 $term = new FakeTerm "$@: going non-interactive";
310}
311
3397f9df
EW
312my $cmd;
313for (my $i = 0; $i < @ARGV; $i++) {
314 if (defined $cmd{$ARGV[$i]}) {
315 $cmd = $ARGV[$i];
316 splice @ARGV, $i, 1;
317 last;
9a8c92ac
BJ
318 } elsif ($ARGV[$i] eq 'help') {
319 $cmd = $ARGV[$i+1];
320 usage(0);
3397f9df
EW
321 }
322};
323
540424b2
EW
324# make sure we're always running at the top-level working directory
325unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
326 unless (-d $ENV{GIT_DIR}) {
327 if ($git_dir_user_set) {
328 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
329 "but it is not a directory\n";
330 }
331 my $git_dir = delete $ENV{GIT_DIR};
fe4003f6
DM
332 my $cdup = undef;
333 git_cmd_try {
334 $cdup = command_oneline(qw/rev-parse --show-cdup/);
335 $git_dir = '.' unless ($cdup);
336 chomp $cdup if ($cdup);
337 $cdup = "." unless ($cdup && length $cdup);
338 } "Already at toplevel, but $git_dir not found\n";
5253dc33
EW
339 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
340 unless (-d $git_dir) {
341 die "$git_dir still not found after going to ",
342 "'$cdup'\n";
343 }
344 $ENV{GIT_DIR} = $git_dir;
345 }
ffe256f9 346 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
5253dc33 347}
f4dd334b
GH
348
349my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
350
1a30582b 351read_git_config(\%opts);
222566e4
EW
352if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
353 Getopt::Long::Configure('pass_through');
354}
87182b17 355my $rv = GetOptions(%opts, 'h|H' => \$_help, 'version|V' => \$_version,
f4dd334b
GH
356 'minimize-connections' => \$Git::SVN::Migration::_minimize,
357 'id|i=s' => \$Git::SVN::default_ref_id,
358 'svn-remote|remote|R=s' => sub {
359 $Git::SVN::no_reuse_existing = 1;
360 $Git::SVN::default_repo_id = $_[1] });
361exit 1 if (!$rv && $cmd && $cmd ne 'log');
362
363usage(0) if $_help;
364version() if $_version;
365usage(1) unless defined $cmd;
366load_authors() if $_authors;
36db1edd
ML
367if (defined $_authors_prog) {
368 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
369}
f4dd334b 370
0425ea90 371unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
372 Git::SVN::Migration::migration_check();
373}
ecc712dd 374Git::SVN::init_vars();
b805b44a
EW
375eval {
376 Git::SVN::verify_remotes_sanity();
377 $cmd{$cmd}->[0]->(@ARGV);
e3bd4dda 378 post_fetch_checkout();
b805b44a
EW
379};
380fatal $@ if $@;
3397f9df
EW
381exit 0;
382
383####################### primary functions ######################
384sub usage {
385 my $exit = shift || 0;
386 my $fd = $exit ? \*STDERR : \*STDOUT;
387 print $fd <<"";
388git-svn - bidirectional operations between a single Subversion tree and git
1b1dd23f 389Usage: git svn <command> [options] [arguments]\n
448c81b4
EW
390
391 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
392
393 foreach (sort keys %cmd) {
448c81b4 394 next if $cmd && $cmd ne $_;
a836a0e1 395 next if /^multi-/; # don't show deprecated commands
b203b769 396 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 397 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
398 # mixed-case options are for .git/config only
399 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 400 # prints out arguments as they should be passed:
b8c92cad 401 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 402 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
403 "--$_" : "-$_" }
404 split /\|/,$_)," $x\n";
405 }
3397f9df
EW
406 }
407 print $fd <<"";
448c81b4
EW
408\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
409arbitrary identifier if you're tracking multiple SVN branches/repositories in
410one git repository and want to keep them separate. See git-svn(1) for more
411information.
3397f9df
EW
412
413 exit $exit;
414}
415
551ce28f 416sub version {
b0779246 417 ::_req_svn();
7d60ab2c 418 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
419 exit 0;
420}
421
afd7f1eb
FH
422sub ask {
423 my ($prompt, %arg) = @_;
424 my $valid_re = $arg{valid_re};
425 my $default = $arg{default};
426 my $resp;
427 my $i = 0;
428
429 if ( !( defined($term->IN)
430 && defined( fileno($term->IN) )
431 && defined( $term->OUT )
432 && defined( fileno($term->OUT) ) ) ){
433 return defined($default) ? $default : undef;
434 }
435
436 while ($i++ < 10) {
437 $resp = $term->readline($prompt);
438 if (!defined $resp) { # EOF
439 print "\n";
440 return defined $default ? $default : undef;
441 }
442 if ($resp eq '' and defined $default) {
443 return $default;
444 }
445 if (!defined $valid_re or $resp =~ /$valid_re/) {
446 return $resp;
447 }
448 }
449 return undef;
450}
451
8164b652
EW
452sub do_git_init_db {
453 unless (-d $ENV{GIT_DIR}) {
454 my @init_db = ('init');
455 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
456 if (defined $_shared) {
457 if ($_shared =~ /[a-z]/) {
458 push @init_db, "--shared=$_shared";
459 } else {
460 push @init_db, "--shared";
461 }
462 }
8164b652 463 command_noisy(@init_db);
ffe256f9 464 $_repository = Git->repository(Repository => ".git");
8164b652 465 }
0dfaf0a4
EW
466 my $set;
467 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
468 foreach my $i (keys %icv) {
469 die "'$set' and '$i' cannot both be set\n" if $set;
470 next unless defined $icv{$i};
471 command_noisy('config', "$pfx.$i", $icv{$i});
472 $set = $i;
473 }
72827aa4 474 my $ignore_paths_regex = \$Git::SVN::Fetcher::_ignore_regex;
cdb51a13
MO
475 command_noisy('config', "$pfx.ignore-paths", $$ignore_paths_regex)
476 if defined $$ignore_paths_regex;
477 my $ignore_refs_regex = \$Git::SVN::Ra::_ignore_refs_regex;
478 command_noisy('config', "$pfx.ignore-refs", $$ignore_refs_regex)
479 if defined $$ignore_refs_regex;
40a1530c 480
72827aa4
JN
481 if (defined $Git::SVN::Fetcher::_preserve_empty_dirs) {
482 my $fname = \$Git::SVN::Fetcher::_placeholder_filename;
40a1530c
RC
483 command_noisy('config', "$pfx.preserve-empty-dirs", 'true');
484 command_noisy('config', "$pfx.placeholder-filename", $$fname);
485 }
8164b652
EW
486}
487
dadc6d2a
EW
488sub init_subdir {
489 my $repo_path = shift or return;
490 mkpath([$repo_path]) unless -d $repo_path;
491 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 492 $ENV{GIT_DIR} = '.git';
ffe256f9 493 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
dadc6d2a
EW
494}
495
0425ea90
EW
496sub cmd_clone {
497 my ($url, $path) = @_;
498 if (!defined $path &&
62244069 499 (defined $_trunk || @_branches || @_tags ||
8f728fb9 500 defined $_stdlayout) &&
0425ea90
EW
501 $url !~ m#^[a-z\+]+://#) {
502 $path = $url;
503 }
0425ea90 504 $path = basename($url) if !defined $path || !length $path;
2bc35dcb 505 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
f30603fc 506 cmd_init($url, $path);
2bc35dcb
AV
507 command_oneline('config', 'svn.authorsfile', $authors_absolute)
508 if $_authors;
f5841509 509 Git::SVN::fetch_all($Git::SVN::default_repo_id);
0425ea90
EW
510}
511
d2866f9e 512sub cmd_init {
8f728fb9 513 if (defined $_stdlayout) {
514 $_trunk = 'trunk' if (!defined $_trunk);
62244069
MB
515 @_tags = 'tags' if (! @_tags);
516 @_branches = 'branches' if (! @_branches);
8f728fb9 517 }
62244069 518 if (defined $_trunk || @_branches || @_tags) {
dadc6d2a 519 return cmd_multi_init(@_);
03e0ea87 520 }
dadc6d2a
EW
521 my $url = shift or die "SVN repository location required ",
522 "as a command-line argument\n";
50ff2366 523 $url = canonicalize_url($url);
dadc6d2a 524 init_subdir(@_);
8164b652 525 do_git_init_db();
03e0ea87 526
6b48829d
EW
527 if ($Git::SVN::_minimize_url eq 'unset') {
528 $Git::SVN::_minimize_url = 0;
529 }
530
706587fc 531 Git::SVN->init($url);
3397f9df
EW
532}
533
2a3240be 534sub cmd_fetch {
e98671e5
EW
535 if (grep /^\d+=./, @_) {
536 die "'<rev>=<commit>' fetch arguments are ",
537 "no longer supported.\n";
07a1c950 538 }
e98671e5
EW
539 my ($remote) = @_;
540 if (@_ > 1) {
c2abd83f 541 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
e98671e5 542 }
4d0157d6 543 $Git::SVN::no_reuse_existing = undef;
c2abd83f
JM
544 if ($_fetch_parent) {
545 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
546 unless ($gs) {
547 die "Unable to determine upstream SVN information from ",
548 "working tree history\n";
549 }
550 # just fetch, don't checkout.
551 $_no_checkout = 'true';
552 $_fetch_all ? $gs->fetch_all : $gs->fetch;
553 } elsif ($_fetch_all) {
e98671e5
EW
554 cmd_multi_fetch();
555 } else {
c2abd83f 556 $remote ||= $Git::SVN::default_repo_id;
e98671e5 557 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 558 }
2a3240be
EW
559}
560
1ce255dc 561sub cmd_set_tree {
3397f9df
EW
562 my (@commits) = @_;
563 if ($_stdin || !@commits) {
564 print "Reading from stdin...\n";
565 @commits = ();
566 while (<STDIN>) {
1ca72aef 567 if (/\b($sha1_short)\b/o) {
3397f9df
EW
568 unshift @commits, $1;
569 }
570 }
571 }
572 my @revs;
8de010ad 573 foreach my $c (@commits) {
aef4e921 574 my @tmp = command('rev-parse',$c);
8de010ad
EW
575 if (scalar @tmp == 1) {
576 push @revs, $tmp[0];
577 } elsif (scalar @tmp > 1) {
aef4e921 578 push @revs, reverse(command('rev-list',@tmp));
8de010ad 579 } else {
207f1a75 580 fatal "Failed to rev-parse $c";
8de010ad 581 }
3397f9df 582 }
1ce255dc
EW
583 my $gs = Git::SVN->new;
584 my ($r_last, $cmt_last) = $gs->last_rev_commit;
585 $gs->fetch;
97f6987a 586 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
587 fatal "There are new revisions that were fetched ",
588 "and need to be merged (or acknowledged) ",
589 "before committing.\nlast rev: $r_last\n",
207f1a75 590 " current: $gs->{last_rev}";
a5e0cedc 591 }
1ce255dc
EW
592 $gs->set_tree($_) foreach @revs;
593 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 594 unlink $gs->{index};
a5e0cedc 595}
8f22562c 596
1e5814f3
BJ
597sub split_merge_info_range {
598 my ($range) = @_;
599 if ($range =~ /(\d+)-(\d+)/) {
600 return (int($1), int($2));
601 } else {
602 return (int($range), int($range));
603 }
604}
605
606sub combine_ranges {
607 my ($in) = @_;
608
609 my @fnums = ();
610 my @arr = split(/,/, $in);
611 for my $element (@arr) {
612 my ($start, $end) = split_merge_info_range($element);
613 push @fnums, $start;
614 }
615
616 my @sorted = @arr [ sort {
617 $fnums[$a] <=> $fnums[$b]
618 } 0..$#arr ];
619
620 my @return = ();
621 my $last = -1;
622 my $first = -1;
623 for my $element (@sorted) {
624 my ($start, $end) = split_merge_info_range($element);
625
626 if ($last == -1) {
627 $first = $start;
628 $last = $end;
629 next;
630 }
631 if ($start <= $last+1) {
632 if ($end > $last) {
633 $last = $end;
634 }
635 next;
636 }
637 if ($first == $last) {
638 push @return, "$first";
639 } else {
640 push @return, "$first-$last";
641 }
642 $first = $start;
643 $last = $end;
644 }
645
646 if ($first != -1) {
647 if ($first == $last) {
648 push @return, "$first";
649 } else {
650 push @return, "$first-$last";
651 }
652 }
653
654 return join(',', @return);
655}
656
657sub merge_revs_into_hash {
658 my ($hash, $minfo) = @_;
659 my @lines = split(' ', $minfo);
660
661 for my $line (@lines) {
662 my ($branchpath, $revs) = split(/:/, $line);
663
664 if (exists($hash->{$branchpath})) {
665 # Merge the two revision sets
666 my $combined = "$hash->{$branchpath},$revs";
667 $hash->{$branchpath} = combine_ranges($combined);
668 } else {
669 # Just do range combining for consolidation
670 $hash->{$branchpath} = combine_ranges($revs);
671 }
672 }
673}
674
675sub merge_merge_info {
676 my ($mergeinfo_one, $mergeinfo_two) = @_;
677 my %result_hash = ();
678
679 merge_revs_into_hash(\%result_hash, $mergeinfo_one);
680 merge_revs_into_hash(\%result_hash, $mergeinfo_two);
681
682 my $result = '';
683 # Sort below is for consistency's sake
684 for my $branchname (sort keys(%result_hash)) {
685 my $revlist = $result_hash{$branchname};
686 $result .= "$branchname:$revlist\n"
687 }
688 return $result;
689}
690
691sub populate_merge_info {
692 my ($d, $gs, $uuid, $linear_refs, $rewritten_parent) = @_;
693
694 my %parentshash;
695 read_commit_parents(\%parentshash, $d);
696 my @parents = @{$parentshash{$d}};
697 if ($#parents > 0) {
698 # Merge commit
699 my $all_parents_ok = 1;
700 my $aggregate_mergeinfo = '';
701 my $rooturl = $gs->repos_root;
702
703 if (defined($rewritten_parent)) {
704 # Replace first parent with newly-rewritten version
705 shift @parents;
706 unshift @parents, $rewritten_parent;
707 }
708
709 foreach my $parent (@parents) {
710 my ($branchurl, $svnrev, $paruuid) =
711 cmt_metadata($parent);
712
713 unless (defined($svnrev)) {
714 # Should have been caught be preflight check
715 fatal "merge commit $d has ancestor $parent, but that change "
716 ."does not have git-svn metadata!";
717 }
0e7e30f5 718 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
1e5814f3
BJ
719 fatal "commit $parent git-svn metadata changed mid-run!";
720 }
721 my $branchpath = $1;
722
723 my $ra = Git::SVN::Ra->new($branchurl);
724 my (undef, undef, $props) =
725 $ra->get_dir(canonicalize_path("."), $svnrev);
726 my $par_mergeinfo = $props->{'svn:mergeinfo'};
727 unless (defined $par_mergeinfo) {
728 $par_mergeinfo = '';
729 }
730 # Merge previous mergeinfo values
731 $aggregate_mergeinfo =
732 merge_merge_info($aggregate_mergeinfo,
733 $par_mergeinfo, 0);
734
735 next if $parent eq $parents[0]; # Skip first parent
736 # Add new changes being placed in tree by merge
737 my @cmd = (qw/rev-list --reverse/,
738 $parent, qw/--not/);
739 foreach my $par (@parents) {
740 unless ($par eq $parent) {
741 push @cmd, $par;
742 }
743 }
744 my @revsin = ();
745 my ($revlist, $ctx) = command_output_pipe(@cmd);
746 while (<$revlist>) {
747 my $irev = $_;
748 chomp $irev;
749 my (undef, $csvnrev, undef) =
750 cmt_metadata($irev);
751 unless (defined $csvnrev) {
752 # A child is missing SVN annotations...
753 # this might be OK, or might not be.
754 warn "W:child $irev is merged into revision "
755 ."$d but does not have git-svn metadata. "
756 ."This means git-svn cannot determine the "
757 ."svn revision numbers to place into the "
758 ."svn:mergeinfo property. You must ensure "
759 ."a branch is entirely committed to "
760 ."SVN before merging it in order for "
761 ."svn:mergeinfo population to function "
762 ."properly";
763 }
764 push @revsin, $csvnrev;
765 }
766 command_close_pipe($revlist, $ctx);
767
768 last unless $all_parents_ok;
769
770 # We now have a list of all SVN revnos which are
771 # merged by this particular parent. Integrate them.
772 next if $#revsin == -1;
773 my $newmergeinfo = "$branchpath:" . join(',', @revsin);
774 $aggregate_mergeinfo =
775 merge_merge_info($aggregate_mergeinfo,
776 $newmergeinfo, 1);
777 }
778 if ($all_parents_ok and $aggregate_mergeinfo) {
779 return $aggregate_mergeinfo;
780 }
781 }
782
783 return undef;
784}
785
d7ad3bed
EW
786sub cmd_dcommit {
787 my $head = shift;
181264ad 788 command_noisy(qw/update-index --refresh/);
c8cfa3e4 789 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 790 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 791 . "or stash them with `git stash'.\n";
d7ad3bed 792 $head ||= 'HEAD';
5eec27e3
TR
793
794 my $old_head;
795 if ($head ne 'HEAD') {
796 $old_head = eval {
797 command_oneline([qw/symbolic-ref -q HEAD/])
798 };
799 if ($old_head) {
800 $old_head =~ s{^refs/heads/}{};
801 } else {
802 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
803 }
804 command(['checkout', $head], STDERR => 0);
805 }
806
a8ae2623 807 my @refs;
5eec27e3 808 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
2cb61105
TR
809 unless ($gs) {
810 die "Unable to determine upstream SVN information from ",
811 "$head history.\nPerhaps the repository is empty.";
812 }
0df84059
PO
813
814 if (defined $_commit_url) {
815 $url = $_commit_url;
816 } else {
817 $url = eval { command_oneline('config', '--get',
818 "svn-remote.$gs->{repo_id}.commiturl") };
819 if (!$url) {
12a296bc 820 $url = $gs->full_pushurl
0df84059
PO
821 }
822 }
823
ba24e745 824 my $last_rev = $_revision if defined $_revision;
59b0c24d
MM
825 if ($url) {
826 print "Committing to $url ...\n";
827 }
733a65aa 828 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
829 if ($_no_rebase && scalar(@$linear_refs) > 1) {
830 warn "Attempting to commit more than one change while ",
831 "--no-rebase is enabled.\n",
832 "If these changes depend on each other, re-running ",
7dfa16b9 833 "without --no-rebase may be required."
751eb395 834 }
afd7f1eb
FH
835
836 if (defined $_interactive){
837 my $ask_default = "y";
838 foreach my $d (@$linear_refs){
839 my ($fh, $ctx) = command_output_pipe(qw(show --summary), "$d");
840 while (<$fh>){
841 print $_;
842 }
843 command_close_pipe($fh, $ctx);
844 $_ = ask("Commit this patch to SVN? ([y]es (default)|[n]o|[q]uit|[a]ll): ",
845 valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
846 default => $ask_default);
847 die "Commit this patch reply required" unless defined $_;
848 if (/^[nq]/i) {
849 exit(0);
850 } elsif (/^a/i) {
851 last;
852 }
853 }
854 }
855
711521e2 856 my $expect_url = $url;
1e5814f3
BJ
857
858 my $push_merge_info = eval {
859 command_oneline(qw/config --get svn.pushmergeinfo/)
860 };
861 if (not defined($push_merge_info)
862 or $push_merge_info eq "false"
863 or $push_merge_info eq "no"
864 or $push_merge_info eq "never") {
865 $push_merge_info = 0;
866 }
867
868 unless (defined($_merge_info) || ! $push_merge_info) {
869 # Preflight check of changes to ensure no issues with mergeinfo
870 # This includes check for uncommitted-to-SVN parents
871 # (other than the first parent, which we will handle),
872 # information from different SVN repos, and paths
873 # which are not underneath this repository root.
874 my $rooturl = $gs->repos_root;
875 foreach my $d (@$linear_refs) {
876 my %parentshash;
877 read_commit_parents(\%parentshash, $d);
878 my @realparents = @{$parentshash{$d}};
879 if ($#realparents > 0) {
880 # Merge commit
881 shift @realparents; # Remove/ignore first parent
882 foreach my $parent (@realparents) {
883 my ($branchurl, $svnrev, $paruuid) = cmt_metadata($parent);
884 unless (defined $paruuid) {
885 # A parent is missing SVN annotations...
886 # abort the whole operation.
887 fatal "$parent is merged into revision $d, "
888 ."but does not have git-svn metadata. "
889 ."Either dcommit the branch or use a "
890 ."local cherry-pick, FF merge, or rebase "
891 ."instead of an explicit merge commit.";
892 }
893
894 unless ($paruuid eq $uuid) {
895 # Parent has SVN metadata from different repository
896 fatal "merge parent $parent for change $d has "
897 ."git-svn uuid $paruuid, while current change "
898 ."has uuid $uuid!";
899 }
900
0e7e30f5 901 unless ($branchurl =~ /^\Q$rooturl\E(.*)/) {
1e5814f3
BJ
902 # This branch is very strange indeed.
903 fatal "merge parent $parent for $d is on branch "
904 ."$branchurl, which is not under the "
905 ."git-svn root $rooturl!";
906 }
907 }
908 }
909 }
910 }
911
912 my $rewritten_parent;
711521e2 913 Git::SVN::remove_username($expect_url);
98c4ab32
BJ
914 if (defined($_merge_info)) {
915 $_merge_info =~ tr{ }{\n};
916 }
c74d9acf
EW
917 while (1) {
918 my $d = shift @$linear_refs or last;
45bf473a
EW
919 unless (defined $last_rev) {
920 (undef, $last_rev, undef) = cmt_metadata("$d~1");
921 unless (defined $last_rev) {
d7ad3bed 922 fatal "Unable to extract revision information ",
207f1a75 923 "from commit $d~1";
45bf473a
EW
924 }
925 }
b22d4497
EW
926 if ($_dry_run) {
927 print "diff-tree $d~1 $d\n";
928 } else {
751eb395 929 my $cmt_rev;
1e5814f3
BJ
930
931 unless (defined($_merge_info) || ! $push_merge_info) {
932 $_merge_info = populate_merge_info($d, $gs,
933 $uuid,
934 $linear_refs,
935 $rewritten_parent);
936 }
937
d7ad3bed 938 my %ed_opts = ( r => $last_rev,
61395354 939 log => get_commit_entry($d)->{log},
ba24e745 940 ra => Git::SVN::Ra->new($url),
3caf320b
KA
941 config => SVN::Core::config_get_config(
942 $Git::SVN::Ra::config_dir
943 ),
61395354
EW
944 tree_a => "$d~1",
945 tree_b => $d,
946 editor_cb => sub {
947 print "Committed r$_[0]\n";
751eb395
EW
948 $cmt_rev = $_[0];
949 },
6abd9332 950 mergeinfo => $_merge_info,
a8ae2623 951 svn_path => '');
72827aa4 952 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 953 print "No changes\n$d~1 == $d\n";
733a65aa 954 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 955 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 956 $parents->{$d};
d7ad3bed 957 }
751eb395 958 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 959 $last_rev = $cmt_rev;
751eb395
EW
960 next if $_no_rebase;
961
962 # we always want to rebase against the current HEAD,
963 # not any head that was passed to us
c74d9acf 964 my @diff = command('diff-tree', $d,
751eb395
EW
965 $gs->refname, '--');
966 my @finish;
967 if (@diff) {
968 @finish = rebase_cmd();
c74d9acf 969 print STDERR "W: $d and ", $gs->refname,
751eb395 970 " differ, using @finish:\n",
c74d9acf 971 join("\n", @diff), "\n";
751eb395
EW
972 } else {
973 print "No changes between current HEAD and ",
974 $gs->refname,
975 "\nResetting to the latest ",
976 $gs->refname, "\n";
977 @finish = qw/reset --mixed/;
978 }
979 command_noisy(@finish, $gs->refname);
1e5814f3
BJ
980
981 $rewritten_parent = command_oneline(qw/rev-parse HEAD/);
982
c74d9acf
EW
983 if (@diff) {
984 @refs = ();
985 my ($url_, $rev_, $uuid_, $gs_) =
5eec27e3 986 working_head_info('HEAD', \@refs);
c74d9acf
EW
987 my ($linear_refs_, $parents_) =
988 linearize_history($gs_, \@refs);
989 if (scalar(@$linear_refs) !=
990 scalar(@$linear_refs_)) {
991 fatal "# of revisions changed ",
992 "\nbefore:\n",
993 join("\n", @$linear_refs),
994 "\n\nafter:\n",
995 join("\n", @$linear_refs_), "\n",
996 'If you are attempting to commit ',
997 "merges, try running:\n\t",
998 'git rebase --interactive',
999 '--preserve-merges ',
1000 $gs->refname,
1001 "\nBefore dcommitting";
1002 }
711521e2 1003 if ($url_ ne $expect_url) {
c03c1f79
AG
1004 if ($url_ eq $gs->metadata_url) {
1005 print
1006 "Accepting rewritten URL:",
1007 " $url_\n";
1008 } else {
1009 fatal
1010 "URL mismatch after rebase:",
1011 " $url_ != $expect_url";
1012 }
c74d9acf
EW
1013 }
1014 if ($uuid_ ne $uuid) {
1015 fatal "uuid mismatch after rebase: ",
1016 "$uuid_ != $uuid";
1017 }
1018 # remap parents
1019 my (%p, @l, $i);
1020 for ($i = 0; $i < scalar @$linear_refs; $i++) {
1021 my $new = $linear_refs_->[$i] or next;
1022 $p{$new} =
1023 $parents->{$linear_refs->[$i]};
1024 push @l, $new;
1025 }
1026 $parents = \%p;
1027 $linear_refs = \@l;
1028 }
b22d4497
EW
1029 }
1030 }
5eec27e3
TR
1031
1032 if ($old_head) {
1033 my $new_head = command_oneline(qw/rev-parse HEAD/);
1034 my $new_is_symbolic = eval {
1035 command_oneline(qw/symbolic-ref -q HEAD/);
1036 };
1037 if ($new_is_symbolic) {
1038 print "dcommitted the branch ", $head, "\n";
1039 } else {
1040 print "dcommitted on a detached HEAD because you gave ",
1041 "a revision argument.\n",
1042 "The rewritten commit is: ", $new_head, "\n";
1043 }
1044 command(['checkout', $old_head], STDERR => 0);
1045 }
1046
3157dd9e 1047 unlink $gs->{index};
b22d4497
EW
1048}
1049
5de70efb
FR
1050sub cmd_branch {
1051 my ($branch_name, $head) = @_;
1052
1053 unless (defined $branch_name && length $branch_name) {
1054 die(($_tag ? "tag" : "branch") . " name required\n");
1055 }
1056 $head ||= 'HEAD';
1057
150d38c4 1058 my (undef, $rev, undef, $gs) = working_head_info($head);
12a296bc 1059 my $src = $gs->full_pushurl;
5de70efb 1060
a0fbc87c 1061 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
62244069
MB
1062 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
1063 my $glob;
1064 if ($#{$allglobs} == 0) {
1065 $glob = $allglobs->[0];
1066 } else {
1067 unless(defined $_branch_dest) {
1068 die "Multiple ",
1069 $_tag ? "tag" : "branch",
1070 " paths defined for Subversion repository.\n",
1071 "You must specify where you want to create the ",
1072 $_tag ? "tag" : "branch",
1073 " with the --destination argument.\n";
1074 }
1075 foreach my $g (@{$allglobs}) {
72827aa4 1076 my $re = Git::SVN::Editor::glob2pat($g->{path}->{left});
f7050599 1077 if ($_branch_dest =~ /$re/) {
62244069
MB
1078 $glob = $g;
1079 last;
1080 }
1081 }
1082 unless (defined $glob) {
eaa14ff8
EW
1083 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
1084 foreach my $g (@{$allglobs}) {
1085 $g->{path}->{left} =~ /$dest_re/ or next;
1086 if (defined $glob) {
1087 die "Ambiguous destination: ",
1088 $_branch_dest, "\nmatches both '",
1089 $glob->{path}->{left}, "' and '",
1090 $g->{path}->{left}, "'\n";
1091 }
1092 $glob = $g;
1093 }
1094 unless (defined $glob) {
1095 die "Unknown ",
1096 $_tag ? "tag" : "branch",
1097 " destination $_branch_dest\n";
1098 }
62244069
MB
1099 }
1100 }
5de70efb 1101 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
99bacd6c
IM
1102 my $url;
1103 if (defined $_commit_url) {
1104 $url = $_commit_url;
1105 } else {
1106 $url = eval { command_oneline('config', '--get',
1107 "svn-remote.$gs->{repo_id}.commiturl") };
1108 if (!$url) {
12a296bc 1109 $url = $remote->{pushurl} || $remote->{url};
99bacd6c
IM
1110 }
1111 }
1112 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
5de70efb 1113
a83b91e7
IM
1114 if ($dst =~ /^https:/ && $src =~ /^http:/) {
1115 $src=~s/^http:/https:/;
1116 }
1117
d32fad2b 1118 ::_req_svn();
1119
5de70efb
FR
1120 my $ctx = SVN::Client->new(
1121 auth => Git::SVN::Ra::_auth_providers(),
1122 log_msg => sub {
1123 ${ $_[0] } = defined $_message
1124 ? $_message
1125 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
1126 . $branch_name;
1127 },
1128 );
1129
1130 eval {
1131 $ctx->ls($dst, 'HEAD', 0);
1132 } and die "branch ${branch_name} already exists\n";
1133
1134 print "Copying ${src} at r${rev} to ${dst}...\n";
1135 $ctx->copy($src, $rev, $dst)
1136 unless $_dry_run;
1137
1138 $gs->fetch_all;
1139}
1140
26e60160 1141sub cmd_find_rev {
ea14e6c5
MAL
1142 my $revision_or_hash = shift or die "SVN or git revision required ",
1143 "as a command-line argument\n";
26e60160
AR
1144 my $result;
1145 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
1146 my $head = shift;
1147 $head ||= 'HEAD';
1148 my @refs;
63c56022 1149 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
b3cb7e45
AR
1150 unless ($gs) {
1151 die "Unable to determine upstream SVN information from ",
1152 "$head history\n";
26e60160 1153 }
b3cb7e45 1154 my $desired_revision = substr($revision_or_hash, 1);
63c56022 1155 $result = $gs->rev_map_get($desired_revision, $uuid);
26e60160
AR
1156 } else {
1157 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
1158 $result = $rev;
1159 }
1160 print "$result\n" if $result;
1161}
1162
55f9d7a7
MH
1163sub auto_create_empty_directories {
1164 my ($gs) = @_;
1165 my $var = eval { command_oneline('config', '--get', '--bool',
1166 "svn-remote.$gs->{repo_id}.automkdirs") };
1167 # By default, create empty directories by consulting the unhandled log,
1168 # but allow setting it to 'false' to skip it.
1169 return !($var && $var eq 'false');
1170}
1171
905f8b7d
EW
1172sub cmd_rebase {
1173 command_noisy(qw/update-index --refresh/);
13c823fb
EW
1174 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1175 unless ($gs) {
905f8b7d
EW
1176 die "Unable to determine upstream SVN information from ",
1177 "working tree history\n";
1178 }
7d45e146
SF
1179 if ($_dry_run) {
1180 print "Remote Branch: " . $gs->refname . "\n";
1181 print "SVN URL: " . $url . "\n";
1182 return;
1183 }
905f8b7d
EW
1184 if (command(qw/diff-index HEAD --/)) {
1185 print STDERR "Cannot rebase with uncommited changes:\n";
1186 command_noisy('status');
1187 exit 1;
1188 }
dee41f3e 1189 unless ($_local) {
cec0d5a3
SG
1190 # rebase will checkout for us, so no need to do it explicitly
1191 $_no_checkout = 'true';
dee41f3e
EW
1192 $_fetch_all ? $gs->fetch_all : $gs->fetch;
1193 }
905f8b7d 1194 command_noisy(rebase_cmd(), $gs->refname);
55f9d7a7
MH
1195 if (auto_create_empty_directories($gs)) {
1196 $gs->mkemptydirs;
1197 }
905f8b7d
EW
1198}
1199
5969cbe1 1200sub cmd_show_ignore {
13c823fb
EW
1201 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1202 $gs ||= Git::SVN->new;
5969cbe1 1203 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
6a8d999e 1204 $gs->prop_walk($gs->path, $r, sub {
01bdab84
BS
1205 my ($gs, $path, $props) = @_;
1206 print STDOUT "\n# $path\n";
1207 my $s = $props->{'svn:ignore'} or return;
1208 $s =~ s/[\r\n]+/\n/g;
a7d72544 1209 $s =~ s/^\n+//;
01bdab84
BS
1210 chomp $s;
1211 $s =~ s#^#$path#gm;
1212 print STDOUT "$s\n";
1213 });
a5e0cedc
EW
1214}
1215
2d879792
VK
1216sub cmd_show_externals {
1217 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1218 $gs ||= Git::SVN->new;
1219 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
6a8d999e 1220 $gs->prop_walk($gs->path, $r, sub {
2d879792
VK
1221 my ($gs, $path, $props) = @_;
1222 print STDOUT "\n# $path\n";
1223 my $s = $props->{'svn:externals'} or return;
1224 $s =~ s/[\r\n]+/\n/g;
1225 chomp $s;
1226 $s =~ s#^#$path#gm;
1227 print STDOUT "$s\n";
1228 });
1229}
1230
d05ddec5
BS
1231sub cmd_create_ignore {
1232 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1233 $gs ||= Git::SVN->new;
1234 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
6a8d999e 1235 $gs->prop_walk($gs->path, $r, sub {
d05ddec5
BS
1236 my ($gs, $path, $props) = @_;
1237 # $path is of the form /path/to/dir/
7d9fd459
BG
1238 $path = '.' . $path;
1239 # SVN can have attributes on empty directories,
1240 # which git won't track
1241 mkpath([$path]) unless -d $path;
1242 my $ignore = $path . '.gitignore';
d05ddec5
BS
1243 my $s = $props->{'svn:ignore'} or return;
1244 open(GITIGNORE, '>', $ignore)
207f1a75 1245 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5 1246 $s =~ s/[\r\n]+/\n/g;
a7d72544 1247 $s =~ s/^\n+//;
d05ddec5
BS
1248 chomp $s;
1249 # Prefix all patterns so that the ignore doesn't apply
1250 # to sub-directories.
1251 $s =~ s#^#/#gm;
1252 print GITIGNORE "$s\n";
1253 close(GITIGNORE)
207f1a75 1254 or fatal("Failed to close `$ignore': $!");
c4c66b26 1255 command_noisy('add', '-f', $ignore);
d05ddec5
BS
1256 });
1257}
1258
6111b934
EW
1259sub cmd_mkdirs {
1260 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1261 $gs ||= Git::SVN->new;
1262 $gs->mkemptydirs($_revision);
1263}
1264
15153451
BS
1265# get_svnprops(PATH)
1266# ------------------
51e057cf 1267# Helper for cmd_propget and cmd_proplist below.
15153451
BS
1268sub get_svnprops {
1269 my $path = shift;
1270 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1271 $gs ||= Git::SVN->new;
1272
1273 # prefix THE PATH by the sub-directory from which the user
1274 # invoked us.
1275 $path = $cmd_dir_prefix . $path;
207f1a75 1276 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
1277 my $is_dir = -d $path ? 1 : 0;
1278 $path = $gs->{path} . '/' . $path;
1279
1280 # canonicalize the path (otherwise libsvn will abort or fail to
1281 # find the file)
b2b3ada7 1282 $path = canonicalize_path($path);
15153451
BS
1283
1284 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
1285 my $props;
1286 if ($is_dir) {
1287 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
1288 }
1289 else {
1290 (undef, $props) = $gs->ra->get_file($path, $r, undef);
1291 }
1292 return $props;
1293}
1294
1295# cmd_propget (PROP, PATH)
1296# ------------------------
1297# Print the SVN property PROP for PATH.
1298sub cmd_propget {
1299 my ($prop, $path) = @_;
1300 $path = '.' if not defined $path;
1301 usage(1) if not defined $prop;
1302 my $props = get_svnprops($path);
1303 if (not defined $props->{$prop}) {
207f1a75 1304 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
1305 }
1306 print $props->{$prop} . "\n";
1307}
1308
51e057cf
BS
1309# cmd_proplist (PATH)
1310# -------------------
1311# Print the list of SVN properties for PATH.
1312sub cmd_proplist {
1313 my $path = shift;
1314 $path = '.' if not defined $path;
1315 my $props = get_svnprops($path);
1316 print "Properties on '$path':\n";
1317 foreach (sort keys %{$props}) {
1318 print " $_\n";
1319 }
1320}
1321
8164b652 1322sub cmd_multi_init {
9d55b41a 1323 my $url = shift;
62244069 1324 unless (defined $_trunk || @_branches || @_tags) {
98327e58 1325 usage(1);
9d55b41a 1326 }
dc431666 1327
8164b652 1328 $_prefix = '' unless defined $_prefix;
dadc6d2a 1329 if (defined $url) {
50ff2366 1330 $url = canonicalize_url($url);
dadc6d2a
EW
1331 init_subdir(@_);
1332 }
f30603fc 1333 do_git_init_db();
98327e58 1334 if (defined $_trunk) {
b4b33600 1335 $_trunk =~ s#^/+##;
6f5748e1 1336 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
706587fc
EW
1337 # try both old-style and new-style lookups:
1338 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 1339 unless ($gs_trunk) {
706587fc
EW
1340 my ($trunk_url, $trunk_path) =
1341 complete_svn_url($url, $_trunk);
1342 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
1343 undef, $trunk_ref);
98327e58 1344 }
c35b96e7 1345 }
62244069 1346 return unless @_branches || @_tags;
e7db67e6 1347 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
62244069
MB
1348 foreach my $path (@_branches) {
1349 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
1350 }
1351 foreach my $path (@_tags) {
1352 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
1353 }
9d55b41a
EW
1354}
1355
1c8443b0 1356sub cmd_multi_fetch {
4d0157d6 1357 $Git::SVN::no_reuse_existing = undef;
0af9c9f9
EW
1358 my $remotes = Git::SVN::read_all_remotes();
1359 foreach my $repo_id (sort keys %$remotes) {
db03cd24 1360 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
1361 Git::SVN::fetch_all($repo_id, $remotes);
1362 }
9d55b41a 1363 }
9d55b41a
EW
1364}
1365
44320b9e
EW
1366# this command is special because it requires no metadata
1367sub cmd_commit_diff {
1368 my ($ta, $tb, $url) = @_;
1369 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 1370 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 1371 fatal($usage) if (!defined $ta || !defined $tb);
d72ab8c8 1372 my $svn_path = '';
44320b9e
EW
1373 if (!defined $url) {
1374 my $gs = eval { Git::SVN->new };
1375 if (!$gs) {
1376 fatal("Needed URL or usable git-svn --id in ",
1377 "the command-line\n", $usage);
1378 }
b1ea6c38 1379 $url = $gs->url;
6a8d999e 1380 $svn_path = $gs->path;
44320b9e
EW
1381 }
1382 unless (defined $_revision) {
1383 fatal("-r|--revision is a required argument\n", $usage);
1384 }
1385 if (defined $_message && defined $_file) {
1386 fatal("Both --message/-m and --file/-F specified ",
1387 "for the commit message.\n",
207f1a75 1388 "I have no idea what you mean");
44320b9e
EW
1389 }
1390 if (defined $_file) {
1391 $_message = file_to_s($_file);
1392 } else {
1393 $_message ||= get_commit_entry($tb)->{log};
1394 }
1395 my $ra ||= Git::SVN::Ra->new($url);
1396 my $r = $_revision;
1397 if ($r eq 'HEAD') {
1398 $r = $ra->get_latest_revnum;
1399 } elsif ($r !~ /^\d+$/) {
1400 die "revision argument: $r not understood by git-svn\n";
1401 }
61395354
EW
1402 my %ed_opts = ( r => $r,
1403 log => $_message,
1404 ra => $ra,
1405 tree_a => $ta,
1406 tree_b => $tb,
1407 editor_cb => sub { print "Committed r$_[0]\n" },
1408 svn_path => $svn_path );
72827aa4 1409 if (!Git::SVN::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
1410 print "No changes\n$ta == $tb\n";
1411 }
44320b9e
EW
1412}
1413
05427b91
TR
1414sub escape_uri_only {
1415 my ($uri) = @_;
1416 my @tmp;
1417 foreach (split m{/}, $uri) {
6a004d3f 1418 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
05427b91
TR
1419 push @tmp, $_;
1420 }
1421 join('/', @tmp);
1422}
1423
1424sub escape_url {
1425 my ($url) = @_;
1426 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1427 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1428 $url = "$scheme://$domain$uri";
1429 }
1430 $url;
1431}
1432
e6fefa92 1433sub cmd_info {
bd2d4f96 1434 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
edde9112 1435 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
bd2d4f96 1436 if (exists $_[1]) {
e6fefa92
DK
1437 die "Too many arguments specified\n";
1438 }
1439
1440 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1441
1442 if (!$file_type && !$diff_status) {
2cf3e3ac
TR
1443 print STDERR "svn: '$path' is not under version control\n";
1444 exit 1;
e6fefa92
DK
1445 }
1446
1447 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1448 unless ($gs) {
1449 die "Unable to determine upstream SVN information from ",
1450 "working tree history\n";
1451 }
bd2d4f96
EW
1452
1453 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1454 $path = "." if $path eq "";
1455
edde9112 1456 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
e6fefa92 1457
8b014d71 1458 if ($_url) {
05427b91 1459 print escape_url($full_url), "\n";
8b014d71
DK
1460 return;
1461 }
1462
e6fefa92
DK
1463 my $result = "Path: $path\n";
1464 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
05427b91 1465 $result .= "URL: " . escape_url($full_url) . "\n";
e6fefa92 1466
a5460eb7
EW
1467 eval {
1468 my $repos_root = $gs->repos_root;
1469 Git::SVN::remove_username($repos_root);
05427b91 1470 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
a5460eb7
EW
1471 };
1472 if ($@) {
1473 $result .= "Repository Root: (offline)\n";
1474 }
b91a8a3e 1475 ::_req_svn();
22ba47f5 1476 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
f760c903 1477 (::compare_svn_version('1.5.4') <= 0 || $file_type ne "dir");
e6fefa92
DK
1478 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1479
1480 $result .= "Node Kind: " .
1481 ($file_type eq "dir" ? "directory" : "file") . "\n";
1482
1483 my $schedule = $diff_status eq "A"
1484 ? "add"
1485 : ($diff_status eq "D" ? "delete" : "normal");
1486 $result .= "Schedule: $schedule\n";
1487
1488 if ($diff_status eq "A") {
1489 print $result, "\n";
1490 return;
1491 }
1492
1493 my ($lc_author, $lc_rev, $lc_date_utc);
edde9112 1494 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
e6fefa92
DK
1495 my $log = command_output_pipe(@args);
1496 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1497 while (<$log>) {
1498 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1499 $lc_author = $1;
1500 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1501 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1502 (undef, $lc_rev, undef) = ::extract_metadata($1);
1503 }
1504 }
1505 close $log;
1506
1507 Git::SVN::Log::set_local_timezone();
1508
1509 $result .= "Last Changed Author: $lc_author\n";
1510 $result .= "Last Changed Rev: $lc_rev\n";
1511 $result .= "Last Changed Date: " .
1512 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1513
1514 if ($file_type ne "dir") {
1515 my $text_last_updated_date =
1516 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1517 $result .=
1518 "Text Last Updated: " .
1519 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1520 "\n";
1521 my $checksum;
1522 if ($diff_status eq "D") {
1523 my ($fh, $ctx) =
1524 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1525 if ($file_type eq "link") {
1526 my $file_name = <$fh>;
8d7c4fad 1527 $checksum = md5sum("link $file_name");
e6fefa92 1528 } else {
8d7c4fad 1529 $checksum = md5sum($fh);
e6fefa92
DK
1530 }
1531 command_close_pipe($fh, $ctx);
1532 } elsif ($file_type eq "link") {
1533 my $file_name =
1534 command(qw(cat-file blob), "HEAD:$path");
1535 $checksum =
8d7c4fad 1536 md5sum("link " . $file_name);
e6fefa92
DK
1537 } else {
1538 open FILE, "<", $path or die $!;
8d7c4fad 1539 $checksum = md5sum(\*FILE);
e6fefa92
DK
1540 close FILE or die $!;
1541 }
1542 $result .= "Checksum: " . $checksum . "\n";
1543 }
1544
1545 print $result, "\n";
1546}
1547
195643f2
BJ
1548sub cmd_reset {
1549 my $target = shift || $_revision or die "SVN revision required\n";
1550 $target = $1 if $target =~ /^r(\d+)$/;
1551 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1552 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1553 unless ($gs) {
1554 die "Unable to determine upstream SVN information from ".
1555 "history\n";
1556 }
1557 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
70ee0b77 1558 die "Cannot find SVN revision $target\n" unless defined($c);
195643f2
BJ
1559 $gs->rev_map_set($r, $c, 'reset', $uuid);
1560 print "r$r = $c ($gs->{ref_id})\n";
1561}
1562
2da9ee08 1563sub cmd_gc {
c2768fa1 1564 if (!can_compress()) {
2da9ee08
RZ
1565 warn "Compress::Zlib could not be found; unhandled.log " .
1566 "files will not be compressed.\n";
1567 }
1568 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1569}
1570
3397f9df
EW
1571########################### utility functions #########################
1572
905f8b7d
EW
1573sub rebase_cmd {
1574 my @cmd = qw/rebase/;
1575 push @cmd, '-v' if $_verbose;
1576 push @cmd, qw/--merge/ if $_merge;
1577 push @cmd, "--strategy=$_strategy" if $_strategy;
b64e1f58 1578 push @cmd, "--preserve-merges" if $_preserve_merges;
905f8b7d
EW
1579 @cmd;
1580}
1581
1e889ef3
EW
1582sub post_fetch_checkout {
1583 return if $_no_checkout;
e3bd4dda 1584 return if verify_ref('HEAD^0');
1e889ef3 1585 my $gs = $Git::SVN::_head or return;
1e889ef3 1586
b186a261
EW
1587 # look for "trunk" ref if it exists
1588 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1589 my $fetch = $remote->{fetch};
1590 if ($fetch) {
1591 foreach my $p (keys %$fetch) {
1592 basename($fetch->{$p}) eq 'trunk' or next;
1593 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1594 last;
1595 }
1596 }
1597
e3bd4dda
MO
1598 command_noisy(qw(update-ref HEAD), $gs->refname);
1599 return unless verify_ref('HEAD^0');
1e889ef3
EW
1600
1601 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1602 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1603 return if -f $index;
1604
7ae3df8c 1605 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
1606 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1607 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1608 print STDERR "Checked out HEAD:\n ",
1609 $gs->full_url, " r", $gs->last_rev, "\n";
55f9d7a7
MH
1610 if (auto_create_empty_directories($gs)) {
1611 $gs->mkemptydirs($gs->last_rev);
1612 }
1e889ef3
EW
1613}
1614
98327e58
EW
1615sub complete_svn_url {
1616 my ($url, $path) = @_;
1617 $path =~ s#/+$##;
6a8d999e
MS
1618
1619 # If the path is not a URL...
98327e58 1620 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
1621 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1622 fatal("E: '$path' is not a complete URL ",
207f1a75 1623 "and a separate URL is not specified");
98327e58 1624 }
706587fc 1625 return ($url, $path);
98327e58 1626 }
706587fc 1627 return ($path, '');
98327e58
EW
1628}
1629
9d55b41a 1630sub complete_url_ls_init {
706587fc
EW
1631 my ($ra, $repo_path, $switch, $pfx) = @_;
1632 unless ($repo_path) {
9d55b41a
EW
1633 print STDERR "W: $switch not specified\n";
1634 return;
1635 }
706587fc
EW
1636 $repo_path =~ s#/+$##;
1637 if ($repo_path =~ m#^[a-z\+]+://#) {
1638 $ra = Git::SVN::Ra->new($repo_path);
1639 $repo_path = '';
e7db67e6 1640 } else {
706587fc 1641 $repo_path =~ s#^/+##;
e7db67e6 1642 unless ($ra) {
706587fc 1643 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 1644 "and a separate URL is not specified");
8164b652 1645 }
e7db67e6 1646 }
b1ea6c38 1647 my $url = $ra->url;
b4d57e5e
EW
1648 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1649 my $k = "svn-remote.$gs->{repo_id}.url";
1650 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
b1ea6c38 1651 if ($orig_url && ($orig_url ne $gs->url)) {
b4d57e5e 1652 die "$k already set: $orig_url\n",
b1ea6c38 1653 "wanted to set to: $gs->url\n";
88cf4107 1654 }
b1ea6c38
MS
1655 command_oneline('config', $k, $gs->url) unless $orig_url;
1656
6a8d999e 1657 my $remote_path = $gs->path . "/$repo_path";
5268f9ed 1658 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
b4d57e5e
EW
1659 $remote_path =~ s#/+#/#g;
1660 $remote_path =~ s#^/##g;
ed0b9d43 1661 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
1662 my ($n) = ($switch =~ /^--(\w+)/);
1663 if (length $pfx && $pfx !~ m#/$#) {
1664 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 1665 }
570d35c2 1666 command_noisy('config',
62244069 1667 '--add',
570d35c2
MG
1668 "svn-remote.$gs->{repo_id}.$n",
1669 "$remote_path:refs/remotes/$pfx*" .
1670 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
9d55b41a
EW
1671}
1672
aef4e921
EW
1673sub verify_ref {
1674 my ($ref) = @_;
2c5c1d53
EW
1675 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1676 { STDERR => 0 }); };
aef4e921
EW
1677}
1678
a5e0cedc 1679sub get_tree_from_treeish {
cf52b8f0 1680 my ($treeish) = @_;
44320b9e 1681 # $treeish can be a symbolic ref, too:
aef4e921 1682 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
1683 my $expected;
1684 while ($type eq 'tag') {
aef4e921 1685 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
1686 }
1687 if ($type eq 'commit') {
aef4e921
EW
1688 $expected = (grep /^tree /, command(qw/cat-file commit/,
1689 $treeish))[0];
44320b9e 1690 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
1691 die "Unable to get tree from $treeish\n" unless $expected;
1692 } elsif ($type eq 'tree') {
1693 $expected = $treeish;
1694 } else {
1695 die "$treeish is a $type, expected tree, tag or commit\n";
1696 }
a5e0cedc
EW
1697 return $expected;
1698}
1699
44320b9e
EW
1700sub get_commit_entry {
1701 my ($treeish) = shift;
1702 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1703 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1704 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1705 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1706
44320b9e 1707 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1708 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1709 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1710 $type, $treeish);
3397f9df 1711 my $in_msg = 0;
6aa9ba14
AP
1712 my $author;
1713 my $saw_from = 0;
328eb9b3 1714 my $msgbuf = "";
3397f9df
EW
1715 while (<$msg_fh>) {
1716 if (!$in_msg) {
1717 $in_msg = 1 if (/^\s*$/);
6aa9ba14 1718 $author = $1 if (/^author (.*>)/);
df746c5a 1719 } elsif (/^git-svn-id: /) {
44320b9e
EW
1720 # skip this for now, we regenerate the
1721 # correct one on re-fetch anyways
1722 # TODO: set *:merge properties or like...
3397f9df 1723 } else {
6aa9ba14
AP
1724 if (/^From:/ || /^Signed-off-by:/) {
1725 $saw_from = 1;
1726 }
328eb9b3 1727 $msgbuf .= $_;
3397f9df
EW
1728 }
1729 }
328eb9b3 1730 $msgbuf =~ s/\s+$//s;
6aa9ba14
AP
1731 if ($Git::SVN::_add_author_from && defined($author)
1732 && !$saw_from) {
328eb9b3 1733 $msgbuf .= "\n\nFrom: $author";
6aa9ba14 1734 }
328eb9b3 1735 print $log_fh $msgbuf or croak $!;
aef4e921 1736 command_close_pipe($msg_fh, $ctx);
3397f9df 1737 }
44320b9e 1738 close $log_fh or croak $!;
3397f9df
EW
1739
1740 if ($_edit || ($type eq 'tree')) {
b4479f07
JN
1741 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1742 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
3397f9df 1743 }
44320b9e 1744 rename $commit_editmsg, $commit_msg or croak $!;
16fc08e2 1745 {
b510df8a 1746 require Encode;
16fc08e2
EW
1747 # SVN requires messages to be UTF-8 when entering the repo
1748 local $/;
1749 open $log_fh, '<', $commit_msg or croak $!;
1750 binmode $log_fh;
1751 chomp($log_entry{log} = <$log_fh>);
1752
b510df8a
EW
1753 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1754 my $msg = $log_entry{log};
1755
1756 eval { $msg = Encode::decode($enc, $msg, 1) };
1757 if ($@) {
1758 die "Could not decode as $enc:\n", $msg,
1759 "\nPerhaps you need to set i18n.commitencoding\n";
16fc08e2 1760 }
b510df8a
EW
1761
1762 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1763 die "Could not encode as UTF-8:\n$msg\n" if $@;
1764
1765 $log_entry{log} = $msg;
1766
16fc08e2
EW
1767 close $log_fh or croak $!;
1768 }
44320b9e
EW
1769 unlink $commit_msg;
1770 \%log_entry;
a5e0cedc
EW
1771}
1772
3397f9df
EW
1773sub s_to_file {
1774 my ($str, $file, $mode) = @_;
1775 open my $fd,'>',$file or croak $!;
1776 print $fd $str,"\n" or croak $!;
1777 close $fd or croak $!;
1778 chmod ($mode &~ umask, $file) if (defined $mode);
1779}
1780
1781sub file_to_s {
1782 my $file = shift;
1783 open my $fd,'<',$file or croak "$!: file: $file\n";
1784 local $/;
1785 my $ret = <$fd>;
1786 close $fd or croak $!;
1787 $ret =~ s/\s*$//s;
1788 return $ret;
1789}
1790
eeb0abe0
EW
1791# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1792sub load_authors {
1793 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1794 my $log = $cmd eq 'log';
eeb0abe0
EW
1795 while (<$authors>) {
1796 chomp;
575d025c 1797 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1798 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1799 if ($log) {
1800 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1801 } else {
1802 $users{$user} = [$name, $email];
1803 }
79bb8d88
EW
1804 }
1805 close $authors or croak $!;
1806}
1807
e0d10e1c 1808# convert GetOpt::Long specs for use by git-config
1a30582b 1809sub read_git_config {
b8c92cad 1810 my $opts = shift;
97ae0911 1811 my @config_only;
b8c92cad 1812 foreach my $o (keys %$opts) {
97ae0911
EW
1813 # if we have mixedCase and a long option-only, then
1814 # it's a config-only variable that we don't need for
1815 # the command-line.
1816 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1817 my $v = $opts->{$o};
97ae0911 1818 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1819 $key =~ s/-//g;
225f1d0c 1820 my $arg = 'git config';
b8c92cad
EW
1821 $arg .= ' --int' if ($o =~ /[:=]i$/);
1822 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1823 if (ref $v eq 'ARRAY') {
1824 chomp(my @tmp = `$arg --get-all svn.$key`);
1825 @$v = @tmp if @tmp;
1826 } else {
1827 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1828 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1829 $$v = $tmp;
1830 }
1831 }
1832 }
97ae0911 1833 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1834}
1835
79bb8d88 1836sub extract_metadata {
c1927a85 1837 my $id = shift or return (undef, undef, undef);
3dfab993 1838 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
b3e95936 1839 \s([a-f\d\-]+)$/ix);
e70dc780 1840 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1841 # some of the original repositories I made had
82e5a82f 1842 # identifiers like this:
b3e95936 1843 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
79bb8d88
EW
1844 }
1845 return ($url, $rev, $uuid);
1846}
1847
c1927a85
EW
1848sub cmt_metadata {
1849 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1850 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1851}
1852
6ea42032
BB
1853sub cmt_sha2rev_batch {
1854 my %s2r;
1855 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1856 my $list = shift;
1857
1858 foreach my $sha (@{$list}) {
1859 my $first = 1;
1860 my $size = 0;
1861 print $out $sha, "\n";
1862
1863 while (my $line = <$in>) {
1864 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1865 last;
1866 } elsif ($first &&
1867 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1868 $first = 0;
1869 $size = $1;
1870 next;
1871 } elsif ($line =~ /^(git-svn-id: )/) {
1872 my (undef, $rev, undef) =
1873 extract_metadata($line);
1874 $s2r{$sha} = $rev;
1875 }
1876
1877 $size -= length($line);
1878 last if ($size == 0);
1879 }
1880 }
1881
1882 command_close_bidi_pipe($pid, $in, $out, $ctx);
1883
1884 return \%s2r;
1885}
1886
905f8b7d
EW
1887sub working_head_info {
1888 my ($head, $refs) = @_;
83cf21f9 1889 my @args = qw/rev-list --first-parent --pretty=medium/;
05b4df31 1890 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1891 my $hash;
40cb8f8f 1892 my %max;
3dfab993
SV
1893 while (<$fh>) {
1894 if ( m{^commit ($::sha1)$} ) {
1895 unshift @$refs, $hash if $hash and $refs;
1896 $hash = $1;
1897 next;
1898 }
1899 next unless s{^\s*(git-svn-id:)}{$1};
1900 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1901 if (defined $url && defined $rev) {
40cb8f8f 1902 next if $max{$url} and $max{$url} < $rev;
13c823fb 1903 if (my $gs = Git::SVN->find_by_url($url)) {
63c56022 1904 my $c = $gs->rev_map_get($rev, $uuid);
b03c7a63 1905 if ($c && $c eq $hash) {
13c823fb
EW
1906 close $fh; # break the pipe
1907 return ($url, $rev, $uuid, $gs);
40cb8f8f 1908 } else {
060610c5 1909 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1910 }
1911 }
1912 }
905f8b7d 1913 }
13c823fb
EW
1914 command_close_pipe($fh, $ctx);
1915 (undef, undef, undef, undef);
905f8b7d
EW
1916}
1917
733a65aa
EW
1918sub read_commit_parents {
1919 my ($parents, $c) = @_;
7b02b85a
EW
1920 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1921 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1922 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1923}
1924
1925sub linearize_history {
1926 my ($gs, $refs) = @_;
1927 my %parents;
1928 foreach my $c (@$refs) {
1929 read_commit_parents(\%parents, $c);
1930 }
1931
1932 my @linear_refs;
1933 my %skip = ();
1934 my $last_svn_commit = $gs->last_commit;
1935 foreach my $c (reverse @$refs) {
1936 next if $c eq $last_svn_commit;
1937 last if $skip{$c};
1938
1939 unshift @linear_refs, $c;
1940 $skip{$c} = 1;
1941
1942 # we only want the first parent to diff against for linear
1943 # history, we save the rest to inject when we finalize the
1944 # svn commit
1945 my $fp_a = verify_ref("$c~1");
1946 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1947 if (!$fp_a || !$fp_b) {
1948 die "Commit $c\n",
1949 "has no parent commit, and therefore ",
1950 "nothing to diff against.\n",
1951 "You should be working from a repository ",
1952 "originally created by git-svn\n";
1953 }
1954 if ($fp_a ne $fp_b) {
1955 die "$c~1 = $fp_a, however parsing commit $c ",
1956 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1957 }
1958
1959 foreach my $p (@{$parents{$c}}) {
1960 $skip{$p} = 1;
1961 }
1962 }
1963 (\@linear_refs, \%parents);
1964}
1965
e6fefa92
DK
1966sub find_file_type_and_diff_status {
1967 my ($path) = @_;
107cee50 1968 return ('dir', '') if $path eq '';
e6fefa92
DK
1969
1970 my $diff_output =
1971 command_oneline(qw(diff --cached --name-status --), $path) || "";
1972 my $diff_status = (split(' ', $diff_output))[0] || "";
1973
1974 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1975
1976 return (undef, undef) if !$diff_status && !$ls_tree;
1977
1978 if ($diff_status eq "A") {
1979 return ("link", $diff_status) if -l $path;
1980 return ("dir", $diff_status) if -d $path;
1981 return ("file", $diff_status);
1982 }
1983
1984 my $mode = (split(' ', $ls_tree))[0] || "";
1985
1986 return ("link", $diff_status) if $mode eq "120000";
1987 return ("dir", $diff_status) if $mode eq "040000";
1988 return ("file", $diff_status);
1989}
1990
b2b3ada7
DK
1991sub md5sum {
1992 my $arg = shift;
1993 my $ref = ref $arg;
1994 my $md5 = Digest::MD5->new();
0b19138b 1995 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
b2b3ada7
DK
1996 $md5->addfile($arg) or croak $!;
1997 } elsif ($ref eq 'SCALAR') {
1998 $md5->add($$arg) or croak $!;
1999 } elsif (!$ref) {
2000 $md5->add($arg) or croak $!;
2001 } else {
c2768fa1 2002 fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
b2b3ada7
DK
2003 }
2004 return $md5->hexdigest();
2005}
2006
2da9ee08 2007sub gc_directory {
c2768fa1 2008 if (can_compress() && -f $_ && basename($_) eq "unhandled.log") {
2da9ee08
RZ
2009 my $out_filename = $_ . ".gz";
2010 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
2011 binmode $in_fh;
2012 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
2013 die "Unable to open $out_filename: $!\n";
2014
2015 my $res;
2016 while ($res = sysread($in_fh, my $str, 1024)) {
2017 $gz->gzwrite($str) or
2018 die "Unable to write: ".$gz->gzerror()."!\n";
2019 }
2020 unlink $_ or die "unlink $File::Find::name: $!\n";
2021 } elsif (-f $_ && basename($_) eq "index") {
2022 unlink $_ or die "unlink $_: $!\n";
2023 }
2024}
2025
3397f9df
EW
2026__END__
2027
2028Data structures:
2029
4bb9ed04
EW
2030
2031$remotes = { # returned by read_all_remotes()
2032 'svn' => {
2033 # svn-remote.svn.url=https://svn.musicpd.org
2034 url => 'https://svn.musicpd.org',
2035 # svn-remote.svn.fetch=mpd/trunk:trunk
2036 fetch => {
2037 'mpd/trunk' => 'trunk',
2038 },
2039 # svn-remote.svn.tags=mpd/tags/*:tags/*
2040 tags => {
2041 path => {
2042 left => 'mpd/tags',
2043 right => '',
2044 regex => qr!mpd/tags/([^/]+)$!,
2045 glob => 'tags/*',
2046 },
2047 ref => {
2048 left => 'tags',
2049 right => '',
2050 regex => qr!tags/([^/]+)$!,
2051 glob => 'tags/*',
2052 },
2053 }
2054 }
2055};
2056
44320b9e 2057$log_entry hashref as returned by libsvn_log_entry()
3397f9df 2058{
44320b9e 2059 log => 'whitespace-formatted log entry
3397f9df
EW
2060', # trailing newline is preserved
2061 revision => '8', # integer
2062 date => '2004-02-24T17:01:44.108345Z', # commit date
2063 author => 'committer name'
2064};
2065
6e8548cc
EW
2066
2067# this is generated by generate_diff();
3397f9df
EW
2068@mods = array of diff-index line hashes, each element represents one line
2069 of diff-index output
2070
2071diff-index line ($m hash)
2072{
2073 mode_a => first column of diff-index output, no leading ':',
2074 mode_b => second column of diff-index output,
2075 sha1_b => sha1sum of the final blob,
ac8e0b91 2076 chg => change type [MCRADT],
3397f9df
EW
2077 file_a => original file name of a file (iff chg is 'C' or 'R')
2078 file_b => new/current file name of a file (any chg)
2079}
2080;
a5e0cedc 2081
a00439ac
EW
2082# retval of read_url_paths{,_all}();
2083$l_map = {
2084 # repository root url
2085 'https://svn.musicpd.org' => {
2086 # repository path # GIT_SVN_ID
2087 'mpd/trunk' => 'trunk',
2088 'mpd/tags/0.11.5' => 'tags/0.11.5',
2089 },
2090}
2091
a5e0cedc
EW
2092Notes:
2093 I don't trust the each() function on unless I created %hash myself
2094 because the internal iterator may not have started at base.