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