]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
diff -c -p: do not die on submodules
[thirdparty/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,
171af110 66 $_version, $_fetch_all, $_no_rebase,
dee41f3e 67 $_merge, $_strategy, $_dry_run, $_local,
4be40381 68 $_prefix, $_no_checkout, $_url, $_verbose,
ba24e745 69 $_git_format, $_commit_url);
0bed5eaa 70$Git::SVN::_follow_parent = 1;
706587fc
EW
71my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
0bed5eaa 74my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 75 'authors-file|A=s' => \$_authors,
ecc712dd 76 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 81 'no-checkout' => \$_no_checkout,
80f50749 82 'quiet|q' => \$_q,
ecc712dd
EW
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
70ae04e4 85 'use-log-author' => \$Git::SVN::_use_log_author,
6aa9ba14 86 'add-author-from' => \$Git::SVN::_add_author_from,
706587fc 87 %remote_opts );
36f5b1f0 88
8f728fb9 89my ($_trunk, $_tags, $_branches, $_stdlayout);
0dfaf0a4 90my %icv;
dadc6d2a
EW
91my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
92 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
93 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
8f728fb9 94 'stdlayout|s' => \$_stdlayout,
4a1bb4c3 95 'minimize-url|m' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
96 'no-metadata' => sub { $icv{noMetadata} = 1 },
97 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
98 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
99 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
dadc6d2a 100 %remote_opts );
27e9fb8d 101my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
102 'rmdir' => \$SVN::Git::Editor::_rmdir,
103 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
104 'l=i' => \$SVN::Git::Editor::_rename_limit,
105 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 106);
9d55b41a 107
3397f9df 108my %cmd = (
2a3240be 109 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 110 { 'revision|r=s' => \$_revision,
905f8b7d 111 'fetch-all|all' => \$_fetch_all,
e98671e5 112 %fc_opts } ],
0425ea90
EW
113 clone => [ \&cmd_clone, "Initialize and fetch revisions",
114 { 'revision|r=s' => \$_revision,
115 %fc_opts, %init_opts } ],
d2866f9e 116 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 117 " (requires URL argument)",
9d55b41a 118 \%init_opts ],
dadc6d2a
EW
119 'multi-init' => [ \&cmd_multi_init,
120 "Deprecated alias for ".
121 "'$0 init -T<trunk> -b<branches> -t<tags>'",
122 \%init_opts ],
d7ad3bed
EW
123 dcommit => [ \&cmd_dcommit,
124 'Commit several diffs to merge with upstream',
3289e86e
EW
125 { 'merge|m|M' => \$_merge,
126 'strategy|s=s' => \$_strategy,
905f8b7d 127 'verbose|v' => \$_verbose,
3289e86e 128 'dry-run|n' => \$_dry_run,
905f8b7d 129 'fetch-all|all' => \$_fetch_all,
ba24e745
EW
130 'commit-url=s' => \$_commit_url,
131 'revision|r=i' => \$_revision,
171af110 132 'no-rebase' => \$_no_rebase,
4b155223 133 %cmt_opts, %fc_opts } ],
1ce255dc
EW
134 'set-tree' => [ \&cmd_set_tree,
135 "Set an SVN repository to a git tree-ish",
136 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
137 'create-ignore' => [ \&cmd_create_ignore,
138 'Create a .gitignore per svn:ignore',
139 { 'revision|r=i' => \$_revision
140 } ],
15153451
BS
141 'propget' => [ \&cmd_propget,
142 'Print the value of a property on a file or directory',
143 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
144 'proplist' => [ \&cmd_proplist,
145 'List all properties of a file or directory',
146 { 'revision|r=i' => \$_revision } ],
5969cbe1 147 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 148 { 'revision|r=i' => \$_revision
05b4df31 149 } ],
2d879792
VK
150 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
151 { 'revision|r=i' => \$_revision
152 } ],
1c8443b0 153 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
154 "Deprecated alias for $0 fetch --all",
155 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
156 'migrate' => [ sub { },
157 # no-op, we automatically run this anyways,
706587fc
EW
158 'Migrate configuration/metadata/layout from
159 previous versions of git-svn',
a836a0e1
EW
160 { 'minimize' => \$Git::SVN::Migration::_minimize,
161 %remote_opts } ],
f8c9d1d2
EW
162 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
163 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 164 'revision|r=s' => \$_revision,
f8c9d1d2
EW
165 'verbose|v' => \$Git::SVN::Log::verbose,
166 'incremental' => \$Git::SVN::Log::incremental,
167 'oneline' => \$Git::SVN::Log::oneline,
168 'show-commit' => \$Git::SVN::Log::show_commit,
169 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 170 'authors-file|A=s' => \$_authors,
f8c9d1d2 171 'color' => \$Git::SVN::Log::color,
4dbfe2e9 172 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 173 } ],
222566e4
EW
174 'find-rev' => [ \&cmd_find_rev,
175 "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 176 {} ],
905f8b7d
EW
177 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
178 { 'merge|m|M' => \$_merge,
179 'verbose|v' => \$_verbose,
180 'strategy|s=s' => \$_strategy,
dee41f3e 181 'local|l' => \$_local,
905f8b7d 182 'fetch-all|all' => \$_fetch_all,
7d45e146 183 'dry-run|n' => \$_dry_run,
905f8b7d 184 %fc_opts } ],
44320b9e
EW
185 'commit-diff' => [ \&cmd_commit_diff,
186 'Commit a diff between two trees',
27e9fb8d
EW
187 { 'message|m=s' => \$_message,
188 'file|F=s' => \$_file,
45bf473a 189 'revision|r=s' => \$_revision,
27e9fb8d 190 %cmt_opts } ],
e6fefa92
DK
191 'info' => [ \&cmd_info,
192 "Show info about the latest SVN revision
193 on the current branch",
8b014d71 194 { 'url' => \$_url, } ],
6fb5375e
TS
195 'blame' => [ \&Git::SVN::Log::cmd_blame,
196 "Show what revision and author last modified each line of a file",
4be40381 197 { 'git-format' => \$_git_format } ],
3397f9df 198);
9d55b41a 199
3397f9df
EW
200my $cmd;
201for (my $i = 0; $i < @ARGV; $i++) {
202 if (defined $cmd{$ARGV[$i]}) {
203 $cmd = $ARGV[$i];
204 splice @ARGV, $i, 1;
205 last;
206 }
207};
208
540424b2
EW
209# make sure we're always running at the top-level working directory
210unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
211 unless (-d $ENV{GIT_DIR}) {
212 if ($git_dir_user_set) {
213 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
214 "but it is not a directory\n";
215 }
216 my $git_dir = delete $ENV{GIT_DIR};
217 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
218 unless (length $cdup) {
219 die "Already at toplevel, but $git_dir ",
220 "not found '$cdup'\n";
221 }
222 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
223 unless (-d $git_dir) {
224 die "$git_dir still not found after going to ",
225 "'$cdup'\n";
226 }
227 $ENV{GIT_DIR} = $git_dir;
228 }
ffe256f9 229 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
5253dc33 230}
f4dd334b
GH
231
232my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
233
234read_repo_config(\%opts);
222566e4
EW
235if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
236 Getopt::Long::Configure('pass_through');
237}
f4dd334b
GH
238my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
239 'minimize-connections' => \$Git::SVN::Migration::_minimize,
240 'id|i=s' => \$Git::SVN::default_ref_id,
241 'svn-remote|remote|R=s' => sub {
242 $Git::SVN::no_reuse_existing = 1;
243 $Git::SVN::default_repo_id = $_[1] });
244exit 1 if (!$rv && $cmd && $cmd ne 'log');
245
246usage(0) if $_help;
247version() if $_version;
248usage(1) unless defined $cmd;
249load_authors() if $_authors;
250
0425ea90 251unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
252 Git::SVN::Migration::migration_check();
253}
ecc712dd 254Git::SVN::init_vars();
b805b44a
EW
255eval {
256 Git::SVN::verify_remotes_sanity();
257 $cmd{$cmd}->[0]->(@ARGV);
258};
259fatal $@ if $@;
1e889ef3 260post_fetch_checkout();
3397f9df
EW
261exit 0;
262
263####################### primary functions ######################
264sub usage {
265 my $exit = shift || 0;
266 my $fd = $exit ? \*STDERR : \*STDOUT;
267 print $fd <<"";
268git-svn - bidirectional operations between a single Subversion tree and git
1b1dd23f 269Usage: git svn <command> [options] [arguments]\n
448c81b4
EW
270
271 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
272
273 foreach (sort keys %cmd) {
448c81b4 274 next if $cmd && $cmd ne $_;
a836a0e1 275 next if /^multi-/; # don't show deprecated commands
b203b769 276 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 277 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
278 # mixed-case options are for .git/config only
279 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 280 # prints out arguments as they should be passed:
b8c92cad 281 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 282 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
283 "--$_" : "-$_" }
284 split /\|/,$_)," $x\n";
285 }
3397f9df
EW
286 }
287 print $fd <<"";
448c81b4
EW
288\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
289arbitrary identifier if you're tracking multiple SVN branches/repositories in
290one git repository and want to keep them separate. See git-svn(1) for more
291information.
3397f9df
EW
292
293 exit $exit;
294}
295
551ce28f 296sub version {
7d60ab2c 297 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
298 exit 0;
299}
300
8164b652
EW
301sub do_git_init_db {
302 unless (-d $ENV{GIT_DIR}) {
303 my @init_db = ('init');
304 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
305 if (defined $_shared) {
306 if ($_shared =~ /[a-z]/) {
307 push @init_db, "--shared=$_shared";
308 } else {
309 push @init_db, "--shared";
310 }
311 }
8164b652 312 command_noisy(@init_db);
ffe256f9 313 $_repository = Git->repository(Repository => ".git");
8164b652 314 }
0dfaf0a4
EW
315 my $set;
316 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
317 foreach my $i (keys %icv) {
318 die "'$set' and '$i' cannot both be set\n" if $set;
319 next unless defined $icv{$i};
320 command_noisy('config', "$pfx.$i", $icv{$i});
321 $set = $i;
322 }
8164b652
EW
323}
324
dadc6d2a
EW
325sub init_subdir {
326 my $repo_path = shift or return;
327 mkpath([$repo_path]) unless -d $repo_path;
328 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 329 $ENV{GIT_DIR} = '.git';
ffe256f9 330 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
dadc6d2a
EW
331}
332
0425ea90
EW
333sub cmd_clone {
334 my ($url, $path) = @_;
335 if (!defined $path &&
8f728fb9 336 (defined $_trunk || defined $_branches || defined $_tags ||
337 defined $_stdlayout) &&
0425ea90
EW
338 $url !~ m#^[a-z\+]+://#) {
339 $path = $url;
340 }
0425ea90 341 $path = basename($url) if !defined $path || !length $path;
f30603fc 342 cmd_init($url, $path);
0425ea90
EW
343 Git::SVN::fetch_all($Git::SVN::default_repo_id);
344}
345
d2866f9e 346sub cmd_init {
8f728fb9 347 if (defined $_stdlayout) {
348 $_trunk = 'trunk' if (!defined $_trunk);
349 $_tags = 'tags' if (!defined $_tags);
350 $_branches = 'branches' if (!defined $_branches);
351 }
dadc6d2a
EW
352 if (defined $_trunk || defined $_branches || defined $_tags) {
353 return cmd_multi_init(@_);
03e0ea87 354 }
dadc6d2a
EW
355 my $url = shift or die "SVN repository location required ",
356 "as a command-line argument\n";
357 init_subdir(@_);
8164b652 358 do_git_init_db();
03e0ea87 359
706587fc 360 Git::SVN->init($url);
3397f9df
EW
361}
362
2a3240be 363sub cmd_fetch {
e98671e5
EW
364 if (grep /^\d+=./, @_) {
365 die "'<rev>=<commit>' fetch arguments are ",
366 "no longer supported.\n";
07a1c950 367 }
e98671e5
EW
368 my ($remote) = @_;
369 if (@_ > 1) {
905f8b7d 370 die "Usage: $0 fetch [--all] [svn-remote]\n";
e98671e5
EW
371 }
372 $remote ||= $Git::SVN::default_repo_id;
373 if ($_fetch_all) {
374 cmd_multi_fetch();
375 } else {
376 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 377 }
2a3240be
EW
378}
379
1ce255dc 380sub cmd_set_tree {
3397f9df
EW
381 my (@commits) = @_;
382 if ($_stdin || !@commits) {
383 print "Reading from stdin...\n";
384 @commits = ();
385 while (<STDIN>) {
1ca72aef 386 if (/\b($sha1_short)\b/o) {
3397f9df
EW
387 unshift @commits, $1;
388 }
389 }
390 }
391 my @revs;
8de010ad 392 foreach my $c (@commits) {
aef4e921 393 my @tmp = command('rev-parse',$c);
8de010ad
EW
394 if (scalar @tmp == 1) {
395 push @revs, $tmp[0];
396 } elsif (scalar @tmp > 1) {
aef4e921 397 push @revs, reverse(command('rev-list',@tmp));
8de010ad 398 } else {
207f1a75 399 fatal "Failed to rev-parse $c";
8de010ad 400 }
3397f9df 401 }
1ce255dc
EW
402 my $gs = Git::SVN->new;
403 my ($r_last, $cmt_last) = $gs->last_rev_commit;
404 $gs->fetch;
97f6987a 405 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
406 fatal "There are new revisions that were fetched ",
407 "and need to be merged (or acknowledged) ",
408 "before committing.\nlast rev: $r_last\n",
207f1a75 409 " current: $gs->{last_rev}";
a5e0cedc 410 }
1ce255dc
EW
411 $gs->set_tree($_) foreach @revs;
412 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 413 unlink $gs->{index};
a5e0cedc 414}
8f22562c 415
d7ad3bed
EW
416sub cmd_dcommit {
417 my $head = shift;
c8cfa3e4 418 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 419 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 420 . "or stash them with `git stash'.\n";
d7ad3bed 421 $head ||= 'HEAD';
a8ae2623 422 my @refs;
13c823fb 423 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
711521e2 424 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
ba24e745 425 my $last_rev = $_revision if defined $_revision;
59b0c24d
MM
426 if ($url) {
427 print "Committing to $url ...\n";
428 }
13c823fb 429 unless ($gs) {
a8ae2623 430 die "Unable to determine upstream SVN information from ",
59b0c24d 431 "$head history.\nPerhaps the repository is empty.";
a8ae2623 432 }
733a65aa 433 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
434 if ($_no_rebase && scalar(@$linear_refs) > 1) {
435 warn "Attempting to commit more than one change while ",
436 "--no-rebase is enabled.\n",
437 "If these changes depend on each other, re-running ",
7dfa16b9 438 "without --no-rebase may be required."
751eb395 439 }
711521e2
EW
440 my $expect_url = $url;
441 Git::SVN::remove_username($expect_url);
c74d9acf
EW
442 while (1) {
443 my $d = shift @$linear_refs or last;
45bf473a
EW
444 unless (defined $last_rev) {
445 (undef, $last_rev, undef) = cmt_metadata("$d~1");
446 unless (defined $last_rev) {
d7ad3bed 447 fatal "Unable to extract revision information ",
207f1a75 448 "from commit $d~1";
45bf473a
EW
449 }
450 }
b22d4497
EW
451 if ($_dry_run) {
452 print "diff-tree $d~1 $d\n";
453 } else {
751eb395 454 my $cmt_rev;
d7ad3bed 455 my %ed_opts = ( r => $last_rev,
61395354 456 log => get_commit_entry($d)->{log},
ba24e745 457 ra => Git::SVN::Ra->new($url),
3caf320b
KA
458 config => SVN::Core::config_get_config(
459 $Git::SVN::Ra::config_dir
460 ),
61395354
EW
461 tree_a => "$d~1",
462 tree_b => $d,
463 editor_cb => sub {
464 print "Committed r$_[0]\n";
751eb395
EW
465 $cmt_rev = $_[0];
466 },
a8ae2623 467 svn_path => '');
61395354 468 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 469 print "No changes\n$d~1 == $d\n";
733a65aa 470 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 471 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 472 $parents->{$d};
d7ad3bed 473 }
751eb395 474 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 475 $last_rev = $cmt_rev;
751eb395
EW
476 next if $_no_rebase;
477
478 # we always want to rebase against the current HEAD,
479 # not any head that was passed to us
c74d9acf 480 my @diff = command('diff-tree', $d,
751eb395
EW
481 $gs->refname, '--');
482 my @finish;
483 if (@diff) {
484 @finish = rebase_cmd();
c74d9acf 485 print STDERR "W: $d and ", $gs->refname,
751eb395 486 " differ, using @finish:\n",
c74d9acf 487 join("\n", @diff), "\n";
751eb395
EW
488 } else {
489 print "No changes between current HEAD and ",
490 $gs->refname,
491 "\nResetting to the latest ",
492 $gs->refname, "\n";
493 @finish = qw/reset --mixed/;
494 }
495 command_noisy(@finish, $gs->refname);
c74d9acf
EW
496 if (@diff) {
497 @refs = ();
498 my ($url_, $rev_, $uuid_, $gs_) =
499 working_head_info($head, \@refs);
500 my ($linear_refs_, $parents_) =
501 linearize_history($gs_, \@refs);
502 if (scalar(@$linear_refs) !=
503 scalar(@$linear_refs_)) {
504 fatal "# of revisions changed ",
505 "\nbefore:\n",
506 join("\n", @$linear_refs),
507 "\n\nafter:\n",
508 join("\n", @$linear_refs_), "\n",
509 'If you are attempting to commit ',
510 "merges, try running:\n\t",
511 'git rebase --interactive',
512 '--preserve-merges ',
513 $gs->refname,
514 "\nBefore dcommitting";
515 }
711521e2 516 if ($url_ ne $expect_url) {
c74d9acf 517 fatal "URL mismatch after rebase: ",
711521e2 518 "$url_ != $expect_url";
c74d9acf
EW
519 }
520 if ($uuid_ ne $uuid) {
521 fatal "uuid mismatch after rebase: ",
522 "$uuid_ != $uuid";
523 }
524 # remap parents
525 my (%p, @l, $i);
526 for ($i = 0; $i < scalar @$linear_refs; $i++) {
527 my $new = $linear_refs_->[$i] or next;
528 $p{$new} =
529 $parents->{$linear_refs->[$i]};
530 push @l, $new;
531 }
532 $parents = \%p;
533 $linear_refs = \@l;
534 }
b22d4497
EW
535 }
536 }
3157dd9e 537 unlink $gs->{index};
b22d4497
EW
538}
539
26e60160 540sub cmd_find_rev {
ea14e6c5
MAL
541 my $revision_or_hash = shift or die "SVN or git revision required ",
542 "as a command-line argument\n";
26e60160
AR
543 my $result;
544 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
545 my $head = shift;
546 $head ||= 'HEAD';
547 my @refs;
63c56022 548 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
b3cb7e45
AR
549 unless ($gs) {
550 die "Unable to determine upstream SVN information from ",
551 "$head history\n";
26e60160 552 }
b3cb7e45 553 my $desired_revision = substr($revision_or_hash, 1);
63c56022 554 $result = $gs->rev_map_get($desired_revision, $uuid);
26e60160
AR
555 } else {
556 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
557 $result = $rev;
558 }
559 print "$result\n" if $result;
560}
561
905f8b7d
EW
562sub cmd_rebase {
563 command_noisy(qw/update-index --refresh/);
13c823fb
EW
564 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
565 unless ($gs) {
905f8b7d
EW
566 die "Unable to determine upstream SVN information from ",
567 "working tree history\n";
568 }
7d45e146
SF
569 if ($_dry_run) {
570 print "Remote Branch: " . $gs->refname . "\n";
571 print "SVN URL: " . $url . "\n";
572 return;
573 }
905f8b7d
EW
574 if (command(qw/diff-index HEAD --/)) {
575 print STDERR "Cannot rebase with uncommited changes:\n";
576 command_noisy('status');
577 exit 1;
578 }
dee41f3e 579 unless ($_local) {
cec0d5a3
SG
580 # rebase will checkout for us, so no need to do it explicitly
581 $_no_checkout = 'true';
dee41f3e
EW
582 $_fetch_all ? $gs->fetch_all : $gs->fetch;
583 }
905f8b7d
EW
584 command_noisy(rebase_cmd(), $gs->refname);
585}
586
5969cbe1 587sub cmd_show_ignore {
13c823fb
EW
588 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
589 $gs ||= Git::SVN->new;
5969cbe1 590 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
01bdab84
BS
591 $gs->prop_walk($gs->{path}, $r, sub {
592 my ($gs, $path, $props) = @_;
593 print STDOUT "\n# $path\n";
594 my $s = $props->{'svn:ignore'} or return;
595 $s =~ s/[\r\n]+/\n/g;
596 chomp $s;
597 $s =~ s#^#$path#gm;
598 print STDOUT "$s\n";
599 });
a5e0cedc
EW
600}
601
2d879792
VK
602sub cmd_show_externals {
603 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
604 $gs ||= Git::SVN->new;
605 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
606 $gs->prop_walk($gs->{path}, $r, sub {
607 my ($gs, $path, $props) = @_;
608 print STDOUT "\n# $path\n";
609 my $s = $props->{'svn:externals'} or return;
610 $s =~ s/[\r\n]+/\n/g;
611 chomp $s;
612 $s =~ s#^#$path#gm;
613 print STDOUT "$s\n";
614 });
615}
616
d05ddec5
BS
617sub cmd_create_ignore {
618 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
619 $gs ||= Git::SVN->new;
620 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
621 $gs->prop_walk($gs->{path}, $r, sub {
622 my ($gs, $path, $props) = @_;
623 # $path is of the form /path/to/dir/
624 my $ignore = '.' . $path . '.gitignore';
625 my $s = $props->{'svn:ignore'} or return;
626 open(GITIGNORE, '>', $ignore)
207f1a75 627 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5
BS
628 $s =~ s/[\r\n]+/\n/g;
629 chomp $s;
630 # Prefix all patterns so that the ignore doesn't apply
631 # to sub-directories.
632 $s =~ s#^#/#gm;
633 print GITIGNORE "$s\n";
634 close(GITIGNORE)
207f1a75 635 or fatal("Failed to close `$ignore': $!");
c4c66b26 636 command_noisy('add', '-f', $ignore);
d05ddec5
BS
637 });
638}
639
b2b3ada7
DK
640sub canonicalize_path {
641 my ($path) = @_;
e6fefa92
DK
642 my $dot_slash_added = 0;
643 if (substr($path, 0, 1) ne "/") {
644 $path = "./" . $path;
645 $dot_slash_added = 1;
646 }
b2b3ada7
DK
647 # File::Spec->canonpath doesn't collapse x/../y into y (for a
648 # good reason), so let's do this manually.
649 $path =~ s#/+#/#g;
650 $path =~ s#/\.(?:/|$)#/#g;
651 $path =~ s#/[^/]+/\.\.##g;
652 $path =~ s#/$##g;
e6fefa92 653 $path =~ s#^\./## if $dot_slash_added;
2fe403e7
GP
654 $path =~ s#^/##;
655 $path =~ s#^\.$##;
b2b3ada7
DK
656 return $path;
657}
658
15153451
BS
659# get_svnprops(PATH)
660# ------------------
51e057cf 661# Helper for cmd_propget and cmd_proplist below.
15153451
BS
662sub get_svnprops {
663 my $path = shift;
664 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
665 $gs ||= Git::SVN->new;
666
667 # prefix THE PATH by the sub-directory from which the user
668 # invoked us.
669 $path = $cmd_dir_prefix . $path;
207f1a75 670 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
671 my $is_dir = -d $path ? 1 : 0;
672 $path = $gs->{path} . '/' . $path;
673
674 # canonicalize the path (otherwise libsvn will abort or fail to
675 # find the file)
b2b3ada7 676 $path = canonicalize_path($path);
15153451
BS
677
678 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
679 my $props;
680 if ($is_dir) {
681 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
682 }
683 else {
684 (undef, $props) = $gs->ra->get_file($path, $r, undef);
685 }
686 return $props;
687}
688
689# cmd_propget (PROP, PATH)
690# ------------------------
691# Print the SVN property PROP for PATH.
692sub cmd_propget {
693 my ($prop, $path) = @_;
694 $path = '.' if not defined $path;
695 usage(1) if not defined $prop;
696 my $props = get_svnprops($path);
697 if (not defined $props->{$prop}) {
207f1a75 698 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
699 }
700 print $props->{$prop} . "\n";
701}
702
51e057cf
BS
703# cmd_proplist (PATH)
704# -------------------
705# Print the list of SVN properties for PATH.
706sub cmd_proplist {
707 my $path = shift;
708 $path = '.' if not defined $path;
709 my $props = get_svnprops($path);
710 print "Properties on '$path':\n";
711 foreach (sort keys %{$props}) {
712 print " $_\n";
713 }
714}
715
8164b652 716sub cmd_multi_init {
9d55b41a 717 my $url = shift;
98327e58
EW
718 unless (defined $_trunk || defined $_branches || defined $_tags) {
719 usage(1);
9d55b41a 720 }
dc431666
EW
721
722 # there are currently some bugs that prevent multi-init/multi-fetch
723 # setups from working well without this.
724 $Git::SVN::_minimize_url = 1;
725
8164b652 726 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
727 if (defined $url) {
728 $url =~ s#/+$##;
729 init_subdir(@_);
730 }
f30603fc 731 do_git_init_db();
98327e58 732 if (defined $_trunk) {
706587fc
EW
733 my $trunk_ref = $_prefix . 'trunk';
734 # try both old-style and new-style lookups:
735 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 736 unless ($gs_trunk) {
706587fc
EW
737 my ($trunk_url, $trunk_path) =
738 complete_svn_url($url, $_trunk);
739 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
740 undef, $trunk_ref);
98327e58 741 }
c35b96e7 742 }
706587fc 743 return unless defined $_branches || defined $_tags;
e7db67e6
EW
744 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
745 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
746 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
747}
748
1c8443b0 749sub cmd_multi_fetch {
0af9c9f9
EW
750 my $remotes = Git::SVN::read_all_remotes();
751 foreach my $repo_id (sort keys %$remotes) {
db03cd24 752 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
753 Git::SVN::fetch_all($repo_id, $remotes);
754 }
9d55b41a 755 }
9d55b41a
EW
756}
757
44320b9e
EW
758# this command is special because it requires no metadata
759sub cmd_commit_diff {
760 my ($ta, $tb, $url) = @_;
761 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 762 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 763 fatal($usage) if (!defined $ta || !defined $tb);
d72ab8c8 764 my $svn_path = '';
44320b9e
EW
765 if (!defined $url) {
766 my $gs = eval { Git::SVN->new };
767 if (!$gs) {
768 fatal("Needed URL or usable git-svn --id in ",
769 "the command-line\n", $usage);
770 }
771 $url = $gs->{url};
d3a840dc 772 $svn_path = $gs->{path};
44320b9e
EW
773 }
774 unless (defined $_revision) {
775 fatal("-r|--revision is a required argument\n", $usage);
776 }
777 if (defined $_message && defined $_file) {
778 fatal("Both --message/-m and --file/-F specified ",
779 "for the commit message.\n",
207f1a75 780 "I have no idea what you mean");
44320b9e
EW
781 }
782 if (defined $_file) {
783 $_message = file_to_s($_file);
784 } else {
785 $_message ||= get_commit_entry($tb)->{log};
786 }
787 my $ra ||= Git::SVN::Ra->new($url);
788 my $r = $_revision;
789 if ($r eq 'HEAD') {
790 $r = $ra->get_latest_revnum;
791 } elsif ($r !~ /^\d+$/) {
792 die "revision argument: $r not understood by git-svn\n";
793 }
61395354
EW
794 my %ed_opts = ( r => $r,
795 log => $_message,
796 ra => $ra,
797 tree_a => $ta,
798 tree_b => $tb,
799 editor_cb => sub { print "Committed r$_[0]\n" },
800 svn_path => $svn_path );
801 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
802 print "No changes\n$ta == $tb\n";
803 }
44320b9e
EW
804}
805
e6fefa92 806sub cmd_info {
bd2d4f96
EW
807 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
808 if (exists $_[1]) {
e6fefa92
DK
809 die "Too many arguments specified\n";
810 }
811
812 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
813
814 if (!$file_type && !$diff_status) {
815 print STDERR "$path: (Not a versioned resource)\n\n";
816 return;
817 }
818
819 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
820 unless ($gs) {
821 die "Unable to determine upstream SVN information from ",
822 "working tree history\n";
823 }
bd2d4f96
EW
824
825 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
826 $path = "." if $path eq "";
827
e6fefa92
DK
828 my $full_url = $url . ($path eq "." ? "" : "/$path");
829
8b014d71
DK
830 if ($_url) {
831 print $full_url, "\n";
832 return;
833 }
834
e6fefa92
DK
835 my $result = "Path: $path\n";
836 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
837 $result .= "URL: " . $full_url . "\n";
838
a5460eb7
EW
839 eval {
840 my $repos_root = $gs->repos_root;
841 Git::SVN::remove_username($repos_root);
842 $result .= "Repository Root: $repos_root\n";
843 };
844 if ($@) {
845 $result .= "Repository Root: (offline)\n";
846 }
e6fefa92
DK
847 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
848 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
849
850 $result .= "Node Kind: " .
851 ($file_type eq "dir" ? "directory" : "file") . "\n";
852
853 my $schedule = $diff_status eq "A"
854 ? "add"
855 : ($diff_status eq "D" ? "delete" : "normal");
856 $result .= "Schedule: $schedule\n";
857
858 if ($diff_status eq "A") {
859 print $result, "\n";
860 return;
861 }
862
863 my ($lc_author, $lc_rev, $lc_date_utc);
864 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
865 my $log = command_output_pipe(@args);
866 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
867 while (<$log>) {
868 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
869 $lc_author = $1;
870 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
871 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
872 (undef, $lc_rev, undef) = ::extract_metadata($1);
873 }
874 }
875 close $log;
876
877 Git::SVN::Log::set_local_timezone();
878
879 $result .= "Last Changed Author: $lc_author\n";
880 $result .= "Last Changed Rev: $lc_rev\n";
881 $result .= "Last Changed Date: " .
882 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
883
884 if ($file_type ne "dir") {
885 my $text_last_updated_date =
886 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
887 $result .=
888 "Text Last Updated: " .
889 Git::SVN::Log::format_svn_date($text_last_updated_date) .
890 "\n";
891 my $checksum;
892 if ($diff_status eq "D") {
893 my ($fh, $ctx) =
894 command_output_pipe(qw(cat-file blob), "HEAD:$path");
895 if ($file_type eq "link") {
896 my $file_name = <$fh>;
8d7c4fad 897 $checksum = md5sum("link $file_name");
e6fefa92 898 } else {
8d7c4fad 899 $checksum = md5sum($fh);
e6fefa92
DK
900 }
901 command_close_pipe($fh, $ctx);
902 } elsif ($file_type eq "link") {
903 my $file_name =
904 command(qw(cat-file blob), "HEAD:$path");
905 $checksum =
8d7c4fad 906 md5sum("link " . $file_name);
e6fefa92
DK
907 } else {
908 open FILE, "<", $path or die $!;
8d7c4fad 909 $checksum = md5sum(\*FILE);
e6fefa92
DK
910 close FILE or die $!;
911 }
912 $result .= "Checksum: " . $checksum . "\n";
913 }
914
915 print $result, "\n";
916}
917
3397f9df
EW
918########################### utility functions #########################
919
905f8b7d
EW
920sub rebase_cmd {
921 my @cmd = qw/rebase/;
922 push @cmd, '-v' if $_verbose;
923 push @cmd, qw/--merge/ if $_merge;
924 push @cmd, "--strategy=$_strategy" if $_strategy;
925 @cmd;
926}
927
1e889ef3
EW
928sub post_fetch_checkout {
929 return if $_no_checkout;
930 my $gs = $Git::SVN::_head or return;
931 return if verify_ref('refs/heads/master^0');
932
933 my $valid_head = verify_ref('HEAD^0');
934 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
935 return if ($valid_head || !verify_ref('HEAD^0'));
936
937 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
938 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
939 return if -f $index;
940
7ae3df8c 941 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
942 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
943 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
944 print STDERR "Checked out HEAD:\n ",
945 $gs->full_url, " r", $gs->last_rev, "\n";
946}
947
98327e58
EW
948sub complete_svn_url {
949 my ($url, $path) = @_;
950 $path =~ s#/+$##;
98327e58 951 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
952 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
953 fatal("E: '$path' is not a complete URL ",
207f1a75 954 "and a separate URL is not specified");
98327e58 955 }
706587fc 956 return ($url, $path);
98327e58 957 }
706587fc 958 return ($path, '');
98327e58
EW
959}
960
9d55b41a 961sub complete_url_ls_init {
706587fc
EW
962 my ($ra, $repo_path, $switch, $pfx) = @_;
963 unless ($repo_path) {
9d55b41a
EW
964 print STDERR "W: $switch not specified\n";
965 return;
966 }
706587fc
EW
967 $repo_path =~ s#/+$##;
968 if ($repo_path =~ m#^[a-z\+]+://#) {
969 $ra = Git::SVN::Ra->new($repo_path);
970 $repo_path = '';
e7db67e6 971 } else {
706587fc 972 $repo_path =~ s#^/+##;
e7db67e6 973 unless ($ra) {
706587fc 974 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 975 "and a separate URL is not specified");
8164b652 976 }
e7db67e6 977 }
706587fc 978 my $url = $ra->{url};
b4d57e5e
EW
979 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
980 my $k = "svn-remote.$gs->{repo_id}.url";
981 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
982 if ($orig_url && ($orig_url ne $gs->{url})) {
983 die "$k already set: $orig_url\n",
984 "wanted to set to: $gs->{url}\n";
88cf4107 985 }
b4d57e5e 986 command_oneline('config', $k, $gs->{url}) unless $orig_url;
ed0b9d43 987 my $remote_path = "$ra->{svn_path}/$repo_path";
b4d57e5e
EW
988 $remote_path =~ s#/+#/#g;
989 $remote_path =~ s#^/##g;
ed0b9d43 990 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
991 my ($n) = ($switch =~ /^--(\w+)/);
992 if (length $pfx && $pfx !~ m#/$#) {
993 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 994 }
570d35c2
MG
995 command_noisy('config',
996 "svn-remote.$gs->{repo_id}.$n",
997 "$remote_path:refs/remotes/$pfx*" .
998 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
9d55b41a
EW
999}
1000
aef4e921
EW
1001sub verify_ref {
1002 my ($ref) = @_;
2c5c1d53
EW
1003 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1004 { STDERR => 0 }); };
aef4e921
EW
1005}
1006
a5e0cedc 1007sub get_tree_from_treeish {
cf52b8f0 1008 my ($treeish) = @_;
44320b9e 1009 # $treeish can be a symbolic ref, too:
aef4e921 1010 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
1011 my $expected;
1012 while ($type eq 'tag') {
aef4e921 1013 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
1014 }
1015 if ($type eq 'commit') {
aef4e921
EW
1016 $expected = (grep /^tree /, command(qw/cat-file commit/,
1017 $treeish))[0];
44320b9e 1018 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
1019 die "Unable to get tree from $treeish\n" unless $expected;
1020 } elsif ($type eq 'tree') {
1021 $expected = $treeish;
1022 } else {
1023 die "$treeish is a $type, expected tree, tag or commit\n";
1024 }
a5e0cedc
EW
1025 return $expected;
1026}
1027
44320b9e
EW
1028sub get_commit_entry {
1029 my ($treeish) = shift;
1030 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1031 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1032 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1033 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1034
44320b9e 1035 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1036 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1037 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1038 $type, $treeish);
3397f9df 1039 my $in_msg = 0;
6aa9ba14
AP
1040 my $author;
1041 my $saw_from = 0;
328eb9b3 1042 my $msgbuf = "";
3397f9df
EW
1043 while (<$msg_fh>) {
1044 if (!$in_msg) {
1045 $in_msg = 1 if (/^\s*$/);
6aa9ba14 1046 $author = $1 if (/^author (.*>)/);
df746c5a 1047 } elsif (/^git-svn-id: /) {
44320b9e
EW
1048 # skip this for now, we regenerate the
1049 # correct one on re-fetch anyways
1050 # TODO: set *:merge properties or like...
3397f9df 1051 } else {
6aa9ba14
AP
1052 if (/^From:/ || /^Signed-off-by:/) {
1053 $saw_from = 1;
1054 }
328eb9b3 1055 $msgbuf .= $_;
3397f9df
EW
1056 }
1057 }
328eb9b3 1058 $msgbuf =~ s/\s+$//s;
6aa9ba14
AP
1059 if ($Git::SVN::_add_author_from && defined($author)
1060 && !$saw_from) {
328eb9b3 1061 $msgbuf .= "\n\nFrom: $author";
6aa9ba14 1062 }
328eb9b3 1063 print $log_fh $msgbuf or croak $!;
aef4e921 1064 command_close_pipe($msg_fh, $ctx);
3397f9df 1065 }
44320b9e 1066 close $log_fh or croak $!;
3397f9df
EW
1067
1068 if ($_edit || ($type eq 'tree')) {
1069 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
1070 # TODO: strip out spaces, comments, like git-commit.sh
1071 system($editor, $commit_editmsg);
3397f9df 1072 }
44320b9e
EW
1073 rename $commit_editmsg, $commit_msg or croak $!;
1074 open $log_fh, '<', $commit_msg or croak $!;
1075 { local $/; chomp($log_entry{log} = <$log_fh>); }
1076 close $log_fh or croak $!;
1077 unlink $commit_msg;
1078 \%log_entry;
a5e0cedc
EW
1079}
1080
3397f9df
EW
1081sub s_to_file {
1082 my ($str, $file, $mode) = @_;
1083 open my $fd,'>',$file or croak $!;
1084 print $fd $str,"\n" or croak $!;
1085 close $fd or croak $!;
1086 chmod ($mode &~ umask, $file) if (defined $mode);
1087}
1088
1089sub file_to_s {
1090 my $file = shift;
1091 open my $fd,'<',$file or croak "$!: file: $file\n";
1092 local $/;
1093 my $ret = <$fd>;
1094 close $fd or croak $!;
1095 $ret =~ s/\s*$//s;
1096 return $ret;
1097}
1098
eeb0abe0
EW
1099# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1100sub load_authors {
1101 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1102 my $log = $cmd eq 'log';
eeb0abe0
EW
1103 while (<$authors>) {
1104 chomp;
575d025c 1105 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1106 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1107 if ($log) {
1108 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1109 } else {
1110 $users{$user} = [$name, $email];
1111 }
79bb8d88
EW
1112 }
1113 close $authors or croak $!;
1114}
1115
e0d10e1c 1116# convert GetOpt::Long specs for use by git-config
b8c92cad 1117sub read_repo_config {
706587fc 1118 return unless -d $ENV{GIT_DIR};
b8c92cad 1119 my $opts = shift;
97ae0911 1120 my @config_only;
b8c92cad 1121 foreach my $o (keys %$opts) {
97ae0911
EW
1122 # if we have mixedCase and a long option-only, then
1123 # it's a config-only variable that we don't need for
1124 # the command-line.
1125 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1126 my $v = $opts->{$o};
97ae0911 1127 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1128 $key =~ s/-//g;
225f1d0c 1129 my $arg = 'git config';
b8c92cad
EW
1130 $arg .= ' --int' if ($o =~ /[:=]i$/);
1131 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1132 if (ref $v eq 'ARRAY') {
1133 chomp(my @tmp = `$arg --get-all svn.$key`);
1134 @$v = @tmp if @tmp;
1135 } else {
1136 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1137 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1138 $$v = $tmp;
1139 }
1140 }
1141 }
97ae0911 1142 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1143}
1144
79bb8d88 1145sub extract_metadata {
c1927a85 1146 my $id = shift or return (undef, undef, undef);
3dfab993 1147 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
79bb8d88 1148 \s([a-f\d\-]+)$/x);
e70dc780 1149 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1150 # some of the original repositories I made had
82e5a82f 1151 # identifiers like this:
3dfab993 1152 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
79bb8d88
EW
1153 }
1154 return ($url, $rev, $uuid);
1155}
1156
c1927a85
EW
1157sub cmt_metadata {
1158 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1159 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1160}
1161
905f8b7d
EW
1162sub working_head_info {
1163 my ($head, $refs) = @_;
b6309ac2 1164 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
05b4df31 1165 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1166 my $hash;
40cb8f8f 1167 my %max;
3dfab993
SV
1168 while (<$fh>) {
1169 if ( m{^commit ($::sha1)$} ) {
1170 unshift @$refs, $hash if $hash and $refs;
1171 $hash = $1;
1172 next;
1173 }
1174 next unless s{^\s*(git-svn-id:)}{$1};
1175 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1176 if (defined $url && defined $rev) {
40cb8f8f 1177 next if $max{$url} and $max{$url} < $rev;
13c823fb 1178 if (my $gs = Git::SVN->find_by_url($url)) {
63c56022 1179 my $c = $gs->rev_map_get($rev, $uuid);
b03c7a63 1180 if ($c && $c eq $hash) {
13c823fb
EW
1181 close $fh; # break the pipe
1182 return ($url, $rev, $uuid, $gs);
40cb8f8f 1183 } else {
060610c5 1184 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1185 }
1186 }
1187 }
905f8b7d 1188 }
13c823fb
EW
1189 command_close_pipe($fh, $ctx);
1190 (undef, undef, undef, undef);
905f8b7d
EW
1191}
1192
733a65aa
EW
1193sub read_commit_parents {
1194 my ($parents, $c) = @_;
7b02b85a
EW
1195 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1196 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1197 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1198}
1199
1200sub linearize_history {
1201 my ($gs, $refs) = @_;
1202 my %parents;
1203 foreach my $c (@$refs) {
1204 read_commit_parents(\%parents, $c);
1205 }
1206
1207 my @linear_refs;
1208 my %skip = ();
1209 my $last_svn_commit = $gs->last_commit;
1210 foreach my $c (reverse @$refs) {
1211 next if $c eq $last_svn_commit;
1212 last if $skip{$c};
1213
1214 unshift @linear_refs, $c;
1215 $skip{$c} = 1;
1216
1217 # we only want the first parent to diff against for linear
1218 # history, we save the rest to inject when we finalize the
1219 # svn commit
1220 my $fp_a = verify_ref("$c~1");
1221 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1222 if (!$fp_a || !$fp_b) {
1223 die "Commit $c\n",
1224 "has no parent commit, and therefore ",
1225 "nothing to diff against.\n",
1226 "You should be working from a repository ",
1227 "originally created by git-svn\n";
1228 }
1229 if ($fp_a ne $fp_b) {
1230 die "$c~1 = $fp_a, however parsing commit $c ",
1231 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1232 }
1233
1234 foreach my $p (@{$parents{$c}}) {
1235 $skip{$p} = 1;
1236 }
1237 }
1238 (\@linear_refs, \%parents);
1239}
1240
e6fefa92
DK
1241sub find_file_type_and_diff_status {
1242 my ($path) = @_;
107cee50 1243 return ('dir', '') if $path eq '';
e6fefa92
DK
1244
1245 my $diff_output =
1246 command_oneline(qw(diff --cached --name-status --), $path) || "";
1247 my $diff_status = (split(' ', $diff_output))[0] || "";
1248
1249 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1250
1251 return (undef, undef) if !$diff_status && !$ls_tree;
1252
1253 if ($diff_status eq "A") {
1254 return ("link", $diff_status) if -l $path;
1255 return ("dir", $diff_status) if -d $path;
1256 return ("file", $diff_status);
1257 }
1258
1259 my $mode = (split(' ', $ls_tree))[0] || "";
1260
1261 return ("link", $diff_status) if $mode eq "120000";
1262 return ("dir", $diff_status) if $mode eq "040000";
1263 return ("file", $diff_status);
1264}
1265
b2b3ada7
DK
1266sub md5sum {
1267 my $arg = shift;
1268 my $ref = ref $arg;
1269 my $md5 = Digest::MD5->new();
0b19138b 1270 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
b2b3ada7
DK
1271 $md5->addfile($arg) or croak $!;
1272 } elsif ($ref eq 'SCALAR') {
1273 $md5->add($$arg) or croak $!;
1274 } elsif (!$ref) {
1275 $md5->add($arg) or croak $!;
1276 } else {
1277 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1278 }
1279 return $md5->hexdigest();
1280}
1281
9b981fc6
EW
1282package Git::SVN;
1283use strict;
1284use warnings;
060610c5
EW
1285use Fcntl qw/:DEFAULT :seek/;
1286use constant rev_map_fmt => 'NH40';
ecc712dd 1287use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 1288 $_repack $_repack_flags $_use_svm_props $_head
70ae04e4 1289 $_use_svnsync_props $no_reuse_existing $_minimize_url
6aa9ba14 1290 $_use_log_author $_add_author_from/;
9b981fc6
EW
1291use Carp qw/croak/;
1292use File::Path qw/mkpath/;
373274f9 1293use File::Copy qw/copy/;
9b981fc6
EW
1294use IPC::Open3;
1295
94bc914c
KW
1296my ($_gc_nr, $_gc_period);
1297
9b981fc6
EW
1298# properties that we do not log:
1299my %SKIP_PROP;
1300BEGIN {
1301 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1302 svn:special svn:executable
1303 svn:entry:committed-rev
1304 svn:entry:last-author
1305 svn:entry:uuid
1306 svn:entry:committed-date/;
91b03282
EW
1307
1308 # some options are read globally, but can be overridden locally
1309 # per [svn-remote "..."] section. Command-line options will *NOT*
1310 # override options set in an [svn-remote "..."] section
c5f71ad0
SV
1311 no strict 'refs';
1312 for my $option (qw/follow_parent no_metadata use_svm_props
1313 use_svnsync_props/) {
1314 my $key = $option;
91b03282 1315 $key =~ tr/_//d;
c5f71ad0
SV
1316 my $prop = "-$option";
1317 *$option = sub {
1318 my ($self) = @_;
1319 return $self->{$prop} if exists $self->{$prop};
1320 my $k = "svn-remote.$self->{repo_id}.$key";
1321 eval { command_oneline(qw/config --get/, $k) };
1322 if ($@) {
1323 $self->{$prop} = ${"Git::SVN::_$option"};
91b03282 1324 } else {
c5f71ad0
SV
1325 my $v = command_oneline(qw/config --bool/,$k);
1326 $self->{$prop} = $v eq 'false' ? 0 : 1;
91b03282 1327 }
c5f71ad0
SV
1328 return $self->{$prop};
1329 }
91b03282 1330 }
9b981fc6
EW
1331}
1332
0b19138b 1333
321b1842
EW
1334my (%LOCKFILES, %INDEX_FILES);
1335END {
1336 unlink keys %LOCKFILES if %LOCKFILES;
1337 unlink keys %INDEX_FILES if %INDEX_FILES;
1338}
373274f9 1339
4bb9ed04
EW
1340sub resolve_local_globs {
1341 my ($url, $fetch, $glob_spec) = @_;
1342 return unless defined $glob_spec;
1343 my $ref = $glob_spec->{ref};
1344 my $path = $glob_spec->{path};
1345 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1346 next unless m#^refs/remotes/$ref->{regex}$#;
1347 my $p = $1;
bf655fd7
RE
1348 my $pathname = desanitize_refname($path->full_path($p));
1349 my $refname = desanitize_refname($ref->full_path($p));
4bb9ed04
EW
1350 if (my $existing = $fetch->{$pathname}) {
1351 if ($existing ne $refname) {
1352 die "Refspec conflict:\n",
1353 "existing: refs/remotes/$existing\n",
1354 " globbed: refs/remotes/$refname\n";
1355 }
1356 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 1357 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
1358 "refs/remotes/$refname: '$url' not found in '$u'\n";
1359 if ($pathname ne $u) {
1360 warn "W: Refspec glob conflict ",
1361 "(ref: refs/remotes/$refname):\n",
1362 "expected path: $pathname\n",
1363 " real path: $u\n",
1364 "Continuing ahead with $u\n";
1365 next;
1366 }
1367 } else {
4bb9ed04
EW
1368 $fetch->{$pathname} = $refname;
1369 }
1370 }
1371}
1372
e98671e5
EW
1373sub parse_revision_argument {
1374 my ($base, $head) = @_;
1375 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1376 return ($base, $head);
1377 }
1378 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1379 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1380 return ($head, $head) if ($::_revision eq 'HEAD');
1381 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1382 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1383 die "revision argument: $::_revision not understood by git-svn\n";
1384}
1385
0af9c9f9 1386sub fetch_all {
4bb9ed04 1387 my ($repo_id, $remotes) = @_;
905f8b7d
EW
1388 if (ref $repo_id) {
1389 my $gs = $repo_id;
1390 $repo_id = undef;
1391 $repo_id = $gs->{repo_id};
1392 }
1393 $remotes ||= read_all_remotes();
7447b4bc
EW
1394 my $remote = $remotes->{$repo_id} or
1395 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 1396 my $fetch = $remote->{fetch};
7447b4bc 1397 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 1398 my (@gs, @globs);
0af9c9f9 1399 my $ra = Git::SVN::Ra->new($url);
26a62d57 1400 my $uuid = $ra->get_uuid;
0af9c9f9 1401 my $head = $ra->get_latest_revnum;
28710f74 1402 my $base = defined $fetch ? $head : 0;
e518192f
EW
1403
1404 # read the max revs for wildcard expansion (branches/*, tags/*)
1405 foreach my $t (qw/branches tags/) {
1406 defined $remote->{$t} or next;
1407 push @globs, $remote->{$t};
93f2689c
EW
1408 my $max_rev = eval { tmp_config(qw/--int --get/,
1409 "svn-remote.$repo_id.${t}-maxRev") };
1410 if (defined $max_rev && ($max_rev < $base)) {
1411 $base = $max_rev;
d6d3346b
EW
1412 } elsif (!defined $max_rev) {
1413 $base = 0;
e518192f
EW
1414 }
1415 }
1416
db03cd24
EW
1417 if ($fetch) {
1418 foreach my $p (sort keys %$fetch) {
1419 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
060610c5 1420 my $lr = $gs->rev_map_max;
db03cd24
EW
1421 if (defined $lr) {
1422 $base = $lr if ($lr < $base);
1423 }
1424 push @gs, $gs;
0af9c9f9 1425 }
0af9c9f9 1426 }
e98671e5
EW
1427
1428 ($base, $head) = parse_revision_argument($base, $head);
e518192f 1429 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
1430}
1431
47e39c55
EW
1432sub read_all_remotes {
1433 my $r = {};
63c56022
JA
1434 my $use_svm_props = eval { command_oneline(qw/config --bool
1435 svn.useSvmProps/) };
1436 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
8b8fc068 1437 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
61192165
AP
1438 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1439 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1440 die("svn-remote.$remote: remote ref '$_remote_ref' "
1441 . "must start with 'refs/remotes/'\n")
1442 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1443 my $remote_ref = $1;
46cf98ba
EW
1444 $local_ref =~ s{^/}{};
1445 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
63c56022
JA
1446 $r->{$remote}->{svm} = {} if $use_svm_props;
1447 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1448 $r->{$1}->{svm} = {};
47e39c55
EW
1449 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1450 $r->{$1}->{url} = $2;
4bb9ed04
EW
1451 } elsif (m!^(.+)\.(branches|tags)=
1452 (.*):refs/remotes/(.+)\s*$/!x) {
1453 my ($p, $g) = ($3, $4);
1454 my $rs = $r->{$1}->{$2} = {
e518192f 1455 t => $2,
93f2689c 1456 remote => $1,
4bb9ed04
EW
1457 path => Git::SVN::GlobSpec->new($p),
1458 ref => Git::SVN::GlobSpec->new($g) };
1459 if (length($rs->{ref}->{right}) != 0) {
1460 die "The '*' glob character must be the last ",
1461 "character of '$g'\n";
1462 }
47e39c55
EW
1463 }
1464 }
63c56022
JA
1465
1466 map {
1467 if (defined $r->{$_}->{svm}) {
1468 my $svm;
1469 eval {
1470 my $section = "svn-remote.$_";
1471 $svm = {
1472 source => tmp_config('--get',
1473 "$section.svm-source"),
1474 replace => tmp_config('--get',
1475 "$section.svm-replace"),
1476 }
1477 };
1478 $r->{$_}->{svm} = $svm;
1479 }
1480 } keys %$r;
1481
47e39c55
EW
1482 $r;
1483}
1484
ecc712dd 1485sub init_vars {
94bc914c 1486 $_gc_nr = $_gc_period = 1000;
af788a6e
KW
1487 if (defined $_repack || defined $_repack_flags) {
1488 warn "Repack options are obsolete; they have no effect.\n";
1489 }
ecc712dd
EW
1490}
1491
b805b44a 1492sub verify_remotes_sanity {
536c4b09 1493 return unless -d $ENV{GIT_DIR};
b805b44a
EW
1494 my %seen;
1495 foreach (command(qw/config -l/)) {
1496 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1497 if ($seen{$1}) {
1498 die "Remote ref refs/remote/$1 is tracked by",
1499 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1500 "Please resolve this ambiguity in ",
1501 "your git configuration file before ",
1502 "continuing\n";
1503 }
1504 $seen{$1} = $_;
1505 }
1506 }
1507}
1508
e6434f87
EW
1509sub find_existing_remote {
1510 my ($url, $remotes) = @_;
befc9adc 1511 return undef if $no_reuse_existing;
e6434f87
EW
1512 my $existing;
1513 foreach my $repo_id (keys %$remotes) {
1514 my $u = $remotes->{$repo_id}->{url} or next;
1515 next if $u ne $url;
1516 $existing = $repo_id;
1517 last;
1518 }
1519 $existing;
1520}
b805b44a 1521
e6434f87 1522sub init_remote_config {
d8115c51 1523 my ($self, $url, $no_write) = @_;
e6434f87
EW
1524 $url =~ s!/+$!!; # strip trailing slash
1525 my $r = read_all_remotes();
1526 my $existing = find_existing_remote($url, $r);
1527 if ($existing) {
e518192f
EW
1528 unless ($no_write) {
1529 print STDERR "Using existing ",
1530 "[svn-remote \"$existing\"]\n";
1531 }
e6434f87 1532 $self->{repo_id} = $existing;
4a1bb4c3 1533 } elsif ($_minimize_url) {
e6434f87
EW
1534 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1535 $existing = find_existing_remote($min_url, $r);
1536 if ($existing) {
e518192f
EW
1537 unless ($no_write) {
1538 print STDERR "Using existing ",
1539 "[svn-remote \"$existing\"]\n";
1540 }
e6434f87
EW
1541 $self->{repo_id} = $existing;
1542 }
1543 if ($min_url ne $url) {
e518192f
EW
1544 unless ($no_write) {
1545 print STDERR "Using higher level of URL: ",
1546 "$url => $min_url\n";
1547 }
e6434f87
EW
1548 my $old_path = $self->{path};
1549 $self->{path} = $url;
4e9f6cc7 1550 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1551 if (length $old_path) {
1552 $self->{path} .= "/$old_path";
1553 }
1554 $url = $min_url;
1555 }
1556 }
1557 my $orig_url;
1558 if (!$existing) {
b805b44a 1559 # verify that we aren't overwriting anything:
e6434f87 1560 $orig_url = eval {
706587fc 1561 command_oneline('config', '--get',
e6434f87 1562 "svn-remote.$self->{repo_id}.url")
706587fc 1563 };
b805b44a 1564 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1565 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1566 "$orig_url\nwanted to set to: $url\n";
1567 }
9b981fc6 1568 }
e6434f87
EW
1569 my ($xrepo_id, $xpath) = find_ref($self->refname);
1570 if (defined $xpath) {
1571 die "svn-remote.$xrepo_id.fetch already set to track ",
1572 "$xpath:refs/remotes/", $self->refname, "\n";
1573 }
d8115c51
EW
1574 unless ($no_write) {
1575 command_noisy('config',
1576 "svn-remote.$self->{repo_id}.url", $url);
46cf98ba 1577 $self->{path} =~ s{^/}{};
d8115c51
EW
1578 command_noisy('config', '--add',
1579 "svn-remote.$self->{repo_id}.fetch",
1580 "$self->{path}:".$self->refname);
1581 }
9b981fc6 1582 $self->{url} = $url;
e6434f87
EW
1583}
1584
a8ae2623
EW
1585sub find_by_url { # repos_root and, path are optional
1586 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1587
1a97a506 1588 return undef unless defined $full_url;
56973d20
AR
1589 remove_username($full_url);
1590 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1591 my $remotes = read_all_remotes();
1592 if (defined $full_url && defined $repos_root && !defined $path) {
1593 $path = $full_url;
1594 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1595 }
1596 foreach my $repo_id (keys %$remotes) {
1597 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1598 remove_username($u);
a8ae2623
EW
1599 next if defined $repos_root && $repos_root ne $u;
1600
1601 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1602 foreach (qw/branches tags/) {
1603 resolve_local_globs($u, $fetch,
1604 $remotes->{$repo_id}->{$_});
1605 }
1606 my $p = $path;
0bb91d9a 1607 my $rwr = rewrite_root({repo_id => $repo_id});
63c56022
JA
1608 my $svm = $remotes->{$repo_id}->{svm}
1609 if defined $remotes->{$repo_id}->{svm};
a8ae2623
EW
1610 unless (defined $p) {
1611 $p = $full_url;
0bb91d9a 1612 my $z = $u;
63c56022 1613 my $prefix = '';
0bb91d9a
JG
1614 if ($rwr) {
1615 $z = $rwr;
63c56022
JA
1616 } elsif (defined $svm) {
1617 $z = $svm->{source};
1618 $prefix = $svm->{replace};
1619 $prefix =~ s#^\Q$u\E(?:/|$)##;
1620 $prefix =~ s#/$##;
0bb91d9a 1621 }
63c56022 1622 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
a8ae2623
EW
1623 }
1624 foreach my $f (keys %$fetch) {
1625 next if $f ne $p;
1626 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1627 }
1628 }
1629 undef;
1630}
1631
e6434f87 1632sub init {
d8115c51 1633 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1634 my $self = _new($class, $repo_id, $ref_id, $path);
1635 if (defined $url) {
d8115c51 1636 $self->init_remote_config($url, $no_write);
e6434f87 1637 }
9b981fc6
EW
1638 $self;
1639}
1640
706587fc
EW
1641sub find_ref {
1642 my ($ref_id) = @_;
1643 foreach (command(qw/config -l/)) {
1644 next unless m!^svn-remote\.(.+)\.fetch=
1645 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1646 my ($repo_id, $path, $ref) = ($1, $2, $3);
1647 if ($ref eq $ref_id) {
1648 $path = '' if ($path =~ m#^\./?#);
1649 return ($repo_id, $path);
1650 }
1651 }
1652 (undef, undef, undef);
1653}
1654
9b981fc6 1655sub new {
706587fc
EW
1656 my ($class, $ref_id, $repo_id, $path) = @_;
1657 if (defined $ref_id && !defined $repo_id && !defined $path) {
1658 ($repo_id, $path) = find_ref($ref_id);
1659 if (!defined $repo_id) {
1660 die "Could not find a \"svn-remote.*.fetch\" key ",
1661 "in the repository configuration matching: ",
1662 "refs/remotes/$ref_id\n";
1663 }
1664 }
1665 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1666 if (!defined $self->{path} || !length $self->{path}) {
1667 my $fetch = command_oneline('config', '--get',
1668 "svn-remote.$repo_id.fetch",
1669 ":refs/remotes/$ref_id\$") or
1670 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1671 "\":refs/remotes/$ref_id\$\" in config\n";
1672 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1673 }
706587fc
EW
1674 $self->{url} = command_oneline('config', '--get',
1675 "svn-remote.$repo_id.url") or
1676 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1677 $self->rebuild;
9b981fc6
EW
1678 $self;
1679}
1680
bf655fd7
RE
1681sub refname {
1682 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1683
1684 # It cannot end with a slash /, we'll throw up on this because
1685 # SVN can't have directories with a slash in their name, either:
1686 if ($refname =~ m{/$}) {
1687 die "ref: '$refname' ends with a trailing slash, this is ",
1688 "not permitted by git nor Subversion\n";
1689 }
1690
1691 # It cannot have ASCII control character space, tilde ~, caret ^,
1692 # colon :, question-mark ?, asterisk *, space, or open bracket [
1693 # anywhere.
1694 #
1695 # Additionally, % must be escaped because it is used for escaping
1696 # and we want our escaped refname to be reversible
1697 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1698
1699 # no slash-separated component can begin with a dot .
1700 # /.* becomes /%2E*
1701 $refname =~ s{/\.}{/%2E}g;
1702
1703 # It cannot have two consecutive dots .. anywhere
1704 # .. becomes %2E%2E
1705 $refname =~ s{\.\.}{%2E%2E}g;
1706
1707 return $refname;
1708}
1709
1710sub desanitize_refname {
1711 my ($refname) = @_;
1712 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1713 return $refname;
1714}
9b981fc6 1715
26a62d57
EW
1716sub svm_uuid {
1717 my ($self) = @_;
1718 return $self->{svm}->{uuid} if $self->svm;
1719 $self->ra;
1720 unless ($self->{svm}) {
1721 die "SVM UUID not cached, and reading remotely failed\n";
1722 }
1723 $self->{svm}->{uuid};
1724}
8a49ee97 1725
26a62d57
EW
1726sub svm {
1727 my ($self) = @_;
1728 return $self->{svm} if $self->{svm};
1729 my $svm;
8a49ee97
EW
1730 # see if we have it in our config, first:
1731 eval {
26a62d57
EW
1732 my $section = "svn-remote.$self->{repo_id}";
1733 $svm = {
93f2689c
EW
1734 source => tmp_config('--get', "$section.svm-source"),
1735 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1736 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1737 }
1738 };
befc9adc
EW
1739 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1740 $self->{svm} = $svm;
1741 }
26a62d57
EW
1742 $self->{svm};
1743}
1744
1745sub _set_svm_vars {
1746 my ($self, $ra) = @_;
db03cd24
EW
1747 return $ra if $self->svm;
1748
1749 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1750 "(svm:source, svm:uuid) ",
db03cd24
EW
1751 "from the following URLs:\n" );
1752 sub read_svm_props {
befc9adc
EW
1753 my ($self, $ra, $path, $r) = @_;
1754 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1755 my $src = $props->{'svm:source'};
db03cd24 1756 my $uuid = $props->{'svm:uuid'};
befc9adc 1757 return undef if (!$src || !$uuid);
26a62d57 1758
befc9adc 1759 chomp($src, $uuid);
26a62d57 1760
db03cd24
EW
1761 $uuid =~ m{^[0-9a-f\-]{30,}$}
1762 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1763
1764 # the '!' is used to mark the repos_root!/relative/path
1765 $src =~ s{/?!/?}{/};
db03cd24 1766 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1767 # username is of no interest
8a49ee97 1768 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1769
befc9adc
EW
1770 my $replace = $ra->{url};
1771 $replace .= "/$path" if length $path;
1772
db03cd24 1773 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1774 tmp_config("$section.svm-source", $src);
1775 tmp_config("$section.svm-replace", $replace);
1776 tmp_config("$section.svm-uuid", $uuid);
1777 $self->{svm} = {
1778 source => $src,
1779 uuid => $uuid,
1780 replace => $replace
1781 };
db03cd24
EW
1782 }
1783
1784 my $r = $ra->get_latest_revnum;
1785 my $path = $self->{path};
befc9adc 1786 my %tried;
db03cd24 1787 while (length $path) {
befc9adc
EW
1788 unless ($tried{"$self->{url}/$path"}) {
1789 return $ra if $self->read_svm_props($ra, $path, $r);
1790 $tried{"$self->{url}/$path"} = 1;
db03cd24 1791 }
befc9adc 1792 $path =~ s#/?[^/]+$##;
8a49ee97 1793 }
befc9adc
EW
1794 die "Path: '$path' should be ''\n" if $path ne '';
1795 return $ra if $self->read_svm_props($ra, $path, $r);
1796 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
1797
1798 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 1799 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1800 }
1801
1802 # nope, make sure we're connected to the repository root:
1803 my $ok;
1804 my @tried_b;
1805 $path = $ra->{svn_path};
db03cd24
EW
1806 $ra = Git::SVN::Ra->new($ra->{repos_root});
1807 while (length $path) {
befc9adc
EW
1808 unless ($tried{"$ra->{url}/$path"}) {
1809 $ok = $self->read_svm_props($ra, $path, $r);
1810 last if $ok;
1811 $tried{"$ra->{url}/$path"} = 1;
1812 }
1813 $path =~ s#/?[^/]+$##;
db03cd24 1814 }
befc9adc
EW
1815 die "Path: '$path' should be ''\n" if $path ne '';
1816 $ok ||= $self->read_svm_props($ra, $path, $r);
1817 $tried{"$ra->{url}/$path"} = 1;
db03cd24 1818 if (!$ok) {
befc9adc 1819 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1820 }
1821 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1822}
1823
62e349d2
EW
1824sub svnsync {
1825 my ($self) = @_;
1826 return $self->{svnsync} if $self->{svnsync};
1827
1828 if ($self->no_metadata) {
1829 die "Can't have both 'noMetadata' and ",
1830 "'useSvnsyncProps' options set!\n";
1831 }
1832 if ($self->rewrite_root) {
1833 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1834 "options set!\n";
1835 }
1836
1837 my $svnsync;
1838 # see if we have it in our config, first:
1839 eval {
1840 my $section = "svn-remote.$self->{repo_id}";
98fa5b68
EW
1841
1842 my $url = tmp_config('--get', "$section.svnsync-url");
1843 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1844 die "doesn't look right - svn:sync-from-url is '$url'\n";
1845
1846 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1847 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1848 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1849
1850 $svnsync = { url => $url, uuid => $uuid }
62e349d2
EW
1851 };
1852 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1853 return $self->{svnsync} = $svnsync;
1854 }
1855
1856 my $err = "useSvnsyncProps set, but failed to read " .
1857 "svnsync property: svn:sync-from-";
1858 my $rp = $self->ra->rev_proplist(0);
1859
1860 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
98fa5b68 1861 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
62e349d2
EW
1862 die "doesn't look right - svn:sync-from-url is '$url'\n";
1863
1864 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
98fa5b68 1865 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
62e349d2
EW
1866 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1867
1868 my $section = "svn-remote.$self->{repo_id}";
1869 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1870 tmp_config('--add', "$section.svnsync-url", $url);
1871 return $self->{svnsync} = { url => $url, uuid => $uuid };
1872}
1873
26a62d57
EW
1874# this allows us to memoize our SVN::Ra UUID locally and avoid a
1875# remote lookup (useful for 'git svn log').
1876sub ra_uuid {
1877 my ($self) = @_;
1878 unless ($self->{ra_uuid}) {
1879 my $key = "svn-remote.$self->{repo_id}.uuid";
1880 my $uuid = eval { tmp_config('--get', $key) };
1881 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1882 $self->{ra_uuid} = $uuid;
1883 } else {
1884 die "ra_uuid called without URL\n" unless $self->{url};
1885 $self->{ra_uuid} = $self->ra->get_uuid;
1886 tmp_config('--add', $key, $self->{ra_uuid});
1887 }
1888 }
1889 $self->{ra_uuid};
1890}
1891
a5460eb7
EW
1892sub _set_repos_root {
1893 my ($self, $repos_root) = @_;
1894 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1895 $repos_root ||= $self->ra->{repos_root};
1896 tmp_config($k, $repos_root);
1897 $repos_root;
1898}
1899
1900sub repos_root {
1901 my ($self) = @_;
1902 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1903 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1904}
1905
9b981fc6
EW
1906sub ra {
1907 my ($self) = shift;
8a49ee97 1908 my $ra = Git::SVN::Ra->new($self->{url});
a5460eb7 1909 $self->_set_repos_root($ra->{repos_root});
91b03282
EW
1910 if ($self->use_svm_props && !$self->{svm}) {
1911 if ($self->no_metadata) {
97ae0911
EW
1912 die "Can't have both 'noMetadata' and ",
1913 "'useSvmProps' options set!\n";
62e349d2
EW
1914 } elsif ($self->use_svnsync_props) {
1915 die "Can't have both 'useSvnsyncProps' and ",
1916 "'useSvmProps' options set!\n";
91b03282 1917 }
26a62d57 1918 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
1919 $self->{-want_revprops} = 1;
1920 }
1921 $ra;
9b981fc6
EW
1922}
1923
15710b6f
EW
1924sub rel_path {
1925 my ($self) = @_;
1926 my $repos_root = $self->ra->{repos_root};
1927 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
1928 my $url = $self->{url} .
1929 (length $self->{path} ? "/$self->{path}" : $self->{path});
1930 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1931 $url;
15710b6f
EW
1932}
1933
01bdab84
BS
1934# prop_walk(PATH, REV, SUB)
1935# -------------------------
1936# Recursively traverse PATH at revision REV and invoke SUB for each
1937# directory that contains a SVN property. SUB will be invoked as
1938# follows: &SUB(gs, path, props); where `gs' is this instance of
1939# Git::SVN, `path' the path to the directory where the properties
1940# `props' were found. The `path' will be relative to point of checkout,
1941# that is, if url://repo/trunk is the current Git branch, and that
1942# directory contains a sub-directory `d', SUB will be invoked with `/d/'
1943# as `path' (note the trailing `/').
1944sub prop_walk {
1945 my ($self, $path, $rev, $sub) = @_;
1946
35cda061 1947 $path =~ s#^/##;
01bdab84
BS
1948 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1949 $path =~ s#^/*#/#g;
9b981fc6 1950 my $p = $path;
01bdab84
BS
1951 # Strip the irrelevant part of the path.
1952 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1953 # Ensure the path is terminated by a `/'.
1954 $p =~ s#/*$#/#;
1955
1956 # The properties contain all the internal SVN stuff nobody
1957 # (usually) cares about.
1958 my $interesting_props = 0;
1959 foreach (keys %{$props}) {
1960 # If it doesn't start with `svn:', it must be a
1961 # user-defined property.
1962 ++$interesting_props and next if $_ !~ /^svn:/;
1963 # FIXME: Fragile, if SVN adds new public properties,
1964 # this needs to be updated.
1965 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1966 |eol-style|mime-type
1967 |externals|needs-lock)$/x;
1968 }
1969 &$sub($self, $p, $props) if $interesting_props;
1970
9b981fc6 1971 foreach (sort keys %$dirent) {
0dc03d6a 1972 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
b7166cce 1973 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
9b981fc6
EW
1974 }
1975}
1976
3ebe8df7
EW
1977sub last_rev { ($_[0]->last_rev_commit)[0] }
1978sub last_commit { ($_[0]->last_rev_commit)[1] }
1979
9b981fc6
EW
1980# returns the newest SVN revision number and newest commit SHA1
1981sub last_rev_commit {
1982 my ($self) = @_;
1983 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1984 return ($self->{last_rev}, $self->{last_commit});
1985 }
d2866f9e 1986 my $c = ::verify_ref($self->refname.'^0');
91b03282 1987 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 1988 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
1989 if (defined $rev) {
1990 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1991 return ($rev, $c);
1992 }
1993 }
060610c5
EW
1994 my $map_path = $self->map_path;
1995 unless (-e $map_path) {
26a62d57
EW
1996 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1997 return (undef, undef);
1998 }
66ab84b9 1999 my ($rev, $commit) = $self->rev_map_max(1);
060610c5
EW
2000 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2001 return ($rev, $commit);
9b981fc6
EW
2002}
2003
3ebe8df7
EW
2004sub get_fetch_range {
2005 my ($self, $min, $max) = @_;
2006 $max ||= $self->ra->get_latest_revnum;
060610c5 2007 $min ||= $self->rev_map_max;
3ebe8df7 2008 (++$min, $max);
9b981fc6
EW
2009}
2010
8a49ee97 2011sub tmp_config {
93f2689c 2012 my (@args) = @_;
b7e5348c
EW
2013 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2014 my $config = "$ENV{GIT_DIR}/svn/.metadata";
38570a47 2015 if (! -f $config && -f $old_def_config) {
b7e5348c
EW
2016 rename $old_def_config, $config or
2017 die "Failed rename $old_def_config => $config: $!\n";
2018 }
8a49ee97 2019 my $old_config = $ENV{GIT_CONFIG};
93f2689c 2020 $ENV{GIT_CONFIG} = $config;
8a49ee97 2021 $@ = undef;
b4d57e5e
EW
2022 my @ret = eval {
2023 unless (-f $config) {
2024 mkfile($config);
2025 open my $fh, '>', $config or
2026 die "Can't open $config: $!\n";
2027 print $fh "; This file is used internally by ",
2028 "git-svn\n" or die
2029 "Couldn't write to $config: $!\n";
2030 print $fh "; You should not have to edit it\n" or
2031 die "Couldn't write to $config: $!\n";
2032 close $fh or die "Couldn't close $config: $!\n";
2033 }
2034 command('config', @args);
2035 };
8a49ee97
EW
2036 my $err = $@;
2037 if (defined $old_config) {
2038 $ENV{GIT_CONFIG} = $old_config;
2039 } else {
2040 delete $ENV{GIT_CONFIG};
2041 }
2042 die $err if $err;
2043 wantarray ? @ret : $ret[0];
2044}
2045
9b981fc6
EW
2046sub tmp_index_do {
2047 my ($self, $sub) = @_;
2048 my $old_index = $ENV{GIT_INDEX_FILE};
2049 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 2050 $@ = undef;
b4d57e5e
EW
2051 my @ret = eval {
2052 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2053 mkpath([$dir]) unless -d $dir;
2054 &$sub;
2055 };
8a49ee97
EW
2056 my $err = $@;
2057 if (defined $old_index) {
9b981fc6
EW
2058 $ENV{GIT_INDEX_FILE} = $old_index;
2059 } else {
2060 delete $ENV{GIT_INDEX_FILE};
2061 }
8a49ee97 2062 die $err if $err;
9b981fc6
EW
2063 wantarray ? @ret : $ret[0];
2064}
2065
2066sub assert_index_clean {
2067 my ($self, $treeish) = @_;
2068
2069 $self->tmp_index_do(sub {
2070 command_noisy('read-tree', $treeish) unless -e $self->{index};
2071 my $x = command_oneline('write-tree');
2072 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2073 /^tree ($::sha1)/mo);
e8d120bd
EW
2074 return if $y eq $x;
2075
2076 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2077 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2078 command_noisy('read-tree', $treeish);
9b981fc6
EW
2079 $x = command_oneline('write-tree');
2080 if ($y ne $x) {
2081 ::fatal "trees ($treeish) $y != $x\n",
207f1a75 2082 "Something is seriously wrong...";
9b981fc6
EW
2083 }
2084 });
2085}
2086
2087sub get_commit_parents {
0af9c9f9 2088 my ($self, $log_entry) = @_;
9b981fc6 2089 my (%seen, @ret, @tmp);
0af9c9f9
EW
2090 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2091 if (my $ip = $self->{inject_parents}) {
2092 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2093 push @tmp, $commit;
9b981fc6
EW
2094 }
2095 }
d2866f9e 2096 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
2097 push @tmp, $cur;
2098 }
733a65aa
EW
2099 if (my $ipd = $self->{inject_parents_dcommit}) {
2100 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2101 push @tmp, @$commit;
2102 }
2103 }
44320b9e 2104 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
2105 while (my $p = shift @tmp) {
2106 next if $seen{$p};
2107 $seen{$p} = 1;
2108 push @ret, $p;
2109 # MAXPARENT is defined to 16 in commit-tree.c:
2110 last if @ret >= 16;
2111 }
2112 if (@tmp) {
44320b9e 2113 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
2114 join("\n\t", @tmp), "\n";
2115 }
2116 @ret;
2117}
2118
aea736cc
EW
2119sub rewrite_root {
2120 my ($self) = @_;
2121 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2122 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2123 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2124 if ($rwr) {
2125 $rwr =~ s#/+$##;
2126 if ($rwr !~ m#^[a-z\+]+://#) {
2127 die "$rwr is not a valid URL (key: $k)\n";
2128 }
2129 }
2130 $self->{-rewrite_root} = $rwr;
2131}
2132
2133sub metadata_url {
2134 my ($self) = @_;
2135 ($self->rewrite_root || $self->{url}) .
2136 (length $self->{path} ? '/' . $self->{path} : '');
2137}
2138
706587fc 2139sub full_url {
9b981fc6 2140 my ($self) = @_;
5d3b7cd5 2141 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
2142}
2143
ad94802a
EW
2144
2145sub set_commit_header_env {
2146 my ($log_entry) = @_;
2147 my %env;
2148 foreach my $ned (qw/NAME EMAIL DATE/) {
2149 foreach my $ac (qw/AUTHOR COMMITTER/) {
2150 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2151 }
9b981fc6 2152 }
ad94802a 2153
70ae04e4
AW
2154 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2155 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
44320b9e 2156 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 2157
70ae04e4
AW
2158 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2159 ? $log_entry->{commit_name}
2160 : $log_entry->{name};
2161 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2162 ? $log_entry->{commit_email}
2163 : $log_entry->{email};
ad94802a
EW
2164 \%env;
2165}
70ae04e4 2166
ad94802a
EW
2167sub restore_commit_header_env {
2168 my ($env) = @_;
2169 foreach my $ned (qw/NAME EMAIL DATE/) {
2170 foreach my $ac (qw/AUTHOR COMMITTER/) {
2171 my $k = "GIT_${ac}_${ned}";
2172 if (defined $env->{$k}) {
2173 $ENV{$k} = $env->{$k};
2174 } else {
2175 delete $ENV{$k};
2176 }
2177 }
2178 }
2179}
2180
94bc914c
KW
2181sub gc {
2182 command_noisy('gc', '--auto');
2183};
2184
ad94802a
EW
2185sub do_git_commit {
2186 my ($self, $log_entry) = @_;
2187 my $lr = $self->last_rev;
2188 if (defined $lr && $lr >= $log_entry->{revision}) {
2189 die "Last fetched revision of ", $self->refname,
2190 " was r$lr, but we are about to fetch: ",
2191 "r$log_entry->{revision}!\n";
2192 }
2193 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2194 croak "$log_entry->{revision} = $c already exists! ",
2195 "Why are we refetching it?\n";
2196 }
2197 my $old_env = set_commit_header_env($log_entry);
44320b9e 2198 my $tree = $log_entry->{tree};
9b981fc6
EW
2199 if (!defined $tree) {
2200 $tree = $self->tmp_index_do(sub {
2201 command_oneline('write-tree') });
2202 }
2203 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2204
e855bfc0 2205 my @exec = ('git', 'commit-tree', $tree);
0af9c9f9 2206 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
2207 push @exec, '-p', $_;
2208 }
2209 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2210 or croak $!;
44320b9e 2211 print $msg_fh $log_entry->{log} or croak $!;
ad94802a 2212 restore_commit_header_env($old_env);
91b03282 2213 unless ($self->no_metadata) {
8a49ee97
EW
2214 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2215 or croak $!;
9760adcc 2216 }
9b981fc6
EW
2217 $msg_fh->flush == 0 or croak $!;
2218 close $msg_fh or croak $!;
2219 chomp(my $commit = do { local $/; <$out_fh> });
2220 close $out_fh or croak $!;
2221 waitpid $pid, 0;
2222 croak $? if $?;
2223 if ($commit !~ /^$::sha1$/o) {
2224 die "Failed to commit, invalid sha1: $commit\n";
2225 }
2226
060610c5 2227 $self->rev_map_set($log_entry->{revision}, $commit, 1);
9b981fc6 2228
44320b9e 2229 $self->{last_rev} = $log_entry->{revision};
9b981fc6 2230 $self->{last_commit} = $commit;
8a49ee97
EW
2231 print "r$log_entry->{revision}";
2232 if (defined $log_entry->{svm_revision}) {
2233 print " (\@$log_entry->{svm_revision})";
060610c5 2234 $self->rev_map_set($log_entry->{svm_revision}, $commit,
26a62d57 2235 0, $self->svm_uuid);
8a49ee97
EW
2236 }
2237 print " = $commit ($self->{ref_id})\n";
94bc914c
KW
2238 if (--$_gc_nr == 0) {
2239 $_gc_nr = $_gc_period;
2240 gc();
2241 }
9b981fc6
EW
2242 return $commit;
2243}
2244
fbcc1737
EW
2245sub match_paths {
2246 my ($self, $paths, $r) = @_;
4e9f6cc7 2247 return 1 if $self->{path} eq '';
d542aedb
EW
2248 if (my $path = $paths->{"/$self->{path}"}) {
2249 return ($path->{action} eq 'D') ? 0 : 1;
2250 }
4e9f6cc7 2251 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
2252 if (grep /$self->{path_regex}/, keys %$paths) {
2253 return 1;
2254 }
2255 my $c = '';
2256 foreach (split m#/#, $self->{path}) {
2257 $c .= "/$_";
74a81227
EW
2258 next unless ($paths->{$c} &&
2259 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
2260 if ($self->ra->check_path($self->{path}, $r) ==
2261 $SVN::Node::dir) {
fbcc1737
EW
2262 return 1;
2263 }
2264 }
2265 return 0;
2266}
2267
15710b6f
EW
2268sub find_parent_branch {
2269 my ($self, $paths, $rev) = @_;
91b03282 2270 return undef unless $self->follow_parent;
e5a0b240 2271 unless (defined $paths) {
c7eba716
EW
2272 my $err_handler = $SVN::Error::handler;
2273 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
2274 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2275 $paths =
2276 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 2277 $SVN::Error::handler = $err_handler;
e5a0b240
EW
2278 }
2279 return undef unless defined $paths;
15710b6f
EW
2280
2281 # look for a parent from another branch:
7f578c55
EW
2282 my @b_path_components = split m#/#, $self->rel_path;
2283 my @a_path_components;
2284 my $i;
2285 while (@b_path_components) {
2286 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 2287 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
2288 unshift(@a_path_components, pop(@b_path_components));
2289 }
74a81227
EW
2290 return undef unless defined $i && defined $i->{copyfrom_path};
2291 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
2292 if (@a_path_components) {
2293 print STDERR "branch_from: $branch_from => ";
2294 $branch_from .= '/'.join('/', @a_path_components);
2295 print STDERR $branch_from, "\n";
2296 }
3ebe8df7 2297 my $r = $i->{copyfrom_rev};
15710b6f
EW
2298 my $repos_root = $self->ra->{repos_root};
2299 my $url = $self->ra->{url};
2300 my $new_url = $repos_root . $branch_from;
2301 print STDERR "Found possible branch point: ",
2302 "$new_url => ", $self->full_url, ", $r\n";
2303 $branch_from =~ s#^/##;
a8ae2623 2304 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
15710b6f 2305 unless ($gs) {
ce2a0f2f
EW
2306 my $ref_id = $self->{ref_id};
2307 $ref_id =~ s/\@\d+$//;
2308 $ref_id .= "\@$r";
15710b6f
EW
2309 # just grow a tail if we're not unique enough :x
2310 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 2311 print STDERR "Initializing parent: $ref_id\n";
f61cc48d 2312 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
c586879c
EW
2313 if ($u =~ s#^\Q$url\E(/|$)##) {
2314 $p = $u;
2315 $u = $url;
f61cc48d 2316 $repo_id = $self->{repo_id};
c586879c 2317 }
f61cc48d 2318 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
15710b6f
EW
2319 }
2320 my ($r0, $parent) = $gs->find_rev_before($r, 1);
553589f7
DM
2321 {
2322 my ($base, $head);
2323 if (!defined $r0 || !defined $parent) {
2324 ($base, $head) = parse_revision_argument(0, $r);
2325 } else {
2326 if ($r0 < $r) {
2327 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2328 0, 1, sub { $base = $_[1] - 1 });
2329 }
2330 }
2331 if (defined $base && $base <= $r) {
d627de6b
EW
2332 $gs->fetch($base, $r);
2333 }
553589f7 2334 ($r0, $parent) = $gs->find_rev_before($r, 1);
15710b6f 2335 }
ef70de96 2336 if (defined $r0 && defined $parent) {
15710b6f 2337 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
2338 my $ed;
2339 if ($self->ra->can_do_switch) {
2e5e2480 2340 $self->assert_index_clean($parent);
8b8fc068 2341 print STDERR "Following parent with do_switch\n";
15710b6f 2342 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 2343 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
2344 # at the moment), so we can't rely on it
2345 $self->{last_commit} = $parent;
2346 $ed = SVN::Git::Fetcher->new($self);
8a603774 2347 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
2348 $self->full_url, $ed)
2349 or die "SVN connection failed somewhere...\n";
9ff74e95
SW
2350 } elsif ($self->ra->trees_match($new_url, $r0,
2351 $self->full_url, $rev)) {
2352 print STDERR "Trees match:\n",
2353 " $new_url\@$r0\n",
2354 " ${\$self->full_url}\@$rev\n",
2355 "Following parent with no changes\n";
2356 $self->tmp_index_do(sub {
2357 command_noisy('read-tree', $parent);
2358 });
2359 $self->{last_commit} = $parent;
15710b6f 2360 } else {
8b8fc068 2361 print STDERR "Following parent with do_update\n";
15710b6f 2362 $ed = SVN::Git::Fetcher->new($self);
8a603774 2363 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
2364 or die "SVN connection failed somewhere...\n";
2365 }
f7c3fc4a 2366 print STDERR "Successfully followed parent\n";
15710b6f
EW
2367 return $self->make_log_entry($rev, [$parent], $ed);
2368 }
15710b6f
EW
2369 return undef;
2370}
2371
9b981fc6 2372sub do_fetch {
706587fc 2373 my ($self, $paths, $rev) = @_;
15710b6f 2374 my $ed;
9b981fc6 2375 my ($last_rev, @parents);
b9dffd8c
EW
2376 if (my $lc = $self->last_commit) {
2377 # we can have a branch that was deleted, then re-added
2378 # under the same name but copied from another path, in
2379 # which case we'll have multiple parents (we don't
2380 # want to break the original ref, nor lose copypath info):
2381 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2382 push @{$log_entry->{parents}}, $lc;
2383 return $log_entry;
2384 }
15710b6f 2385 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2386 $last_rev = $self->{last_rev};
b9dffd8c
EW
2387 $ed->{c} = $lc;
2388 @parents = ($lc);
9b981fc6
EW
2389 } else {
2390 $last_rev = $rev;
15710b6f
EW
2391 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2392 return $log_entry;
2393 }
2394 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2395 }
8a603774 2396 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
2397 die "SVN connection failed somewhere...\n";
2398 }
2399 $self->make_log_entry($rev, \@parents, $ed);
2400}
2401
97f6987a
EW
2402sub get_untracked {
2403 my ($self, $ed) = @_;
2404 my @out;
2405 my $h = $ed->{empty};
9b981fc6
EW
2406 foreach (sort keys %$h) {
2407 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 2408 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
2409 warn "W: $act: $_\n";
2410 }
2411 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 2412 $h = $ed->{$t} or next;
9b981fc6
EW
2413 foreach my $path (sort keys %$h) {
2414 my $ppath = $path eq '' ? '.' : $path;
2415 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 2416 next if $SKIP_PROP{$prop};
9b981fc6 2417 my $v = $h->{$path}->{$prop};
97f6987a
EW
2418 my $t_ppath_prop = "$t: " .
2419 uri_encode($ppath) . ' ' .
2420 uri_encode($prop);
9b981fc6 2421 if (defined $v) {
97f6987a
EW
2422 push @out, " +$t_ppath_prop " .
2423 uri_encode($v);
9b981fc6 2424 } else {
97f6987a 2425 push @out, " -$t_ppath_prop";
9b981fc6
EW
2426 }
2427 }
2428 }
2429 }
2430 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 2431 $h = $ed->{$t} or next;
9b981fc6
EW
2432 foreach my $parent (sort keys %$h) {
2433 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
2434 push @out, " $t: " .
2435 uri_encode("$parent/$path");
9b981fc6
EW
2436 warn "W: $t: $parent/$path ",
2437 "Insufficient permissions?\n";
2438 }
2439 }
2440 }
97f6987a 2441 \@out;
9b981fc6
EW
2442}
2443
1c8443b0
EW
2444sub parse_svn_date {
2445 my $date = shift || return '+0000 1970-01-01 00:00:00';
2446 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2447 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2448 croak "Unable to parse date: $date\n";
2449 "+0000 $Y-$m-$d $H:$M:$S";
2450}
2451
2452sub check_author {
2453 my ($author) = @_;
2454 if (!defined $author || length $author == 0) {
2455 $author = '(no author)';
9231f500 2456 } elsif (defined $::_authors && ! defined $::users{$author}) {
1c8443b0
EW
2457 die "Author: $author not defined in $::_authors file\n";
2458 }
2459 $author;
2460}
2461
9b981fc6 2462sub make_log_entry {
97f6987a
EW
2463 my ($self, $rev, $parents, $ed) = @_;
2464 my $untracked = $self->get_untracked($ed);
2465
9b981fc6 2466 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
2467 print $un "r$rev\n" or croak $!;
2468 print $un $_, "\n" foreach @$untracked;
2469 my %log_entry = ( parents => $parents || [], revision => $rev,
2470 log => '');
fbcc1737 2471
8a49ee97 2472 my $headrev;
fbcc1737 2473 my $logged = delete $self->{logged_rev_props};
8a49ee97 2474 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
2475 my $rp = $self->ra->rev_proplist($rev);
2476 foreach (sort keys %$rp) {
2477 my $v = $rp->{$_};
2478 if (/^svn:(author|date|log)$/) {
2479 $log_entry{$1} = $v;
8a49ee97
EW
2480 } elsif ($_ eq 'svm:headrev') {
2481 $headrev = $v;
fbcc1737
EW
2482 } else {
2483 print $un " rev_prop: ", uri_encode($_), ' ',
2484 uri_encode($v), "\n";
2485 }
9b981fc6 2486 }
fbcc1737
EW
2487 } else {
2488 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
2489 }
2490 close $un or croak $!;
97f6987a 2491
9b981fc6 2492 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 2493 $log_entry{log} .= "\n";
db03cd24
EW
2494 my $author = $log_entry{author} = check_author($log_entry{author});
2495 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
70ae04e4
AW
2496 : ($author, undef);
2497
2498 my ($commit_name, $commit_email) = ($name, $email);
2499 if ($_use_log_author) {
5ff6aae8
AW
2500 my $name_field;
2501 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2502 $name_field = $1;
2503 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2504 $name_field = $1;
2505 }
2506 if (!defined $name_field) {
abfa533d
SB
2507 if (!defined $email) {
2508 $email = $name;
2509 }
5ff6aae8 2510 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
70ae04e4 2511 ($name, $email) = ($1, $2);
5ff6aae8
AW
2512 } elsif ($name_field =~ /(.*)@/) {
2513 ($name, $email) = ($1, $name_field);
2514 } else {
abfa533d 2515 ($name, $email) = ($name_field, $name_field);
70ae04e4
AW
2516 }
2517 }
91b03282 2518 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
2519 if ($self->rewrite_root) {
2520 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2521 "options set!\n";
2522 }
8a49ee97 2523 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
2524 # we don't want "SVM: initializing mirror for junk" ...
2525 return undef if $r == 0;
2526 my $svm = $self->svm;
2527 if ($uuid ne $svm->{uuid}) {
8a49ee97 2528 die "UUID mismatch on SVM path:\n",
befc9adc 2529 "expected: $svm->{uuid}\n",
8a49ee97
EW
2530 " got: $uuid\n";
2531 }
befc9adc
EW
2532 my $full_url = $self->full_url;
2533 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2534 die "Failed to replace '$svm->{replace}' with ",
2535 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
2536 # throw away username for storing in records
2537 remove_username($full_url);
8a49ee97
EW
2538 $log_entry{metadata} = "$full_url\@$r $uuid";
2539 $log_entry{svm_revision} = $r;
70ae04e4
AW
2540 $email ||= "$author\@$uuid";
2541 $commit_email ||= "$author\@$uuid";
62e349d2
EW
2542 } elsif ($self->use_svnsync_props) {
2543 my $full_url = $self->svnsync->{url};
2544 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 2545 remove_username($full_url);
62e349d2
EW
2546 my $uuid = $self->svnsync->{uuid};
2547 $log_entry{metadata} = "$full_url\@$rev $uuid";
70ae04e4
AW
2548 $email ||= "$author\@$uuid";
2549 $commit_email ||= "$author\@$uuid";
8a49ee97 2550 } else {
ce118739
AR
2551 my $url = $self->metadata_url;
2552 remove_username($url);
2553 $log_entry{metadata} = "$url\@$rev " .
26a62d57 2554 $self->ra->get_uuid;
db03cd24 2555 $email ||= "$author\@" . $self->ra->get_uuid;
70ae04e4 2556 $commit_email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 2557 }
db03cd24
EW
2558 $log_entry{name} = $name;
2559 $log_entry{email} = $email;
70ae04e4
AW
2560 $log_entry{commit_name} = $commit_name;
2561 $log_entry{commit_email} = $commit_email;
9b981fc6
EW
2562 \%log_entry;
2563}
2564
2565sub fetch {
3ebe8df7 2566 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 2567 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 2568 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 2569 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
2570}
2571
2572sub set_tree_cb {
2573 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
2574 $self->{inject_parents} = { $rev => $tree };
2575 $self->fetch(undef, undef);
9b981fc6
EW
2576}
2577
2578sub set_tree {
2579 my ($self, $tree) = (shift, shift);
1ce255dc 2580 my $log_entry = ::get_commit_entry($tree);
9b981fc6 2581 unless ($self->{last_rev}) {
0a1a1c86 2582 ::fatal("Must have an existing revision to commit");
9b981fc6 2583 }
61395354
EW
2584 my %ed_opts = ( r => $self->{last_rev},
2585 log => $log_entry->{log},
2586 ra => $self->ra,
2587 tree_a => $self->{last_commit},
2588 tree_b => $tree,
2589 editor_cb => sub {
2590 $self->set_tree_cb($log_entry, $tree, @_) },
2591 svn_path => $self->{path} );
2592 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
2593 print "No changes\nr$self->{last_rev} = $tree\n";
2594 }
9b981fc6
EW
2595}
2596
060610c5
EW
2597sub rebuild_from_rev_db {
2598 my ($self, $path) = @_;
2599 my $r = -1;
2600 open my $fh, '<', $path or croak "open: $!";
4f7ec797 2601 binmode $fh or croak "binmode: $!";
060610c5
EW
2602 while (<$fh>) {
2603 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2604 chomp($_);
2605 ++$r;
2606 next if $_ eq ('0' x 40);
2607 $self->rev_map_set($r, $_);
2608 print "r$r = $_\n";
2609 }
2610 close $fh or croak "close: $!";
2611 unlink $path or croak "unlink: $!";
2612}
2613
f0ecca10
EW
2614sub rebuild {
2615 my ($self) = @_;
060610c5
EW
2616 my $map_path = $self->map_path;
2617 return if (-e $map_path && ! -z $map_path);
d6d3346b 2618 return unless ::verify_ref($self->refname.'^0');
060610c5
EW
2619 if ($self->use_svm_props || $self->no_metadata) {
2620 my $rev_db = $self->rev_db_path;
2621 $self->rebuild_from_rev_db($rev_db);
2622 if ($self->use_svm_props) {
2623 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2624 $self->rebuild_from_rev_db($svm_rev_db);
2625 }
2626 $self->unlink_rev_db_symlink;
26a62d57
EW
2627 return;
2628 }
060610c5
EW
2629 print "Rebuilding $map_path ...\n";
2630 my ($log, $ctx) =
2631 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2632 $self->refname, '--');
74b1e123
JK
2633 my $metadata_url = $self->metadata_url;
2634 remove_username($metadata_url);
060610c5 2635 my $svn_uuid = $self->ra_uuid;
3dfab993
SV
2636 my $c;
2637 while (<$log>) {
2638 if ( m{^commit ($::sha1)$} ) {
2639 $c = $1;
2640 next;
2641 }
2642 next unless s{^\s*(git-svn-id:)}{$1};
2643 my ($url, $rev, $uuid) = ::extract_metadata($_);
18ea92bd 2644 remove_username($url);
f0ecca10
EW
2645
2646 # ignore merges (from set-tree)
2647 next if (!defined $rev || !$uuid);
2648
2649 # if we merged or otherwise started elsewhere, this is
2650 # how we break out of it
060610c5 2651 if (($uuid ne $svn_uuid) ||
74b1e123 2652 ($metadata_url && $url && ($url ne $metadata_url))) {
f0ecca10
EW
2653 next;
2654 }
f0ecca10 2655
060610c5 2656 $self->rev_map_set($rev, $c);
f0ecca10
EW
2657 print "r$rev = $c\n";
2658 }
3dfab993 2659 command_close_pipe($log, $ctx);
060610c5
EW
2660 print "Done rebuilding $map_path\n";
2661 my $rev_db_path = $self->rev_db_path;
2662 if (-f $self->rev_db_path) {
2663 unlink $self->rev_db_path or croak "unlink: $!";
2664 }
2665 $self->unlink_rev_db_symlink;
f0ecca10
EW
2666}
2667
060610c5 2668# rev_map:
9b981fc6
EW
2669# Tie::File seems to be prone to offset errors if revisions get sparse,
2670# it's not that fast, either. Tie::File is also not in Perl 5.6. So
2671# one of my favorite modules is out :< Next up would be one of the DBM
060610c5
EW
2672# modules, but I'm not sure which is most portable...
2673#
2674# This is the replacement for the rev_db format, which was too big
2675# and inefficient for large repositories with a lot of sparse history
2676# (mainly tags)
2677#
2678# The format is this:
2679# - 24 bytes for every record,
2680# * 4 bytes for the integer representing an SVN revision number
2681# * 20 bytes representing the sha1 of a git commit
2682# - No empty padding records like the old format
66ab84b9 2683# (except the last record, which can be overwritten)
060610c5
EW
2684# - new records are written append-only since SVN revision numbers
2685# increase monotonically
2686# - lookups on SVN revision number are done via a binary search
66ab84b9
EW
2687# - Piping the file to xxd -c24 is a good way of dumping it for
2688# viewing or editing (piped back through xxd -r), should the need
2689# ever arise.
2690# - The last record can be padding revision with an all-zero sha1
2691# This is used to optimize fetch performance when using multiple
2692# "fetch" directives in .git/config
060610c5 2693#
97ae0911 2694# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 2695
060610c5 2696sub _rev_map_set {
26a62d57 2697 my ($fh, $rev, $commit) = @_;
060610c5 2698
4f7ec797 2699 binmode $fh or croak "binmode: $!";
060610c5
EW
2700 my $size = (stat($fh))[7];
2701 ($size % 24) == 0 or croak "inconsistent size: $size";
2702
66ab84b9 2703 my $wr_offset = 0;
060610c5
EW
2704 if ($size > 0) {
2705 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2706 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2707 $read == 24 or croak "read only $read bytes (!= 24)";
2708 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
2709 if ($last_commit eq ('0' x40)) {
2710 if ($size >= 48) {
2711 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2712 $read = sysread($fh, $buf, 24) or
2713 croak "read: $!";
2714 $read == 24 or
2715 croak "read only $read bytes (!= 24)";
2716 ($last_rev, $last_commit) =
2717 unpack(rev_map_fmt, $buf);
2718 if ($last_commit eq ('0' x40)) {
2719 croak "inconsistent .rev_map\n";
2720 }
2721 }
2722 if ($last_rev >= $rev) {
2723 croak "last_rev is higher!: $last_rev >= $rev";
2724 }
2725 $wr_offset = -24;
26a62d57
EW
2726 }
2727 }
66ab84b9 2728 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
060610c5
EW
2729 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2730 croak "write: $!";
26a62d57
EW
2731}
2732
2733sub mkfile {
2734 my ($path) = @_;
2735 unless (-e $path) {
2736 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2737 mkpath([$dir]) unless -d $dir;
2738 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2739 close $fh or die "Couldn't close (create) $path: $!\n";
2740 }
2741}
2742
060610c5 2743sub rev_map_set {
26a62d57
EW
2744 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2745 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
060610c5 2746 my $db = $self->map_path($uuid);
26a62d57 2747 my $db_lock = "$db.lock";
373274f9
EW
2748 my $sig;
2749 if ($update_ref) {
2750 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2751 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2752 }
26a62d57
EW
2753 mkfile($db);
2754
373274f9 2755 $LOCKFILES{$db_lock} = 1;
97ae0911 2756 my $sync;
97ae0911
EW
2757 # both of these options make our .rev_db file very, very important
2758 # and we can't afford to lose it because rebuild() won't work
2759 if ($self->use_svm_props || $self->no_metadata) {
2760 $sync = 1;
060610c5 2761 copy($db, $db_lock) or die "rev_map_set(@_): ",
26a62d57 2762 "Failed to copy: ",
373274f9
EW
2763 "$db => $db_lock ($!)\n";
2764 } else {
060610c5 2765 rename $db, $db_lock or die "rev_map_set(@_): ",
26a62d57 2766 "Failed to rename: ",
373274f9
EW
2767 "$db => $db_lock ($!)\n";
2768 }
060610c5 2769
66ab84b9 2770 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
060610c5
EW
2771 or croak "Couldn't open $db_lock: $!\n";
2772 _rev_map_set($fh, $rev, $commit);
97ae0911
EW
2773 if ($sync) {
2774 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2775 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2776 }
9b981fc6 2777 close $fh or croak $!;
373274f9 2778 if ($update_ref) {
1e889ef3 2779 $_head = $self;
373274f9
EW
2780 command_noisy('update-ref', '-m', "r$rev",
2781 $self->refname, $commit);
2782 }
060610c5 2783 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
373274f9
EW
2784 "$db_lock => $db ($!)\n";
2785 delete $LOCKFILES{$db_lock};
2786 if ($update_ref) {
2787 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2788 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2789 kill $sig, $$ if defined $sig;
2790 }
9b981fc6
EW
2791}
2792
66ab84b9
EW
2793# If want_commit, this will return an array of (rev, commit) where
2794# commit _must_ be a valid commit in the archive.
2795# Otherwise, it'll return the max revision (whether or not the
2796# commit is valid or just a 0x40 placeholder).
060610c5 2797sub rev_map_max {
66ab84b9 2798 my ($self, $want_commit) = @_;
d6d3346b 2799 $self->rebuild;
060610c5 2800 my $map_path = $self->map_path;
66ab84b9 2801 stat $map_path or return $want_commit ? (0, undef) : 0;
060610c5 2802 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 2803 binmode $fh or croak "binmode: $!";
060610c5
EW
2804 my $size = (stat($fh))[7];
2805 ($size % 24) == 0 or croak "inconsistent size: $size";
2806
2807 if ($size == 0) {
2808 close $fh or croak "close: $!";
66ab84b9 2809 return $want_commit ? (0, undef) : 0;
060610c5
EW
2810 }
2811
66ab84b9 2812 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
060610c5 2813 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
060610c5 2814 my ($r, $c) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
2815 if ($want_commit && $c eq ('0' x40)) {
2816 if ($size < 48) {
2817 return $want_commit ? (0, undef) : 0;
2818 }
2819 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2820 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2821 ($r, $c) = unpack(rev_map_fmt, $buf);
2822 if ($c eq ('0'x40)) {
2823 croak "Penultimate record is all-zeroes in $map_path";
2824 }
2825 }
2826 close $fh or croak "close: $!";
2827 $want_commit ? ($r, $c) : $r;
9c93fee5
EW
2828}
2829
060610c5 2830sub rev_map_get {
26a62d57 2831 my ($self, $rev, $uuid) = @_;
060610c5
EW
2832 my $map_path = $self->map_path($uuid);
2833 return undef unless -e $map_path;
2834
2835 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 2836 binmode $fh or croak "binmode: $!";
060610c5
EW
2837 my $size = (stat($fh))[7];
2838 ($size % 24) == 0 or croak "inconsistent size: $size";
2839
2840 if ($size == 0) {
2841 close $fh or croak "close: $fh";
2842 return undef;
2843 }
2844
2845 my ($l, $u) = (0, $size - 24);
2846 my ($r, $c, $buf);
2847
2848 while ($l <= $u) {
2849 my $i = int(($l/24 + $u/24) / 2) * 24;
2850 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2851 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2852 my ($r, $c) = unpack('NH40', $buf);
2853
2854 if ($r < $rev) {
2855 $l = $i + 24;
2856 } elsif ($r > $rev) {
2857 $u = $i - 24;
2858 } else { # $r == $rev
2859 close($fh) or croak "close: $!";
66ab84b9 2860 return $c eq ('0' x 40) ? undef : $c;
060610c5 2861 }
9b981fc6 2862 }
060610c5
EW
2863 close($fh) or croak "close: $!";
2864 undef;
9b981fc6
EW
2865}
2866
111947ef
DK
2867# Finds the first svn revision that exists on (if $eq_ok is true) or
2868# before $rev for the current branch. It will not search any lower
2869# than $min_rev. Returns the git commit hash and svn revision number
2870# if found, else (undef, undef).
15710b6f 2871sub find_rev_before {
111947ef 2872 my ($self, $rev, $eq_ok, $min_rev) = @_;
15710b6f 2873 --$rev unless $eq_ok;
111947ef
DK
2874 $min_rev ||= 1;
2875 while ($rev >= $min_rev) {
060610c5 2876 if (my $c = $self->rev_map_get($rev)) {
15710b6f
EW
2877 return ($rev, $c);
2878 }
2879 --$rev;
2880 }
2881 return (undef, undef);
2882}
2883
111947ef
DK
2884# Finds the first svn revision that exists on (if $eq_ok is true) or
2885# after $rev for the current branch. It will not search any higher
2886# than $max_rev. Returns the git commit hash and svn revision number
2887# if found, else (undef, undef).
2888sub find_rev_after {
2889 my ($self, $rev, $eq_ok, $max_rev) = @_;
2890 ++$rev unless $eq_ok;
060610c5 2891 $max_rev ||= $self->rev_map_max;
111947ef 2892 while ($rev <= $max_rev) {
060610c5 2893 if (my $c = $self->rev_map_get($rev)) {
111947ef
DK
2894 return ($rev, $c);
2895 }
2896 ++$rev;
2897 }
2898 return (undef, undef);
2899}
2900
9b981fc6 2901sub _new {
706587fc
EW
2902 my ($class, $repo_id, $ref_id, $path) = @_;
2903 unless (defined $repo_id && length $repo_id) {
2904 $repo_id = $Git::SVN::default_repo_id;
2905 }
2906 unless (defined $ref_id && length $ref_id) {
8b8fc068 2907 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc 2908 }
7829f20f 2909 $_[1] = $repo_id;
706587fc
EW
2910 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2911 $_[3] = $path = '' unless (defined $path);
b4d57e5e 2912 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
2913 bless {
2914 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 2915 path => $path, config => "$ENV{GIT_DIR}/svn/config",
060610c5 2916 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
26a62d57
EW
2917}
2918
060610c5
EW
2919# for read-only access of old .rev_db formats
2920sub unlink_rev_db_symlink {
2921 my ($self) = @_;
2922 my $link = $self->rev_db_path;
2923 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2924 if (-l $link) {
2925 unlink $link or croak "unlink: $link failed!";
2926 }
2927}
2928
2929sub rev_db_path {
2930 my ($self, $uuid) = @_;
2931 my $db_path = $self->map_path($uuid);
2932 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2933 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2934 $db_path;
2935}
2936
2937# the new replacement for .rev_db
2938sub map_path {
26a62d57
EW
2939 my ($self, $uuid) = @_;
2940 $uuid ||= $self->ra_uuid;
060610c5 2941 "$self->{map_root}.$uuid";
9b981fc6
EW
2942}
2943
1c8443b0
EW
2944sub uri_encode {
2945 my ($f) = @_;
2946 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2947 $f
2948}
9b981fc6 2949
18ea92bd
SV
2950sub remove_username {
2951 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2952}
2953
d976acfd
EW
2954package Git::SVN::Prompt;
2955use strict;
2956use warnings;
2957require SVN::Core;
2958use vars qw/$_no_auth_cache $_username/;
2959
2960sub simple {
30d055aa
EW
2961 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2962 $may_save = undef if $_no_auth_cache;
2963 $default_username = $_username if defined $_username;
2964 if (defined $default_username && length $default_username) {
2965 if (defined $realm && length $realm) {
6f729591
EW
2966 print STDERR "Authentication realm: $realm\n";
2967 STDERR->flush;
30d055aa
EW
2968 }
2969 $cred->username($default_username);
2970 } else {
d976acfd 2971 username($cred, $realm, $may_save, $pool);
30d055aa
EW
2972 }
2973 $cred->password(_read_password("Password for '" .
2974 $cred->username . "': ", $realm));
2975 $cred->may_save($may_save);
2976 $SVN::_Core::SVN_NO_ERROR;
2977}
2978
d976acfd 2979sub ssl_server_trust {
30d055aa
EW
2980 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2981 $may_save = undef if $_no_auth_cache;
6f729591 2982 print STDERR "Error validating server certificate for '$realm':\n";
fd499bcc
ER
2983 {
2984 no warnings 'once';
2985 # All variables SVN::Auth::SSL::* are used only once,
2986 # so we're shutting up Perl warnings about this.
2987 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2988 print STDERR " - The certificate is not issued ",
2989 "by a trusted authority. Use the\n",
2990 " fingerprint to validate ",
2991 "the certificate manually!\n";
2992 }
2993 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2994 print STDERR " - The certificate hostname ",
2995 "does not match.\n";
2996 }
2997 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2998 print STDERR " - The certificate is not yet valid.\n";
2999 }
3000 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3001 print STDERR " - The certificate has expired.\n";
3002 }
3003 if ($failures & $SVN::Auth::SSL::OTHER) {
3004 print STDERR " - The certificate has ",
3005 "an unknown error.\n";
3006 }
3007 } # no warnings 'once'
6f729591
EW
3008 printf STDERR
3009 "Certificate information:\n".
30d055aa
EW
3010 " - Hostname: %s\n".
3011 " - Valid: from %s until %s\n".
3012 " - Issuer: %s\n".
3013 " - Fingerprint: %s\n",
3014 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 3015 issuer_dname fingerprint);
30d055aa
EW
3016 my $choice;
3017prompt:
6f729591 3018 print STDERR $may_save ?
30d055aa
EW
3019 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3020 "(R)eject or accept (t)emporarily? ";
6f729591 3021 STDERR->flush;
30d055aa
EW
3022 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3023 if ($choice =~ /^t$/i) {
3024 $cred->may_save(undef);
3025 } elsif ($choice =~ /^r$/i) {
3026 return -1;
3027 } elsif ($may_save && $choice =~ /^p$/i) {
3028 $cred->may_save($may_save);
3029 } else {
3030 goto prompt;
3031 }
3032 $cred->accepted_failures($failures);
3033 $SVN::_Core::SVN_NO_ERROR;
3034}
3035
d976acfd 3036sub ssl_client_cert {
30d055aa
EW
3037 my ($cred, $realm, $may_save, $pool) = @_;
3038 $may_save = undef if $_no_auth_cache;
6f729591
EW
3039 print STDERR "Client certificate filename: ";
3040 STDERR->flush;
30d055aa
EW
3041 chomp(my $filename = <STDIN>);
3042 $cred->cert_file($filename);
3043 $cred->may_save($may_save);
3044 $SVN::_Core::SVN_NO_ERROR;
3045}
3046
d976acfd 3047sub ssl_client_cert_pw {
30d055aa
EW
3048 my ($cred, $realm, $may_save, $pool) = @_;
3049 $may_save = undef if $_no_auth_cache;
3050 $cred->password(_read_password("Password: ", $realm));
3051 $cred->may_save($may_save);
3052 $SVN::_Core::SVN_NO_ERROR;
3053}
3054
d976acfd 3055sub username {
30d055aa
EW
3056 my ($cred, $realm, $may_save, $pool) = @_;
3057 $may_save = undef if $_no_auth_cache;
3058 if (defined $realm && length $realm) {
6f729591 3059 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
3060 }
3061 my $username;
3062 if (defined $_username) {
3063 $username = $_username;
3064 } else {
6f729591
EW
3065 print STDERR "Username: ";
3066 STDERR->flush;
30d055aa
EW
3067 chomp($username = <STDIN>);
3068 }
3069 $cred->username($username);
3070 $cred->may_save($may_save);
3071 $SVN::_Core::SVN_NO_ERROR;
3072}
3073
3074sub _read_password {
3075 my ($prompt, $realm) = @_;
6f729591
EW
3076 print STDERR $prompt;
3077 STDERR->flush;
30d055aa
EW
3078 require Term::ReadKey;
3079 Term::ReadKey::ReadMode('noecho');
3080 my $password = '';
3081 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3082 last if $key =~ /[\012\015]/; # \n\r
3083 $password .= $key;
3084 }
3085 Term::ReadKey::ReadMode('restore');
6f729591
EW
3086 print STDERR "\n";
3087 STDERR->flush;
30d055aa
EW
3088 $password;
3089}
3090
27a1a801
EW
3091package SVN::Git::Fetcher;
3092use vars qw/@ISA/;
3093use strict;
3094use warnings;
3095use Carp qw/croak/;
ffe256f9 3096use File::Temp qw/tempfile/;
27a1a801
EW
3097use IO::File qw//;
3098
3099# file baton members: path, mode_a, mode_b, pool, fh, blob, base
3100sub new {
3101 my ($class, $git_svn) = @_;
3102 my $self = SVN::Delta::Editor->new;
3103 bless $self, $class;
1c8443b0 3104 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
3105 $self->{empty} = {};
3106 $self->{dir_prop} = {};
3107 $self->{file_prop} = {};
3108 $self->{absent_dir} = {};
3109 $self->{absent_file} = {};
ef3cfaad 3110 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
3111 $self;
3112}
3113
8b8fc068
EW
3114sub set_path_strip {
3115 my ($self, $path) = @_;
4e9f6cc7 3116 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
3117}
3118
d2a9a87b
EW
3119sub open_root {
3120 { path => '' };
3121}
3122
3123sub open_directory {
3124 my ($self, $path, $pb, $rev) = @_;
3125 { path => $path };
3126}
3127
706587fc
EW
3128sub git_path {
3129 my ($self, $path) = @_;
2b27f6c8
EW
3130 if ($self->{path_strip}) {
3131 $path =~ s!$self->{path_strip}!! or
3132 die "Failed to strip path '$path' ($self->{path_strip})\n";
3133 }
706587fc
EW
3134 $path;
3135}
3136
27a1a801
EW
3137sub delete_entry {
3138 my ($self, $path, $rev, $pb) = @_;
4a87db0e 3139
706587fc 3140 my $gpath = $self->git_path($path);
8a603774
EW
3141 return undef if ($gpath eq '');
3142
4a87db0e 3143 # remove entire directories.
706587fc 3144 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
3145 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3146 -r --name-only -z/,
706587fc 3147 $self->{c}, '--', $gpath);
4a87db0e
EW
3148 local $/ = "\0";
3149 while (<$ls>) {
ef3cfaad
EW
3150 chomp;
3151 $self->{gii}->remove($_);
9e3cdbd4 3152 print "\tD\t$_\n" unless $::_q;
4a87db0e 3153 }
9e3cdbd4 3154 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
3155 command_close_pipe($ls, $ctx);
3156 $self->{empty}->{$path} = 0
3157 } else {
ef3cfaad 3158 $self->{gii}->remove($gpath);
9e3cdbd4 3159 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 3160 }
27a1a801
EW
3161 undef;
3162}
3163
3164sub open_file {
3165 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
3166 my $gpath = $self->git_path($path);
3167 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 3168 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
3169 unless (defined $mode && defined $blob) {
3170 die "$path was not found in commit $self->{c} (r$rev)\n";
3171 }
27a1a801 3172 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 3173 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
3174}
3175
3176sub add_file {
3177 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
3178 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3179 delete $self->{empty}->{$dir};
27a1a801 3180 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 3181 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
3182}
3183
d2a9a87b
EW
3184sub add_directory {
3185 my ($self, $path, $cp_path, $cp_rev) = @_;
12a6d752
EW
3186 my $gpath = $self->git_path($path);
3187 if ($gpath eq '') {
3188 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3189 -r --name-only -z/,
3190 $self->{c});
3191 local $/ = "\0";
3192 while (<$ls>) {
3193 chomp;
3194 $self->{gii}->remove($_);
3195 print "\tD\t$_\n" unless $::_q;
3196 }
3197 command_close_pipe($ls, $ctx);
3198 $self->{empty}->{$path} = 0;
3199 }
d2a9a87b
EW
3200 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3201 delete $self->{empty}->{$dir};
3202 $self->{empty}->{$path} = 1;
3203 { path => $path };
3204}
3205
3206sub change_dir_prop {
3207 my ($self, $db, $prop, $value) = @_;
3208 $self->{dir_prop}->{$db->{path}} ||= {};
3209 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3210 undef;
3211}
3212
3213sub absent_directory {
3214 my ($self, $path, $pb) = @_;
3215 $self->{absent_dir}->{$pb->{path}} ||= [];
3216 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3217 undef;
3218}
3219
3220sub absent_file {
3221 my ($self, $path, $pb) = @_;
3222 $self->{absent_file}->{$pb->{path}} ||= [];
3223 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3224 undef;
3225}
3226
27a1a801
EW
3227sub change_file_prop {
3228 my ($self, $fb, $prop, $value) = @_;
3229 if ($prop eq 'svn:executable') {
3230 if ($fb->{mode_b} != 120000) {
3231 $fb->{mode_b} = defined $value ? 100755 : 100644;
3232 }
3233 } elsif ($prop eq 'svn:special') {
3234 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
3235 } else {
3236 $self->{file_prop}->{$fb->{path}} ||= {};
3237 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
3238 }
3239 undef;
3240}
3241
3242sub apply_textdelta {
3243 my ($self, $fb, $exp) = @_;
0b19138b 3244 my $fh = Git::temp_acquire('svn_delta');
27a1a801
EW
3245 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3246 # (but $base does not,) so dup() it for reading in close_file
3247 open my $dup, '<&', $fh or croak $!;
0b19138b 3248 my $base = Git::temp_acquire('git_blob');
27a1a801 3249 if ($fb->{blob}) {
ffe256f9
AR
3250 print $base 'link ' if ($fb->{mode_a} == 120000);
3251 my $size = $::_repository->cat_blob($fb->{blob}, $base);
d683a0e0 3252 die "Failed to read object $fb->{blob}" if ($size < 0);
27a1a801
EW
3253
3254 if (defined $exp) {
3255 seek $base, 0, 0 or croak $!;
8d7c4fad 3256 my $got = ::md5sum($base);
27a1a801
EW
3257 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3258 "expected: $exp\n",
3259 " got: $got\n" if ($got ne $exp);
3260 }
3261 }
3262 seek $base, 0, 0 or croak $!;
0b19138b 3263 $fb->{fh} = $fh;
27a1a801 3264 $fb->{base} = $base;
0b19138b 3265 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
27a1a801
EW
3266}
3267
3268sub close_file {
3269 my ($self, $fb, $exp) = @_;
3270 my $hash;
706587fc 3271 my $path = $self->git_path($fb->{path});
27a1a801 3272 if (my $fh = $fb->{fh}) {
7faf0686
EW
3273 if (defined $exp) {
3274 seek($fh, 0, 0) or croak $!;
8d7c4fad 3275 my $got = ::md5sum($fh);
7faf0686
EW
3276 if ($got ne $exp) {
3277 die "Checksum mismatch: $path\n",
3278 "expected: $exp\n got: $got\n";
3279 }
3280 }
27a1a801 3281 if ($fb->{mode_b} == 120000) {
510b0945
MG
3282 sysseek($fh, 0, 0) or croak $!;
3283 sysread($fh, my $buf, 5) == 5 or croak $!;
ffe256f9 3284
510b0945
MG
3285 unless ($buf eq 'link ') {
3286 warn "$path has mode 120000",
3287 " but is not a link\n";
3288 } else {
3289 my $tmp_fh = Git::temp_acquire('svn_hash');
3290 my $res;
3291 while ($res = sysread($fh, my $str, 1024)) {
3292 my $out = syswrite($tmp_fh, $str, $res);
3293 defined($out) && $out == $res
3294 or croak("write ",
836ff95d 3295 Git::temp_path($tmp_fh),
510b0945
MG
3296 ": $!\n");
3297 }
3298 defined $res or croak $!;
ffe256f9 3299
510b0945
MG
3300 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3301 Git::temp_release($tmp_fh, 1);
3302 }
3303 }
0b19138b
MG
3304
3305 $hash = $::_repository->hash_and_insert_object(
836ff95d 3306 Git::temp_path($fh));
27a1a801 3307 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
0b19138b
MG
3308
3309 Git::temp_release($fb->{base}, 1);
510b0945 3310 Git::temp_release($fh, 1);
27a1a801
EW
3311 } else {
3312 $hash = $fb->{blob} or die "no blob information\n";
3313 }
3314 $fb->{pool}->clear;
ef3cfaad 3315 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 3316 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
3317 undef;
3318}
3319
3320sub abort_edit {
3321 my $self = shift;
ef3cfaad
EW
3322 $self->{nr} = $self->{gii}->{nr};
3323 delete $self->{gii};
27a1a801
EW
3324 $self->SUPER::abort_edit(@_);
3325}
3326
3327sub close_edit {
3328 my $self = shift;
dad73c0b 3329 $self->{git_commit_ok} = 1;
ef3cfaad
EW
3330 $self->{nr} = $self->{gii}->{nr};
3331 delete $self->{gii};
27a1a801
EW
3332 $self->SUPER::close_edit(@_);
3333}
1a82e793 3334
a5e0cedc 3335package SVN::Git::Editor;
24e22aa8 3336use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
3337use strict;
3338use warnings;
3339use Carp qw/croak/;
3340use IO::File;
3341
3342sub new {
61395354
EW
3343 my ($class, $opts) = @_;
3344 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3345 die "$_ required!\n" unless (defined $opts->{$_});
3346 }
3347
3348 my $pool = SVN::Pool->new;
3349 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3350 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3351 $opts->{r}, $mods);
3352
3353 # $opts->{ra} functions should not be used after this:
3354 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3355 $opts->{editor_cb}, $pool);
3356 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 3357 bless $self, $class;
61395354
EW
3358 foreach (qw/svn_path r tree_a tree_b/) {
3359 $self->{$_} = $opts->{$_};
a5e0cedc 3360 }
61395354
EW
3361 $self->{url} = $opts->{ra}->{url};
3362 $self->{mods} = $mods;
3363 $self->{types} = $types;
3364 $self->{pool} = $pool;
a5e0cedc
EW
3365 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3366 $self->{rm} = { };
d3a840dc
EW
3367 $self->{path_prefix} = length $self->{svn_path} ?
3368 "$self->{svn_path}/" : '';
128de657 3369 $self->{config} = $opts->{config};
a5e0cedc
EW
3370 return $self;
3371}
3372
61395354
EW
3373sub generate_diff {
3374 my ($tree_a, $tree_b) = @_;
3375 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
3376 if ($_cp_similarity) {
3377 push @diff_tree, "-C$_cp_similarity";
61395354
EW
3378 } else {
3379 push @diff_tree, '-C';
3380 }
24e22aa8
EW
3381 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3382 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
3383 push @diff_tree, $tree_a, $tree_b;
3384 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3385 local $/ = "\0";
3386 my $state = 'meta';
3387 my @mods;
3388 while (<$diff_fh>) {
3389 chomp $_; # this gets rid of the trailing "\0"
3390 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3391 $::sha1\s($::sha1)\s
3392 ([MTCRAD])\d*$/xo) {
3393 push @mods, { mode_a => $1, mode_b => $2,
3394 sha1_b => $3, chg => $4 };
3395 if ($4 =~ /^(?:C|R)$/) {
3396 $state = 'file_a';
3397 } else {
3398 $state = 'file_b';
3399 }
3400 } elsif ($state eq 'file_a') {
3401 my $x = $mods[$#mods] or croak "Empty array\n";
3402 if ($x->{chg} !~ /^(?:C|R)$/) {
3403 croak "Error parsing $_, $x->{chg}\n";
3404 }
3405 $x->{file_a} = $_;
3406 $state = 'file_b';
3407 } elsif ($state eq 'file_b') {
3408 my $x = $mods[$#mods] or croak "Empty array\n";
3409 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3410 croak "Error parsing $_, $x->{chg}\n";
3411 }
3412 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3413 croak "Error parsing $_, $x->{chg}\n";
3414 }
3415 $x->{file_b} = $_;
3416 $state = 'meta';
3417 } else {
3418 croak "Error parsing $_\n";
3419 }
3420 }
3421 command_close_pipe($diff_fh, $ctx);
3422 \@mods;
3423}
3424
3425sub check_diff_paths {
3426 my ($ra, $pfx, $rev, $mods) = @_;
3427 my %types;
3428 $pfx .= '/' if length $pfx;
3429
3430 sub type_diff_paths {
3431 my ($ra, $types, $path, $rev) = @_;
3432 my @p = split m#/+#, $path;
3433 my $c = shift @p;
3434 unless (defined $types->{$c}) {
3435 $types->{$c} = $ra->check_path($c, $rev);
3436 }
3437 while (@p) {
3438 $c .= '/' . shift @p;
3439 next if defined $types->{$c};
3440 $types->{$c} = $ra->check_path($c, $rev);
3441 }
3442 }
3443
3444 foreach my $m (@$mods) {
3445 foreach my $f (qw/file_a file_b/) {
3446 next unless defined $m->{$f};
3447 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3448 if (length $pfx.$dir && ! defined $types{$dir}) {
3449 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3450 }
3451 }
3452 }
3453 \%types;
3454}
3455
a5e0cedc
EW
3456sub split_path {
3457 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3458}
3459
3460sub repo_path {
d3a840dc
EW
3461 my ($self, $path) = @_;
3462 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
3463}
3464
3465sub url_path {
3466 my ($self, $path) = @_;
29633bb9
EW
3467 if ($self->{url} =~ m#^https?://#) {
3468 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3469 }
6e8548cc 3470 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
3471}
3472
3473sub rmdirs {
61395354 3474 my ($self) = @_;
a5e0cedc
EW
3475 my $rm = $self->{rm};
3476 delete $rm->{''}; # we never delete the url we're tracking
3477 return unless %$rm;
3478
3479 foreach (keys %$rm) {
3480 my @d = split m#/#, $_;
3481 my $c = shift @d;
3482 $rm->{$c} = 1;
3483 while (@d) {
3484 $c .= '/' . shift @d;
3485 $rm->{$c} = 1;
3486 }
3487 }
3488 delete $rm->{$self->{svn_path}};
3489 delete $rm->{''}; # we never delete the url we're tracking
3490 return unless %$rm;
3491
61395354
EW
3492 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3493 $self->{tree_b});
a5e0cedc
EW
3494 local $/ = "\0";
3495 while (<$fh>) {
3496 chomp;
747fa12c 3497 my @dn = split m#/#, $_;
c07eee1f
EW
3498 while (pop @dn) {
3499 delete $rm->{join '/', @dn};
3500 }
3501 unless (%$rm) {
22600a25 3502 close $fh;
c07eee1f
EW
3503 return;
3504 }
a5e0cedc 3505 }
aef4e921 3506 command_close_pipe($fh, $ctx);
c07eee1f 3507
a5e0cedc
EW
3508 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3509 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3510 $self->close_directory($bat->{$d}, $p);
3511 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 3512 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
3513 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3514 delete $bat->{$d};
3515 }
3516}
3517
3518sub open_or_add_dir {
3519 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
3520 my $t = $self->{types}->{$full_path};
3521 if (!defined $t) {
3522 die "$full_path not known in r$self->{r} or we have a bug!\n";
3523 }
fd499bcc
ER
3524 {
3525 no warnings 'once';
3526 # SVN::Node::none and SVN::Node::file are used only once,
3527 # so we're shutting up Perl's warnings about them.
3528 if ($t == $SVN::Node::none) {
3529 return $self->add_directory($full_path, $baton,
3530 undef, -1, $self->{pool});
3531 } elsif ($t == $SVN::Node::dir) {
3532 return $self->open_directory($full_path, $baton,
3533 $self->{r}, $self->{pool});
3534 } # no warnings 'once'
3535 print STDERR "$full_path already exists in repository at ",
3536 "r$self->{r} and it is not a directory (",
3537 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3538 } # no warnings 'once'
a5e0cedc
EW
3539 exit 1;
3540}
3541
3542sub ensure_path {
3543 my ($self, $path) = @_;
3544 my $bat = $self->{bat};
6e8548cc
EW
3545 my $repo_path = $self->repo_path($path);
3546 return $bat->{''} unless (length $repo_path);
3547 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
3548 my $c = shift @p;
3549 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3550 while (@p) {
3551 my $c0 = $c;
3552 $c .= '/' . shift @p;
3553 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3554 }
3555 return $bat->{$c};
3556}
3557
128de657
BK
3558# Subroutine to convert a globbing pattern to a regular expression.
3559# From perl cookbook.
3560sub glob2pat {
3561 my $globstr = shift;
3562 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3563 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3564 return '^' . $globstr . '$';
3565}
3566
3567sub check_autoprop {
3568 my ($self, $pattern, $properties, $file, $fbat) = @_;
3569 # Convert the globbing pattern to a regular expression.
3570 my $regex = glob2pat($pattern);
3571 # Check if the pattern matches the file name.
3572 if($file =~ m/($regex)/) {
3573 # Parse the list of properties to set.
3574 my @props = split(/;/, $properties);
3575 foreach my $prop (@props) {
3576 # Parse 'name=value' syntax and set the property.
3577 if ($prop =~ /([^=]+)=(.*)/) {
3578 my ($n,$v) = ($1,$2);
3579 for ($n, $v) {
3580 s/^\s+//; s/\s+$//;
3581 }
3582 $self->change_file_prop($fbat, $n, $v);
3583 }
3584 }
3585 }
3586}
3587
3588sub apply_autoprops {
3589 my ($self, $file, $fbat) = @_;
3590 my $conf_t = ${$self->{config}}{'config'};
3591 no warnings 'once';
3592 # Check [miscellany]/enable-auto-props in svn configuration.
3593 if (SVN::_Core::svn_config_get_bool(
3594 $conf_t,
3595 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3596 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3597 0)) {
3598 # Auto-props are enabled. Enumerate them to look for matches.
3599 my $callback = sub {
3600 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3601 };
3602 SVN::_Core::svn_config_enumerate(
3603 $conf_t,
3604 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3605 $callback);
3606 }
3607}
3608
a5e0cedc 3609sub A {
44320b9e 3610 my ($self, $m) = @_;
a5e0cedc
EW
3611 my ($dir, $file) = split_path($m->{file_b});
3612 my $pbat = $self->ensure_path($dir);
3613 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3614 undef, -1);
44320b9e 3615 print "\tA\t$m->{file_b}\n" unless $::_q;
128de657 3616 $self->apply_autoprops($file, $fbat);
a5e0cedc
EW
3617 $self->chg_file($fbat, $m);
3618 $self->close_file($fbat,undef,$self->{pool});
3619}
3620
3621sub C {
44320b9e 3622 my ($self, $m) = @_;
a5e0cedc
EW
3623 my ($dir, $file) = split_path($m->{file_b});
3624 my $pbat = $self->ensure_path($dir);
3625 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3626 $self->url_path($m->{file_a}), $self->{r});
44320b9e 3627 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3628 $self->chg_file($fbat, $m);
3629 $self->close_file($fbat,undef,$self->{pool});
3630}
3631
3632sub delete_entry {
3633 my ($self, $path, $pbat) = @_;
3634 my $rpath = $self->repo_path($path);
3635 my ($dir, $file) = split_path($rpath);
3636 $self->{rm}->{$dir} = 1;
3637 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3638}
3639
3640sub R {
44320b9e 3641 my ($self, $m) = @_;
a5e0cedc
EW
3642 my ($dir, $file) = split_path($m->{file_b});
3643 my $pbat = $self->ensure_path($dir);
3644 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3645 $self->url_path($m->{file_a}), $self->{r});
44320b9e 3646 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3647 $self->chg_file($fbat, $m);
3648 $self->close_file($fbat,undef,$self->{pool});
3649
3650 ($dir, $file) = split_path($m->{file_a});
3651 $pbat = $self->ensure_path($dir);
3652 $self->delete_entry($m->{file_a}, $pbat);
3653}
3654
3655sub M {
44320b9e 3656 my ($self, $m) = @_;
a5e0cedc
EW
3657 my ($dir, $file) = split_path($m->{file_b});
3658 my $pbat = $self->ensure_path($dir);
3659 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3660 $pbat,$self->{r},$self->{pool});
44320b9e 3661 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3662 $self->chg_file($fbat, $m);
3663 $self->close_file($fbat,undef,$self->{pool});
3664}
3665
3666sub T { shift->M(@_) }
3667
3668sub change_file_prop {
3669 my ($self, $fbat, $pname, $pval) = @_;
3670 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3671}
3672
3673sub chg_file {
3674 my ($self, $fbat, $m) = @_;
3675 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3676 $self->change_file_prop($fbat,'svn:executable','*');
3677 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3678 $self->change_file_prop($fbat,'svn:executable',undef);
3679 }
0b19138b 3680 my $fh = Git::temp_acquire('git_blob');
a5e0cedc
EW
3681 if ($m->{mode_b} =~ /^120/) {
3682 print $fh 'link ' or croak $!;
3683 $self->change_file_prop($fbat,'svn:special','*');
3684 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3685 $self->change_file_prop($fbat,'svn:special',undef);
3686 }
ffe256f9 3687 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
d683a0e0 3688 croak "Failed to read object $m->{sha1_b}" if ($size < 0);
a5e0cedc
EW
3689 $fh->flush == 0 or croak $!;
3690 seek $fh, 0, 0 or croak $!;
3691
8d7c4fad 3692 my $exp = ::md5sum($fh);
a5e0cedc
EW
3693 seek $fh, 0, 0 or croak $!;
3694
f7197dff
EW
3695 my $pool = SVN::Pool->new;
3696 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3697 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 3698 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
0b19138b 3699 Git::temp_release($fh, 1);
f7197dff 3700 $pool->clear;
a5e0cedc
EW
3701}
3702
3703sub D {
44320b9e 3704 my ($self, $m) = @_;
a5e0cedc
EW
3705 my ($dir, $file) = split_path($m->{file_b});
3706 my $pbat = $self->ensure_path($dir);
44320b9e 3707 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3708 $self->delete_entry($m->{file_b}, $pbat);
3709}
3710
3711sub close_edit {
3712 my ($self) = @_;
3713 my ($p,$bat) = ($self->{pool}, $self->{bat});
3714 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
6442754d 3715 next if $_ eq '';
a5e0cedc
EW
3716 $self->close_directory($bat->{$_}, $p);
3717 }
6442754d 3718 $self->close_directory($bat->{''}, $p);
a5e0cedc
EW
3719 $self->SUPER::close_edit($p);
3720 $p->clear;
3721}
3722
3723sub abort_edit {
3724 my ($self) = @_;
3725 $self->SUPER::abort_edit($self->{pool});
61395354
EW
3726}
3727
3728sub DESTROY {
3729 my $self = shift;
3730 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
3731 $self->{pool}->clear;
3732}
3733
44320b9e
EW
3734# this drives the editor
3735sub apply_diff {
61395354
EW
3736 my ($self) = @_;
3737 my $mods = $self->{mods};
44320b9e 3738 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 3739 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
3740 my $f = $m->{chg};
3741 if (defined $o{$f}) {
3742 $self->$f($m);
3743 } else {
207f1a75 3744 fatal("Invalid change type: $f");
44320b9e
EW
3745 }
3746 }
24e22aa8 3747 $self->rmdirs if $_rmdir;
6e8548cc 3748 if (@$mods == 0) {
44320b9e
EW
3749 $self->abort_edit;
3750 } else {
3751 $self->close_edit;
3752 }
6e8548cc 3753 return scalar @$mods;
44320b9e
EW
3754}
3755
d81bf827 3756package Git::SVN::Ra;
6af1db44 3757use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
3758use strict;
3759use warnings;
a51cdb0c 3760my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
d81bf827
EW
3761
3762BEGIN {
3763 # enforce temporary pool usage for some simple functions
c5f71ad0
SV
3764 no strict 'refs';
3765 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3766 my $SUPER = "SUPER::$f";
3767 *$f = sub {
3768 my $self = shift;
3769 my $pool = SVN::Pool->new;
3770 my @ret = $self->$SUPER(@_,$pool);
3771 $pool->clear;
3772 wantarray ? @ret : $ret[0];
3773 };
d81bf827 3774 }
d81bf827
EW
3775}
3776
9ff74e95
SW
3777sub _auth_providers () {
3778 [
3779 SVN::Client::get_simple_provider(),
3780 SVN::Client::get_ssl_server_trust_file_provider(),
3781 SVN::Client::get_simple_prompt_provider(
3782 \&Git::SVN::Prompt::simple, 2),
3783 SVN::Client::get_ssl_client_cert_file_provider(),
3784 SVN::Client::get_ssl_client_cert_prompt_provider(
3785 \&Git::SVN::Prompt::ssl_client_cert, 2),
77266e96 3786 SVN::Client::get_ssl_client_cert_pw_file_provider(),
9ff74e95
SW
3787 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3788 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3789 SVN::Client::get_username_provider(),
3790 SVN::Client::get_ssl_server_trust_prompt_provider(
3791 \&Git::SVN::Prompt::ssl_server_trust),
3792 SVN::Client::get_username_prompt_provider(
3793 \&Git::SVN::Prompt::username, 2)
3794 ]
3795}
3796
cfbe7ab3
EW
3797sub escape_uri_only {
3798 my ($uri) = @_;
3799 my @tmp;
3800 foreach (split m{/}, $uri) {
d1a8d0ea 3801 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
cfbe7ab3
EW
3802 push @tmp, $_;
3803 }
3804 join('/', @tmp);
3805}
3806
3807sub escape_url {
3808 my ($url) = @_;
3809 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3810 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3811 $url = "$scheme://$domain$uri";
3812 }
3813 $url;
3814}
3815
d81bf827
EW
3816sub new {
3817 my ($class, $url) = @_;
f6f09876 3818 $url =~ s!/+$!!;
5d3b7cd5 3819 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 3820
d81bf827 3821 SVN::_Core::svn_config_ensure($config_dir, undef);
9ff74e95 3822 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
d81bf827 3823 my $config = SVN::Core::config_get_config($config_dir);
7730fbe6 3824 $RA = undef;
602015e0
ER
3825 my $dont_store_passwords = 1;
3826 my $conf_t = ${$config}{'config'};
3827 {
fd499bcc 3828 no warnings 'once';
602015e0
ER
3829 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3830 # produces warnings that variables are used only once.
3831 # I had not found the better way to shut them up, so
fd499bcc 3832 # the warnings of type 'once' are disabled in this block.
602015e0
ER
3833 if (SVN::_Core::svn_config_get_bool($conf_t,
3834 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3835 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3836 1) == 0) {
3837 SVN::_Core::svn_auth_set_parameter($baton,
3838 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3839 bless (\$dont_store_passwords, "_p_void"));
3840 }
3841 if (SVN::_Core::svn_config_get_bool($conf_t,
3842 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3843 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3844 1) == 0) {
3845 $Git::SVN::Prompt::_no_auth_cache = 1;
3846 }
fd499bcc 3847 } # no warnings 'once'
cfbe7ab3 3848 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
d81bf827
EW
3849 config => $config,
3850 pool => SVN::Pool->new,
3851 auth_provider_callbacks => $callbacks);
cfbe7ab3 3852 $self->{url} = $url;
d81bf827
EW
3853 $self->{svn_path} = $url;
3854 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 3855 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
0dc03d6a
EW
3856 $self->{cache} = { check_path => { r => 0, data => {} },
3857 get_dir => { r => 0, data => {} } };
5d3b7cd5 3858 $RA = bless $self, $class;
d81bf827
EW
3859}
3860
0dc03d6a
EW
3861sub check_path {
3862 my ($self, $path, $r) = @_;
3863 my $cache = $self->{cache}->{check_path};
3864 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3865 return $cache->{data}->{$path};
3866 }
3867 my $pool = SVN::Pool->new;
3868 my $t = $self->SUPER::check_path($path, $r, $pool);
3869 $pool->clear;
3870 if ($r != $cache->{r}) {
3871 %{$cache->{data}} = ();
3872 $cache->{r} = $r;
3873 }
3874 $cache->{data}->{$path} = $t;
3875}
3876
3877sub get_dir {
3878 my ($self, $dir, $r) = @_;
3879 my $cache = $self->{cache}->{get_dir};
3880 if ($r == $cache->{r}) {
3881 if (my $x = $cache->{data}->{$dir}) {
3882 return wantarray ? @$x : $x->[0];
3883 }
3884 }
3885 my $pool = SVN::Pool->new;
3886 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3887 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3888 $pool->clear;
3889 if ($r != $cache->{r}) {
3890 %{$cache->{data}} = ();
3891 $cache->{r} = $r;
3892 }
3893 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3894 wantarray ? (\%dirents, $r, $props) : \%dirents;
3895}
3896
d81bf827 3897sub DESTROY {
5d3b7cd5 3898 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
3899}
3900
d81bf827
EW
3901sub get_log {
3902 my ($self, @args) = @_;
3903 my $pool = SVN::Pool->new;
d81bf827
EW
3904 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3905 my $ret = $self->SUPER::get_log(@args, $pool);
3906 $pool->clear;
3907 $ret;
3908}
3909
9ff74e95
SW
3910sub trees_match {
3911 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3912 my $ctx = SVN::Client->new(auth => _auth_providers);
3913 my $out = IO::File->new_tmpfile;
3914
3915 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3916 # $ctx->diff(), so we'll create a default one
3917 my $pool = SVN::Pool->new_default_sub;
3918
3919 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3920 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3921 $out->flush;
3922 my $ret = (($out->stat)[7] == 0);
3923 close $out or croak $!;
3924
3925 $ret;
3926}
3927
d81bf827 3928sub get_commit_editor {
44320b9e 3929 my ($self, $log, $cb, $pool) = @_;
d81bf827 3930 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 3931 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
3932}
3933
d81bf827 3934sub gs_do_update {
8a603774
EW
3935 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3936 my $new = ($rev_a == $rev_b);
3937 my $path = $gs->{path};
3938
2e5e2480
EW
3939 if ($new && -e $gs->{index}) {
3940 unlink $gs->{index} or die
3941 "Couldn't unlink index: $gs->{index}: $!\n";
3942 }
d81bf827 3943 my $pool = SVN::Pool->new;
8b8fc068 3944 $editor->set_path_strip($path);
2b27f6c8
EW
3945 my (@pc) = split m#/#, $path;
3946 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 3947 1, $editor, $pool);
d81bf827 3948 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
3949
3950 # Since we can't rely on svn_ra_reparent being available, we'll
3951 # just have to do some magic with set_path to make it so
3952 # we only want a partial path.
3953 my $sp = '';
3954 my $final = join('/', @pc);
3955 while (@pc) {
3956 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3957 $sp .= '/' if length $sp;
3958 $sp .= shift @pc;
3959 }
3960 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3961
2b27f6c8
EW
3962 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3963
d81bf827
EW
3964 $reporter->finish_report($pool);
3965 $pool->clear;
3966 $editor->{git_commit_ok};
3967}
3968
2b27f6c8
EW
3969# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3970# svn_ra_reparent didn't work before 1.4)
d81bf827 3971sub gs_do_switch {
8a603774
EW
3972 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3973 my $path = $gs->{path};
d81bf827 3974 my $pool = SVN::Pool->new;
2b27f6c8
EW
3975
3976 my $full_url = $self->{url};
3977 my $old_url = $full_url;
cfbe7ab3 3978 $full_url .= '/' . escape_uri_only($path) if length $path;
5d3b7cd5 3979 my ($ra, $reparented);
ad0a82ba
AB
3980
3981 if ($old_url =~ m#^svn(\+ssh)?://#) {
3982 $_[0] = undef;
3983 $self = undef;
3984 $RA = undef;
3985 $ra = Git::SVN::Ra->new($full_url);
3986 $ra_invalid = 1;
3987 } elsif ($old_url ne $full_url) {
3988 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
3989 $self->{url} = $full_url;
3990 $reparented = 1;
5d3b7cd5 3991 }
ad0a82ba 3992
5d3b7cd5 3993 $ra ||= $self;
61aeeefd 3994 $url_b = escape_url($url_b);
8a603774 3995 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 3996 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 3997 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 3998 $reporter->finish_report($pool);
2b27f6c8 3999
5d3b7cd5
EW
4000 if ($reparented) {
4001 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4002 $self->{url} = $old_url;
4003 }
2b27f6c8 4004
d81bf827
EW
4005 $pool->clear;
4006 $editor->{git_commit_ok};
4007}
4008
b54a901e
EW
4009sub longest_common_path {
4010 my ($gsv, $globs) = @_;
d2ae1434 4011 my %common;
e518192f
EW
4012 my $common_max = scalar @$gsv;
4013
4014 foreach my $gs (@$gsv) {
d2ae1434
EW
4015 my @tmp = split m#/#, $gs->{path};
4016 my $p = '';
4017 foreach (@tmp) {
4018 $p .= length($p) ? "/$_" : $_;
4019 $common{$p} ||= 0;
4020 $common{$p}++;
4021 }
4022 }
e518192f
EW
4023 $globs ||= [];
4024 $common_max += scalar @$globs;
4025 foreach my $glob (@$globs) {
4026 my @tmp = split m#/#, $glob->{path}->{left};
4027 my $p = '';
4028 foreach (@tmp) {
4029 $p .= length($p) ? "/$_" : $_;
4030 $common{$p} ||= 0;
4031 $common{$p}++;
4032 }
4033 }
4034
d2ae1434
EW
4035 my $longest_path = '';
4036 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 4037 if ($common{$_} == $common_max) {
d2ae1434
EW
4038 $longest_path = $_;
4039 last;
4040 }
0af9c9f9 4041 }
b54a901e
EW
4042 $longest_path;
4043}
4044
4045sub gs_fetch_loop_common {
4046 my ($self, $base, $head, $gsv, $globs) = @_;
4047 return if ($base > $head);
4048 my $inc = $_log_window_size;
4049 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4050 my $longest_path = longest_common_path($gsv, $globs);
a51cdb0c 4051 my $ra_url = $self->{url};
0af9c9f9 4052 while (1) {
d4eff2bd 4053 my %revs;
d2ae1434 4054 my $err;
f7c3fc4a 4055 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
4056 $SVN::Error::handler = sub {
4057 ($err) = @_;
4058 skip_unknown_revs($err);
4059 };
4060 sub _cb {
4061 my ($paths, $r, $author, $date, $log) = @_;
4062 [ dup_changed_paths($paths),
4063 { author => $author, date => $date, log => $log } ];
4064 }
4065 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4066 sub { $revs{$_[1]} = _cb(@_) });
4067 if ($err && $max >= $head) {
4068 print STDERR "Path '$longest_path' ",
4069 "was probably deleted:\n",
4070 $err->expanded_message,
4071 "\nWill attempt to follow ",
4072 "revisions r$min .. r$max ",
4073 "committed before the deletion\n";
4074 my $hi = $max;
4075 while (--$hi >= $min) {
4076 my $ok;
4077 $self->get_log([$longest_path], $min, $hi,
4078 0, 1, 1, sub {
4079 $ok ||= $_[1];
4080 $revs{$_[1]} = _cb(@_) });
4081 if ($ok) {
4082 print STDERR "r$min .. r$ok OK\n";
4083 last;
4084 }
4085 }
4086 }
d4eff2bd 4087 $SVN::Error::handler = $err_handler;
fbcc1737 4088
e518192f 4089 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 4090 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 4091 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
4092
4093 foreach my $gs ($self->match_globs(\%exists, $paths,
4094 $globs, $r)) {
060610c5 4095 if ($gs->rev_map_max >= $r) {
fbcc1737
EW
4096 next;
4097 }
4098 next unless $gs->match_paths($paths, $r);
4099 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
4100 if (my $last_commit = $gs->last_commit) {
4101 $gs->assert_index_clean($last_commit);
4102 }
fbcc1737
EW
4103 my $log_entry = $gs->do_fetch($paths, $r);
4104 if ($log_entry) {
0af9c9f9
EW
4105 $gs->do_git_commit($log_entry);
4106 }
321b1842 4107 $INDEX_FILES{$gs->{index}} = 1;
0af9c9f9 4108 }
e518192f 4109 foreach my $g (@$globs) {
93f2689c
EW
4110 my $k = "svn-remote.$g->{remote}." .
4111 "$g->{t}-maxRev";
4112 Git::SVN::tmp_config($k, $r);
e518192f 4113 }
a51cdb0c
EW
4114 if ($ra_invalid) {
4115 $_[0] = undef;
4116 $self = undef;
4117 $RA = undef;
4118 $self = Git::SVN::Ra->new($ra_url);
4119 $ra_invalid = undef;
4120 }
0af9c9f9 4121 }
9c93fee5
EW
4122 # pre-fill the .rev_db since it'll eventually get filled in
4123 # with '0' x40 if something new gets committed
e518192f 4124 foreach my $gs (@$gsv) {
66ab84b9
EW
4125 next if $gs->rev_map_max >= $max;
4126 next if defined $gs->rev_map_get($max);
4127 $gs->rev_map_set($max, 0 x40);
9c93fee5 4128 }
c3560e53
EW
4129 foreach my $g (@$globs) {
4130 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4131 Git::SVN::tmp_config($k, $max);
4132 }
0af9c9f9
EW
4133 last if $max >= $head;
4134 $min = $max + 1;
4135 $max += $inc;
4136 $max = $head if ($max > $head);
4137 }
94bc914c 4138 Git::SVN::gc();
0af9c9f9
EW
4139}
4140
570d35c2
MG
4141sub get_dir_globbed {
4142 my ($self, $left, $depth, $r) = @_;
4143
4144 my @x = eval { $self->get_dir($left, $r) };
4145 return unless scalar @x == 3;
4146 my $dirents = $x[0];
4147 my @finalents;
4148 foreach my $de (keys %$dirents) {
4149 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4150 if ($depth > 1) {
4151 my @args = ("$left/$de", $depth - 1, $r);
4152 foreach my $dir ($self->get_dir_globbed(@args)) {
4153 push @finalents, "$de/$dir";
4154 }
4155 } else {
4156 push @finalents, $de;
4157 }
4158 }
4159 @finalents;
4160}
4161
e518192f
EW
4162sub match_globs {
4163 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
4164
4165 sub get_dir_check {
4166 my ($self, $exists, $g, $r) = @_;
570d35c2
MG
4167
4168 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4169 $g->{path}->{depth},
4170 $r);
4171
4172 foreach my $de (@dirs) {
74a81227
EW
4173 my $p = $g->{path}->full_path($de);
4174 next if $exists->{$p};
4175 next if (length $g->{path}->{right} &&
4176 ($self->check_path($p, $r) !=
4177 $SVN::Node::dir));
4178 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4179 $g->{ref}->full_path($de), 1);
4180 }
4181 }
e518192f 4182 foreach my $g (@$globs) {
74a81227
EW
4183 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4184 if ($path->{action} =~ /^[AR]$/) {
4185 get_dir_check($self, $exists, $g, $r);
4186 }
4187 }
e518192f 4188 foreach (keys %$paths) {
28710f74
EW
4189 if (/$g->{path}->{left_regex}/ &&
4190 !/$g->{path}->{regex}/) {
74a81227
EW
4191 next if $paths->{$_}->{action} !~ /^[AR]$/;
4192 get_dir_check($self, $exists, $g, $r);
4193 }
e518192f
EW
4194 next unless /$g->{path}->{regex}/;
4195 my $p = $1;
4196 my $pathname = $g->{path}->full_path($p);
4197 next if $exists->{$pathname};
0c1ec5a1
EW
4198 next if ($self->check_path($pathname, $r) !=
4199 $SVN::Node::dir);
e518192f
EW
4200 $exists->{$pathname} = Git::SVN->init(
4201 $self->{url}, $pathname, undef,
4202 $g->{ref}->full_path($p), 1);
4203 }
4204 my $c = '';
4205 foreach (split m#/#, $g->{path}->{left}) {
4206 $c .= "/$_";
4207 next unless ($paths->{$c} &&
74a81227
EW
4208 ($paths->{$c}->{action} =~ /^[AR]$/));
4209 get_dir_check($self, $exists, $g, $r);
e518192f
EW
4210 }
4211 }
4212 values %$exists;
4213}
4214
e6434f87
EW
4215sub minimize_url {
4216 my ($self) = @_;
4217 return $self->{url} if ($self->{url} eq $self->{repos_root});
4218 my $url = $self->{repos_root};
4219 my @components = split(m!/!, $self->{svn_path});
4220 my $c = '';
4221 do {
4222 $url .= "/$c" if length $c;
4223 eval { (ref $self)->new($url)->get_latest_revnum };
4224 } while ($@ && ($c = shift @components));
4225 $url;
4226}
4227
d81bf827
EW
4228sub can_do_switch {
4229 my $self = shift;
4230 unless (defined $can_do_switch) {
4231 my $pool = SVN::Pool->new;
4232 my $rep = eval {
4233 $self->do_switch(1, '', 0, $self->{url},
4234 SVN::Delta::Editor->new, $pool);
4235 };
4236 if ($@) {
4237 $can_do_switch = 0;
4238 } else {
4239 $rep->abort_report($pool);
4240 $can_do_switch = 1;
4241 }
4242 $pool->clear;
4243 }
4244 $can_do_switch;
4245}
4246
0af9c9f9
EW
4247sub skip_unknown_revs {
4248 my ($err) = @_;
4249 my $errno = $err->apr_err();
4250 # Maybe the branch we're tracking didn't
4251 # exist when the repo started, so it's
4252 # not an error if it doesn't, just continue
4253 #
4254 # Wonderfully consistent library, eh?
4255 # 160013 - svn:// and file://
4256 # 175002 - http(s)://
4257 # 175007 - http(s):// (this repo required authorization, too...)
4258 # More codes may be discovered later...
4259 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
4260 my $err_key = $err->expanded_message;
4261 # revision numbers change every time, filter them out
4262 $err_key =~ s/\d+/\0/g;
4263 $err_key = "$errno\0$err_key";
4264 unless ($ignored_err{$err_key}) {
4265 warn "W: Ignoring error from SVN, path probably ",
4266 "does not exist: ($errno): ",
4267 $err->expanded_message,"\n";
eee8a174
EW
4268 warn "W: Do not be alarmed at the above message ",
4269 "git-svn is just searching aggressively for ",
4270 "old history.\n",
4271 "This may take a while on large repositories\n";
a6a15a99
EW
4272 $ignored_err{$err_key} = 1;
4273 }
0af9c9f9
EW
4274 return;
4275 }
4276 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4277}
4278
4279# svn_log_changed_path_t objects passed to get_log are likely to be
4280# overwritten even if only the refs are copied to an external variable,
4281# so we should dup the structures in their entirety. Using an externally
4282# passed pool (instead of our temporary and quickly cleared pool in
4283# Git::SVN::Ra) does not help matters at all...
4284sub dup_changed_paths {
4285 my ($paths) = @_;
4286 return undef unless $paths;
4287 my %ret;
4288 foreach my $p (keys %$paths) {
4289 my $i = $paths->{$p};
4290 my %s = map { $_ => $i->$_ }
4291 qw/copyfrom_path copyfrom_rev action/;
4292 $ret{$p} = \%s;
4293 }
4294 \%ret;
4295}
4296
f8c9d1d2
EW
4297package Git::SVN::Log;
4298use strict;
4299use warnings;
4300use POSIX qw/strftime/;
111947ef 4301use constant commit_log_separator => ('-' x 72) . "\n";
f8c9d1d2
EW
4302use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4303 %rusers $show_commit $incremental/;
4304my $l_fmt;
4305
4306sub cmt_showable {
4307 my ($c) = @_;
4308 return 1 if defined $c->{r};
c16d0871
EW
4309
4310 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
4311 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4312 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 4313 @{$c->{l}} = ();
44320b9e 4314 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
4315
4316 # shift off the headers
4317 shift @log while ($log[0] ne '');
44320b9e 4318 shift @log;
c16d0871
EW
4319
4320 # TODO: make $c->{l} not have a trailing newline in the future
4321 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
4322
4323 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 4324 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
4325 }
4326 return defined $c->{r};
4327}
4328
4329sub log_use_color {
cd459e3f 4330 return $color || Git->repository->get_colorbool('color.diff');
f8c9d1d2
EW
4331}
4332
4333sub git_svn_log_cmd {
3bc718ba
EW
4334 my ($r_min, $r_max, @args) = @_;
4335 my $head = 'HEAD';
6ed77266 4336 my (@files, @log_opts);
3bc718ba 4337 foreach my $x (@args) {
6ed77266
EW
4338 if ($x eq '--' || @files) {
4339 push @files, $x;
4340 } else {
4341 if (::verify_ref("$x^0")) {
4342 $head = $x;
4343 } else {
4344 push @log_opts, $x;
4345 }
4346 }
3bc718ba
EW
4347 }
4348
13c823fb
EW
4349 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4350 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
4351 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4352 $gs->refname);
4353 push @cmd, '-r' unless $non_recursive;
4354 push @cmd, qw/--raw --name-status/ if $verbose;
4355 push @cmd, '--color' if log_use_color();
6ed77266
EW
4356 push @cmd, @log_opts;
4357 if (defined $r_max && $r_max == $r_min) {
f8c9d1d2 4358 push @cmd, '--max-count=1';
060610c5 4359 if (my $c = $gs->rev_map_get($r_max)) {
f8c9d1d2
EW
4360 push @cmd, $c;
4361 }
6ed77266 4362 } elsif (defined $r_max) {
111947ef
DK
4363 if ($r_max < $r_min) {
4364 ($r_min, $r_max) = ($r_max, $r_min);
4365 }
4366 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4367 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4368 # If there are no commits in the range, both $c_max and $c_min
4369 # will be undefined. If there is at least 1 commit in the
4370 # range, both will be defined.
4371 return () if !defined $c_min || !defined $c_max;
4372 if ($c_min eq $c_max) {
4373 push @cmd, '--max-count=1', $c_min;
f8c9d1d2 4374 } else {
111947ef 4375 push @cmd, '--boundary', "$c_min..$c_max";
f8c9d1d2
EW
4376 }
4377 }
6ed77266 4378 return (@cmd, @files);
f8c9d1d2
EW
4379}
4380
4381# adapted from pager.c
4382sub config_pager {
4383 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4384 if (!defined $pager) {
4385 $pager = 'less';
4386 } elsif (length $pager == 0 || $pager eq 'cat') {
4387 $pager = undef;
4388 }
cd459e3f 4389 $ENV{GIT_PAGER_IN_USE} = defined($pager);
f8c9d1d2
EW
4390}
4391
4392sub run_pager {
b0193048 4393 return unless -t *STDOUT && defined $pager;
971e6283 4394 pipe my ($rfd, $wfd) or return;
207f1a75 4395 defined(my $pid = fork) or ::fatal "Can't fork: $!";
f8c9d1d2
EW
4396 if (!$pid) {
4397 open STDOUT, '>&', $wfd or
207f1a75 4398 ::fatal "Can't redirect to stdout: $!";
f8c9d1d2
EW
4399 return;
4400 }
207f1a75 4401 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
f8c9d1d2 4402 $ENV{LESS} ||= 'FRSX';
207f1a75 4403 exec $pager or ::fatal "Can't run pager: $! ($pager)";
f8c9d1d2
EW
4404}
4405
b2b3ada7
DK
4406sub format_svn_date {
4407 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4408}
4409
4410sub parse_git_date {
4411 my ($t, $tz) = @_;
4412 # Date::Parse isn't in the standard Perl distro :(
4413 if ($tz =~ s/^\+//) {
4414 $t += tz_to_s_offset($tz);
4415 } elsif ($tz =~ s/^\-//) {
4416 $t -= tz_to_s_offset($tz);
4417 }
4418 return $t;
4419}
4420
4421sub set_local_timezone {
4422 if (defined $TZ) {
4423 $ENV{TZ} = $TZ;
4424 } else {
4425 delete $ENV{TZ};
4426 }
4427}
4428
21819a37
EW
4429sub tz_to_s_offset {
4430 my ($tz) = @_;
4431 $tz =~ s/(\d\d)$//;
4432 return ($1 * 60) + ($tz * 3600);
4433}
4434
f8c9d1d2
EW
4435sub get_author_info {
4436 my ($dest, $author, $t, $tz) = @_;
4437 $author =~ s/(?:^\s*|\s*$)//g;
4438 $dest->{a_raw} = $author;
4439 my $au;
1c8443b0 4440 if ($::_authors) {
f8c9d1d2
EW
4441 $au = $rusers{$author} || undef;
4442 }
4443 if (!$au) {
4444 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4445 }
4446 $dest->{t} = $t;
4447 $dest->{tz} = $tz;
4448 $dest->{a} = $au;
b2b3ada7 4449 $dest->{t_utc} = parse_git_date($t, $tz);
f8c9d1d2
EW
4450}
4451
4452sub process_commit {
4453 my ($c, $r_min, $r_max, $defer) = @_;
4454 if (defined $r_min && defined $r_max) {
4455 if ($r_min == $c->{r} && $r_min == $r_max) {
4456 show_commit($c);
4457 return 0;
4458 }
4459 return 1 if $r_min == $r_max;
4460 if ($r_min < $r_max) {
4461 # we need to reverse the print order
4462 return 0 if (defined $limit && --$limit < 0);
4463 push @$defer, $c;
4464 return 1;
4465 }
4466 if ($r_min != $r_max) {
4467 return 1 if ($r_min < $c->{r});
4468 return 1 if ($r_max > $c->{r});
4469 }
4470 }
4471 return 0 if (defined $limit && --$limit < 0);
4472 show_commit($c);
4473 return 1;
4474}
4475
4476sub show_commit {
4477 my $c = shift;
4478 if ($oneline) {
4479 my $x = "\n";
4480 if (my $l = $c->{l}) {
4481 while ($l->[0] =~ /^\s*$/) { shift @$l }
4482 $x = $l->[0];
4483 }
4484 $l_fmt ||= 'A' . length($c->{r});
4485 print 'r',pack($l_fmt, $c->{r}),' | ';
4486 print "$c->{c} | " if $show_commit;
4487 print $x;
4488 } else {
4489 show_commit_normal($c);
4490 }
4491}
4492
4493sub show_commit_changed_paths {
4494 my ($c) = @_;
4495 return unless $c->{changed};
4496 print "Changed paths:\n", @{$c->{changed}};
4497}
4498
4499sub show_commit_normal {
4500 my ($c) = @_;
111947ef 4501 print commit_log_separator, "r$c->{r} | ";
f8c9d1d2 4502 print "$c->{c} | " if $show_commit;
b2b3ada7 4503 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
f8c9d1d2
EW
4504 my $nr_line = 0;
4505
4506 if (my $l = $c->{l}) {
4507 while ($l->[$#$l] eq "\n" && $#$l > 0
4508 && $l->[($#$l - 1)] eq "\n") {
4509 pop @$l;
4510 }
4511 $nr_line = scalar @$l;
4512 if (!$nr_line) {
4513 print "1 line\n\n\n";
4514 } else {
4515 if ($nr_line == 1) {
4516 $nr_line = '1 line';
4517 } else {
4518 $nr_line .= ' lines';
4519 }
4520 print $nr_line, "\n";
4521 show_commit_changed_paths($c);
4522 print "\n";
4523 print $_ foreach @$l;
4524 }
4525 } else {
4526 print "1 line\n";
4527 show_commit_changed_paths($c);
4528 print "\n";
4529
4530 }
488a63ec 4531 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
4532 if ($c->{$x}) {
4533 print "\n";
4534 print $_ foreach @{$c->{$x}}
4535 }
4536 }
4537}
4538
4539sub cmd_show_log {
4540 my (@args) = @_;
4541 my ($r_min, $r_max);
4542 my $r_last = -1; # prevent dupes
b2b3ada7 4543 set_local_timezone();
f8c9d1d2
EW
4544 if (defined $::_revision) {
4545 if ($::_revision =~ /^(\d+):(\d+)$/) {
4546 ($r_min, $r_max) = ($1, $2);
4547 } elsif ($::_revision =~ /^\d+$/) {
4548 $r_min = $r_max = $::_revision;
4549 } else {
4550 ::fatal "-r$::_revision is not supported, use ",
207f1a75 4551 "standard 'git log' arguments instead";
f8c9d1d2
EW
4552 }
4553 }
4554
4555 config_pager();
6ed77266 4556 @args = git_svn_log_cmd($r_min, $r_max, @args);
111947ef
DK
4557 if (!@args) {
4558 print commit_log_separator unless $incremental || $oneline;
4559 return;
4560 }
f8c9d1d2
EW
4561 my $log = command_output_pipe(@args);
4562 run_pager();
488a63ec 4563 my (@k, $c, $d, $stat);
f8c9d1d2
EW
4564 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4565 while (<$log>) {
60f3ff12 4566 if (/^${esc_color}commit -?($::sha1_short)/o) {
f8c9d1d2
EW
4567 my $cmt = $1;
4568 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4569 $r_last = $c->{r};
4570 process_commit($c, $r_min, $r_max, \@k) or
4571 goto out;
4572 }
4573 $d = undef;
4574 $c = { c => $cmt };
4575 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4576 get_author_info($c, $1, $2, $3);
4577 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4578 # ignore
4579 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4580 push @{$c->{raw}}, $_;
4581 } elsif (/^${esc_color}[ACRMDT]\t/) {
4582 # we could add $SVN->{svn_path} here, but that requires
4583 # remote access at the moment (repo_path_split)...
4584 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4585 push @{$c->{changed}}, $_;
4586 } elsif (/^${esc_color}diff /o) {
4587 $d = 1;
4588 push @{$c->{diff}}, $_;
4589 } elsif ($d) {
4590 push @{$c->{diff}}, $_;
488a63ec
EW
4591 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4592 $esc_color*[\+\-]*$esc_color$/x) {
4593 $stat = 1;
4594 push @{$c->{stat}}, $_;
4595 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4596 push @{$c->{stat}}, $_;
4597 $stat = undef;
f8c9d1d2
EW
4598 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4599 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4600 } elsif (s/^${esc_color} //o) {
4601 push @{$c->{l}}, $_;
4602 }
4603 }
4604 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4605 $r_last = $c->{r};
4606 process_commit($c, $r_min, $r_max, \@k);
4607 }
4608 if (@k) {
111947ef 4609 ($r_min, $r_max) = ($r_max, $r_min);
f8c9d1d2
EW
4610 process_commit($_, $r_min, $r_max) foreach reverse @k;
4611 }
4612out:
c843c464 4613 close $log;
111947ef 4614 print commit_log_separator unless $incremental || $oneline;
f8c9d1d2
EW
4615}
4616
6fb5375e 4617sub cmd_blame {
4be40381 4618 my $path = pop;
6fb5375e
TS
4619
4620 config_pager();
4621 run_pager();
4622
4be40381
SG
4623 my ($fh, $ctx, $rev);
4624
4625 if ($_git_format) {
4626 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4627 while (my $line = <$fh>) {
4628 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4629 # Uncommitted edits show up as a rev ID of
4630 # all zeros, which we can't look up with
4631 # cmt_metadata
4632 if ($1 !~ /^0+$/) {
4633 (undef, $rev, undef) =
4634 ::cmt_metadata($1);
4635 $rev = '0' if (!$rev);
4636 } else {
4637 $rev = '0';
4638 }
4639 $rev = sprintf('%-10s', $rev);
4640 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4641 }
4642 print $line;
4643 }
4644 } else {
4645 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4646 '--', $path);
4647 my ($sha1);
4648 my %authors;
4649 while (my $line = <$fh>) {
4650 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4651 $sha1 = $1;
4652 (undef, $rev, undef) = ::cmt_metadata($1);
4653 $rev = '0' if (!$rev);
4654 }
4655 elsif ($line =~ /^author (.*)/) {
4656 $authors{$rev} = $1;
4657 $authors{$rev} =~ s/\s/_/g;
4658 }
4659 elsif ($line =~ /^\t(.*)$/) {
4660 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4661 }
6fb5375e 4662 }
6fb5375e
TS
4663 }
4664 command_close_pipe($fh, $ctx);
4665}
4666
706587fc
EW
4667package Git::SVN::Migration;
4668# these version numbers do NOT correspond to actual version numbers
4669# of git nor git-svn. They are just relative.
4670#
4671# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4672#
4673# v1 layout: .git/$id/info/url, refs/remotes/$id
4674#
4675# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4676#
4677# v3 layout: .git/svn/$id, refs/remotes/$id
4678# - info/url may remain for backwards compatibility
4679# - this is what we migrate up to this layout automatically,
4680# - this will be used by git svn init on single branches
26a62d57
EW
4681# v3.1 layout (auto migrated):
4682# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4683# for backwards compatibility
706587fc
EW
4684#
4685# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4686# - this is only created for newly multi-init-ed
4687# repositories. Similar in spirit to the
4688# --use-separate-remotes option in git-clone (now default)
4689# - we do not automatically migrate to this (following
4690# the example set by core git)
060610c5
EW
4691#
4692# v5 layout: .rev_db.$UUID => .rev_map.$UUID
4693# - newer, more-efficient format that uses 24-bytes per record
4694# with no filler space.
4695# - use xxd -c24 < .rev_map.$UUID to view and debug
4696# - This is a one-way migration, repositories updated to the
4697# new format will not be able to use old git-svn without
4698# rebuilding the .rev_db. Rebuilding the rev_db is not
4699# possible if noMetadata or useSvmProps are set; but should
4700# be no problem for users that use the (sensible) defaults.
706587fc
EW
4701use strict;
4702use warnings;
4703use Carp qw/croak/;
4704use File::Path qw/mkpath/;
47e39c55
EW
4705use File::Basename qw/dirname basename/;
4706use vars qw/$_minimize/;
706587fc
EW
4707
4708sub migrate_from_v0 {
4709 my $git_dir = $ENV{GIT_DIR};
4710 return undef unless -d $git_dir;
4711 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4712 my $migrated = 0;
4713 while (<$fh>) {
4714 chomp;
4715 my ($id, $orig_ref) = ($_, $_);
4716 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4717 next unless -f "$git_dir/$id/info/url";
4718 my $new_ref = "refs/remotes/$id";
4719 if (::verify_ref("$new_ref^0")) {
4720 print STDERR "W: $orig_ref is probably an old ",
4721 "branch used by an ancient version of ",
4722 "git-svn.\n",
4723 "However, $new_ref also exists.\n",
4724 "We will not be able ",
4725 "to use this branch until this ",
4726 "ambiguity is resolved.\n";
4727 next;
4728 }
4729 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4730 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4731 command_noisy('update-ref', $new_ref, $orig_ref);
4732 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4733 $migrated++;
4734 }
4735 command_close_pipe($fh, $ctx);
4736 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4737 $migrated;
4738}
4739
4740sub migrate_from_v1 {
4741 my $git_dir = $ENV{GIT_DIR};
4742 my $migrated = 0;
4743 return $migrated unless -d $git_dir;
4744 my $svn_dir = "$git_dir/svn";
4745
4746 # just in case somebody used 'svn' as their $id at some point...
4747 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4748
4749 print STDERR "Migrating from a git-svn v1 layout...\n";
4750 mkpath([$svn_dir]);
4751 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4752 "$svn_dir\n\t(required for this version ",
8f510bef 4753 "($::VERSION) of git-svn) does not exist.\n";
706587fc
EW
4754 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4755 while (<$fh>) {
4756 my $x = $_;
4757 next unless $x =~ s#^refs/remotes/##;
4758 chomp $x;
4759 next unless -f "$git_dir/$x/info/url";
4760 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4761 next unless $u;
4762 my $dn = dirname("$git_dir/svn/$x");
4763 mkpath([$dn]) unless -d $dn;
4764 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4765 mkpath(["$git_dir/svn/svn"]);
4766 print STDERR " - $git_dir/$x/info => ",
4767 "$git_dir/svn/$x/info\n";
4768 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4769 croak "$!: $x";
4770 # don't worry too much about these, they probably
4771 # don't exist with repos this old (save for index,
4772 # and we can easily regenerate that)
4773 foreach my $f (qw/unhandled.log index .rev_db/) {
4774 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4775 }
4776 } else {
4777 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4778 rename "$git_dir/$x", "$git_dir/svn/$x" or
4779 croak "$!: $x";
4780 }
4781 $migrated++;
4782 }
4783 command_close_pipe($fh, $ctx);
4784 print STDERR "Done migrating from a git-svn v1 layout\n";
4785 $migrated;
4786}
4787
4788sub read_old_urls {
4789 my ($l_map, $pfx, $path) = @_;
4790 my @dir;
4791 foreach (<$path/*>) {
4792 if (-r "$_/info/url") {
4793 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4794 my $ref_id = $pfx . basename $_;
4795 my $url = ::file_to_s("$_/info/url");
4796 $l_map->{$ref_id} = $url;
4797 } elsif (-d $_) {
4798 push @dir, $_;
4799 }
4800 }
4801 foreach (@dir) {
4802 my $x = $_;
4803 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4804 read_old_urls($l_map, $x, $_);
4805 }
4806}
4807
4808sub migrate_from_v2 {
4809 my @cfg = command(qw/config -l/);
4810 return if grep /^svn-remote\..+\.url=/, @cfg;
4811 my %l_map;
4812 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4813 my $migrated = 0;
4814
4815 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
4816 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4817 if ($@) {
4818 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4819 }
706587fc
EW
4820 $migrated++;
4821 }
4822 $migrated;
4823}
4824
47e39c55
EW
4825sub minimize_connections {
4826 my $r = Git::SVN::read_all_remotes();
4827 my $new_urls = {};
4828 my $root_repos = {};
4829 foreach my $repo_id (keys %$r) {
4830 my $url = $r->{$repo_id}->{url} or next;
4831 my $fetch = $r->{$repo_id}->{fetch} or next;
4832 my $ra = Git::SVN::Ra->new($url);
4833
4834 # skip existing cases where we already connect to the root
4835 if (($ra->{url} eq $ra->{repos_root}) ||
7829f20f 4836 ($ra->{repos_root} eq $repo_id)) {
47e39c55
EW
4837 $root_repos->{$ra->{url}} = $repo_id;
4838 next;
4839 }
4840
4841 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4842 my $root_path = $ra->{url};
4e9f6cc7 4843 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
4844 foreach my $path (keys %$fetch) {
4845 my $ref_id = $fetch->{$path};
4846 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4847
4848 # make sure we can read when connecting to
4849 # a higher level of a repository
4850 my ($last_rev, undef) = $gs->last_rev_commit;
4851 if (!defined $last_rev) {
4852 $last_rev = eval {
4853 $root_ra->get_latest_revnum;
4854 };
4855 next if $@;
4856 }
4857 my $new = $root_path;
4858 $new .= length $path ? "/$path" : '';
4859 eval {
4860 $root_ra->get_log([$new], $last_rev, $last_rev,
4861 0, 0, 1, sub { });
4862 };
4863 next if $@;
4864 $new_urls->{$ra->{repos_root}}->{$new} =
4865 { ref_id => $ref_id,
4866 old_repo_id => $repo_id,
4867 old_path => $path };
4868 }
4869 }
4870
4871 my @emptied;
4872 foreach my $url (keys %$new_urls) {
4873 # see if we can re-use an existing [svn-remote "repo_id"]
4874 # instead of creating a(n ugly) new section:
7829f20f 4875 my $repo_id = $root_repos->{$url} || $url;
47e39c55
EW
4876
4877 my $fetch = $new_urls->{$url};
4878 foreach my $path (keys %$fetch) {
4879 my $x = $fetch->{$path};
4880 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4881 my $pfx = "svn-remote.$x->{old_repo_id}";
4882
4883 my $old_fetch = quotemeta("$x->{old_path}:".
4884 "refs/remotes/$x->{ref_id}");
8b8fc068 4885 command_noisy(qw/config --unset/,
47e39c55
EW
4886 "$pfx.fetch", '^'. $old_fetch . '$');
4887 delete $r->{$x->{old_repo_id}}->
4888 {fetch}->{$x->{old_path}};
4889 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 4890 command_noisy(qw/config --unset/,
47e39c55
EW
4891 "$pfx.url");
4892 push @emptied, $x->{old_repo_id}
4893 }
4894 }
4895 }
4896 if (@emptied) {
4897 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4898 "$ENV{GIT_DIR}/config";
4899 print STDERR <<EOF;
4900The following [svn-remote] sections in your config file ($file) are empty
4901and can be safely removed:
4902EOF
4903 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4904 }
4905}
4906
706587fc
EW
4907sub migration_check {
4908 migrate_from_v0();
4909 migrate_from_v1();
4910 migrate_from_v2();
47e39c55 4911 minimize_connections() if $_minimize;
706587fc
EW
4912}
4913
ef3cfaad
EW
4914package Git::IndexInfo;
4915use strict;
4916use warnings;
4917use Git qw/command_input_pipe command_close_pipe/;
4918
4919sub new {
4920 my ($class) = @_;
4921 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4922 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4923}
4924
4925sub remove {
4926 my ($self, $path) = @_;
4927 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4928 return ++$self->{nr};
4929 }
4930 undef;
4931}
4932
4933sub update {
4934 my ($self, $mode, $hash, $path) = @_;
4935 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4936 return ++$self->{nr};
4937 }
4938 undef;
4939}
4940
4941sub DESTROY {
4942 my ($self) = @_;
4943 command_close_pipe($self->{gui}, $self->{ctx});
4944}
4945
4bb9ed04
EW
4946package Git::SVN::GlobSpec;
4947use strict;
4948use warnings;
4949
4950sub new {
4951 my ($class, $glob) = @_;
4bb9ed04
EW
4952 my $re = $glob;
4953 $re =~ s!/+$!!g; # no need for trailing slashes
570d35c2
MG
4954 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
4955 my $temp = $re;
4956 my ($left, $right) = ($1, $3);
4957 $re = $2;
4958 my $depth = $re =~ tr/*/*/;
4959 if ($depth != $temp =~ tr/*/*/) {
4960 die "Only one set of wildcard directories " .
4961 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
4962 }
4963 if ($depth == 0) {
e518192f 4964 die "One '*' is needed for glob: '$glob'\n";
4bb9ed04 4965 }
570d35c2
MG
4966 $re =~ s!\*!\[^/\]*!g;
4967 $re = quotemeta($left) . "($re)" . quotemeta($right);
4e9f6cc7
EW
4968 if (length $left && !($left =~ s!/+$!!g)) {
4969 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4970 }
4971 if (length $right && !($right =~ s!^/+!!g)) {
4972 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4973 }
74a81227
EW
4974 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4975 bless { left => $left, right => $right, left_regex => $left_re,
570d35c2 4976 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4bb9ed04
EW
4977}
4978
4979sub full_path {
4980 my ($self, $path) = @_;
4981 return (length $self->{left} ? "$self->{left}/" : '') .
4982 $path . (length $self->{right} ? "/$self->{right}" : '');
4983}
4984
3397f9df
EW
4985__END__
4986
4987Data structures:
4988
4bb9ed04
EW
4989
4990$remotes = { # returned by read_all_remotes()
4991 'svn' => {
4992 # svn-remote.svn.url=https://svn.musicpd.org
4993 url => 'https://svn.musicpd.org',
4994 # svn-remote.svn.fetch=mpd/trunk:trunk
4995 fetch => {
4996 'mpd/trunk' => 'trunk',
4997 },
4998 # svn-remote.svn.tags=mpd/tags/*:tags/*
4999 tags => {
5000 path => {
5001 left => 'mpd/tags',
5002 right => '',
5003 regex => qr!mpd/tags/([^/]+)$!,
5004 glob => 'tags/*',
5005 },
5006 ref => {
5007 left => 'tags',
5008 right => '',
5009 regex => qr!tags/([^/]+)$!,
5010 glob => 'tags/*',
5011 },
5012 }
5013 }
5014};
5015
44320b9e 5016$log_entry hashref as returned by libsvn_log_entry()
3397f9df 5017{
44320b9e 5018 log => 'whitespace-formatted log entry
3397f9df
EW
5019', # trailing newline is preserved
5020 revision => '8', # integer
5021 date => '2004-02-24T17:01:44.108345Z', # commit date
5022 author => 'committer name'
5023};
5024
6e8548cc
EW
5025
5026# this is generated by generate_diff();
3397f9df
EW
5027@mods = array of diff-index line hashes, each element represents one line
5028 of diff-index output
5029
5030diff-index line ($m hash)
5031{
5032 mode_a => first column of diff-index output, no leading ':',
5033 mode_b => second column of diff-index output,
5034 sha1_b => sha1sum of the final blob,
ac8e0b91 5035 chg => change type [MCRADT],
3397f9df
EW
5036 file_a => original file name of a file (iff chg is 'C' or 'R')
5037 file_b => new/current file name of a file (any chg)
5038}
5039;
a5e0cedc 5040
a00439ac
EW
5041# retval of read_url_paths{,_all}();
5042$l_map = {
5043 # repository root url
5044 'https://svn.musicpd.org' => {
5045 # repository path # GIT_SVN_ID
5046 'mpd/trunk' => 'trunk',
5047 'mpd/tags/0.11.5' => 'tags/0.11.5',
5048 },
5049}
5050
a5e0cedc
EW
5051Notes:
5052 I don't trust the each() function on unless I created %hash myself
5053 because the internal iterator may not have started at base.