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