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