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