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