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