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