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