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