git-svn: add support for using svnsync properties
[git/git.git] / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
9760adcc
EW
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
3397f9df 9$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 10$VERSION = '@@GIT_VERSION@@';
13ccd6d4 11
706587fc 12$ENV{GIT_DIR} ||= '.git';
9fa00b65 13$Git::SVN::default_repo_id = 'svn';
8b8fc068 14$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 15$Git::SVN::Ra::_log_window_size = 100;
13ccd6d4 16
f8c9d1d2 17$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 18$ENV{TZ} = 'UTC';
a00439ac 19$| = 1; # unbuffer STDOUT
3397f9df 20
6fda05ae 21sub fatal (@) { print STDERR @_; exit 1 }
b9c85187
EW
22require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
23require SVN::Ra;
24require SVN::Delta;
25if ($SVN::Core::VERSION lt '1.1.0') {
26 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
27}
d81bf827 28push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
29push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
30push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df
EW
31use Carp qw/croak/;
32use IO::File qw//;
33use File::Basename qw/dirname basename/;
34use File::Path qw/mkpath/;
79bb8d88 35use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
968bdf1f 36use IPC::Open3;
336f1714 37use Git;
a5e0cedc 38
336f1714
EW
39BEGIN {
40 my $s;
41 foreach (qw/command command_oneline command_noisy command_output_pipe
42 command_input_pipe command_close_pipe/) {
43 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
706587fc 44 "*Git::SVN::Migration::$_ = ".
f8c9d1d2 45 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
336f1714
EW
46 }
47 eval $s;
48}
49
b9c85187 50my ($SVN);
83e9940a 51
f8c9d1d2
EW
52$sha1 = qr/[a-f\d]{40}/;
53$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 54my ($_stdin, $_help, $_edit,
9760adcc 55 $_message, $_file,
d05d72e0 56 $_template, $_shared,
e98671e5 57 $_version, $_fetch_all,
f8c9d1d2 58 $_merge, $_strategy, $_dry_run,
905f8b7d 59 $_prefix, $_no_checkout, $_verbose);
0bed5eaa 60$Git::SVN::_follow_parent = 1;
706587fc
EW
61my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
62 'config-dir=s' => \$Git::SVN::Ra::config_dir,
63 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
0bed5eaa 64my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 65 'authors-file|A=s' => \$_authors,
ecc712dd 66 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
67 'noMetadata' => \$Git::SVN::_no_metadata,
68 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 69 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 70 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 71 'no-checkout' => \$_no_checkout,
80f50749 72 'quiet|q' => \$_q,
ecc712dd
EW
73 'repack-flags|repack-args|repack-opts=s' =>
74 \$Git::SVN::_repack_flags,
706587fc 75 %remote_opts );
36f5b1f0 76
9d55b41a 77my ($_trunk, $_tags, $_branches);
dadc6d2a
EW
78my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
79 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
80 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
81 %remote_opts );
27e9fb8d 82my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
83 'rmdir' => \$SVN::Git::Editor::_rmdir,
84 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
85 'l=i' => \$SVN::Git::Editor::_rename_limit,
86 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 87);
9d55b41a 88
3397f9df 89my %cmd = (
2a3240be 90 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 91 { 'revision|r=s' => \$_revision,
905f8b7d 92 'fetch-all|all' => \$_fetch_all,
e98671e5 93 %fc_opts } ],
0425ea90
EW
94 clone => [ \&cmd_clone, "Initialize and fetch revisions",
95 { 'revision|r=s' => \$_revision,
96 %fc_opts, %init_opts } ],
d2866f9e 97 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 98 " (requires URL argument)",
9d55b41a 99 \%init_opts ],
dadc6d2a
EW
100 'multi-init' => [ \&cmd_multi_init,
101 "Deprecated alias for ".
102 "'$0 init -T<trunk> -b<branches> -t<tags>'",
103 \%init_opts ],
d7ad3bed
EW
104 dcommit => [ \&cmd_dcommit,
105 'Commit several diffs to merge with upstream',
3289e86e
EW
106 { 'merge|m|M' => \$_merge,
107 'strategy|s=s' => \$_strategy,
905f8b7d 108 'verbose|v' => \$_verbose,
3289e86e 109 'dry-run|n' => \$_dry_run,
905f8b7d 110 'fetch-all|all' => \$_fetch_all,
4b155223 111 %cmt_opts, %fc_opts } ],
1ce255dc
EW
112 'set-tree' => [ \&cmd_set_tree,
113 "Set an SVN repository to a git tree-ish",
114 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
5969cbe1 115 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
a5e0cedc 116 { 'revision|r=i' => \$_revision } ],
1c8443b0 117 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
118 "Deprecated alias for $0 fetch --all",
119 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
120 'migrate' => [ sub { },
121 # no-op, we automatically run this anyways,
706587fc
EW
122 'Migrate configuration/metadata/layout from
123 previous versions of git-svn',
a836a0e1
EW
124 { 'minimize' => \$Git::SVN::Migration::_minimize,
125 %remote_opts } ],
f8c9d1d2
EW
126 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
127 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 128 'revision|r=s' => \$_revision,
f8c9d1d2
EW
129 'verbose|v' => \$Git::SVN::Log::verbose,
130 'incremental' => \$Git::SVN::Log::incremental,
131 'oneline' => \$Git::SVN::Log::oneline,
132 'show-commit' => \$Git::SVN::Log::show_commit,
133 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 134 'authors-file|A=s' => \$_authors,
f8c9d1d2
EW
135 'color' => \$Git::SVN::Log::color,
136 'pager=s' => \$Git::SVN::Log::pager,
79bb8d88 137 } ],
905f8b7d
EW
138 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
139 { 'merge|m|M' => \$_merge,
140 'verbose|v' => \$_verbose,
141 'strategy|s=s' => \$_strategy,
142 'fetch-all|all' => \$_fetch_all,
143 %fc_opts } ],
44320b9e
EW
144 'commit-diff' => [ \&cmd_commit_diff,
145 'Commit a diff between two trees',
27e9fb8d
EW
146 { 'message|m=s' => \$_message,
147 'file|F=s' => \$_file,
45bf473a 148 'revision|r=s' => \$_revision,
27e9fb8d 149 %cmt_opts } ],
3397f9df 150);
9d55b41a 151
3397f9df
EW
152my $cmd;
153for (my $i = 0; $i < @ARGV; $i++) {
154 if (defined $cmd{$ARGV[$i]}) {
155 $cmd = $ARGV[$i];
156 splice @ARGV, $i, 1;
157 last;
158 }
159};
160
448c81b4 161my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 162
b8c92cad 163read_repo_config(\%opts);
9760adcc
EW
164my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
165 'minimize-connections' => \$Git::SVN::Migration::_minimize,
166 'id|i=s' => \$Git::SVN::default_ref_id,
167 'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
79bb8d88 168exit 1 if (!$rv && $cmd ne 'log');
6f0783cf 169
3397f9df 170usage(0) if $_help;
551ce28f 171version() if $_version;
eeb0abe0
EW
172usage(1) unless defined $cmd;
173load_authors() if $_authors;
0425ea90 174unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
175 Git::SVN::Migration::migration_check();
176}
ecc712dd 177Git::SVN::init_vars();
b805b44a
EW
178eval {
179 Git::SVN::verify_remotes_sanity();
180 $cmd{$cmd}->[0]->(@ARGV);
181};
182fatal $@ if $@;
1e889ef3 183post_fetch_checkout();
3397f9df
EW
184exit 0;
185
186####################### primary functions ######################
187sub usage {
188 my $exit = shift || 0;
189 my $fd = $exit ? \*STDERR : \*STDOUT;
190 print $fd <<"";
191git-svn - bidirectional operations between a single Subversion tree and git
192Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
193
194 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
195
196 foreach (sort keys %cmd) {
448c81b4 197 next if $cmd && $cmd ne $_;
a836a0e1 198 next if /^multi-/; # don't show deprecated commands
b203b769 199 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
200 foreach (keys %{$cmd{$_}->[2]}) {
201 # prints out arguments as they should be passed:
b8c92cad 202 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 203 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
204 "--$_" : "-$_" }
205 split /\|/,$_)," $x\n";
206 }
3397f9df
EW
207 }
208 print $fd <<"";
448c81b4
EW
209\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
210arbitrary identifier if you're tracking multiple SVN branches/repositories in
211one git repository and want to keep them separate. See git-svn(1) for more
212information.
3397f9df
EW
213
214 exit $exit;
215}
216
551ce28f 217sub version {
7d60ab2c 218 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
219 exit 0;
220}
221
8164b652
EW
222sub do_git_init_db {
223 unless (-d $ENV{GIT_DIR}) {
224 my @init_db = ('init');
225 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
226 if (defined $_shared) {
227 if ($_shared =~ /[a-z]/) {
228 push @init_db, "--shared=$_shared";
229 } else {
230 push @init_db, "--shared";
231 }
232 }
8164b652
EW
233 command_noisy(@init_db);
234 }
235}
236
dadc6d2a
EW
237sub init_subdir {
238 my $repo_path = shift or return;
239 mkpath([$repo_path]) unless -d $repo_path;
240 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
241 $ENV{GIT_DIR} = $repo_path . "/.git";
242}
243
0425ea90
EW
244sub cmd_clone {
245 my ($url, $path) = @_;
246 if (!defined $path &&
247 (defined $_trunk || defined $_branches || defined $_tags) &&
248 $url !~ m#^[a-z\+]+://#) {
249 $path = $url;
250 }
251 warn "--path: $path\n" if defined $path;
252 $path = basename($url) if !defined $path || !length $path;
253 warn "++path: $path\n" if defined $path;
254 mkpath([$path]);
255 chdir $path or die "Couldn't chdir to $path\n";
256 cmd_init(@_);
257 Git::SVN::fetch_all($Git::SVN::default_repo_id);
258}
259
d2866f9e 260sub cmd_init {
dadc6d2a
EW
261 if (defined $_trunk || defined $_branches || defined $_tags) {
262 return cmd_multi_init(@_);
03e0ea87 263 }
dadc6d2a
EW
264 my $url = shift or die "SVN repository location required ",
265 "as a command-line argument\n";
266 init_subdir(@_);
8164b652 267 do_git_init_db();
03e0ea87 268
706587fc 269 Git::SVN->init($url);
3397f9df
EW
270}
271
2a3240be 272sub cmd_fetch {
e98671e5
EW
273 if (grep /^\d+=./, @_) {
274 die "'<rev>=<commit>' fetch arguments are ",
275 "no longer supported.\n";
07a1c950 276 }
e98671e5
EW
277 my ($remote) = @_;
278 if (@_ > 1) {
905f8b7d 279 die "Usage: $0 fetch [--all] [svn-remote]\n";
e98671e5
EW
280 }
281 $remote ||= $Git::SVN::default_repo_id;
282 if ($_fetch_all) {
283 cmd_multi_fetch();
284 } else {
285 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 286 }
2a3240be
EW
287}
288
1ce255dc 289sub cmd_set_tree {
3397f9df
EW
290 my (@commits) = @_;
291 if ($_stdin || !@commits) {
292 print "Reading from stdin...\n";
293 @commits = ();
294 while (<STDIN>) {
1ca72aef 295 if (/\b($sha1_short)\b/o) {
3397f9df
EW
296 unshift @commits, $1;
297 }
298 }
299 }
300 my @revs;
8de010ad 301 foreach my $c (@commits) {
aef4e921 302 my @tmp = command('rev-parse',$c);
8de010ad
EW
303 if (scalar @tmp == 1) {
304 push @revs, $tmp[0];
305 } elsif (scalar @tmp > 1) {
aef4e921 306 push @revs, reverse(command('rev-list',@tmp));
8de010ad 307 } else {
1ce255dc 308 fatal "Failed to rev-parse $c\n";
8de010ad 309 }
3397f9df 310 }
1ce255dc
EW
311 my $gs = Git::SVN->new;
312 my ($r_last, $cmt_last) = $gs->last_rev_commit;
313 $gs->fetch;
97f6987a 314 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
315 fatal "There are new revisions that were fetched ",
316 "and need to be merged (or acknowledged) ",
317 "before committing.\nlast rev: $r_last\n",
318 " current: $gs->{last_rev}\n";
a5e0cedc 319 }
1ce255dc
EW
320 $gs->set_tree($_) foreach @revs;
321 print "Done committing ",scalar @revs," revisions to SVN\n";
a5e0cedc 322}
8f22562c 323
d7ad3bed
EW
324sub cmd_dcommit {
325 my $head = shift;
d7ad3bed 326 $head ||= 'HEAD';
a8ae2623 327 my @refs;
905f8b7d
EW
328 my ($url, $rev, $uuid) = working_head_info($head, \@refs);
329 my $c = $refs[-1];
a8ae2623
EW
330 unless (defined $url && defined $rev && defined $uuid) {
331 die "Unable to determine upstream SVN information from ",
905f8b7d 332 "$head history\n";
a8ae2623 333 }
60d9c97a 334 my $gs = Git::SVN->find_by_url($url);
45bf473a 335 my $last_rev;
a8ae2623 336 foreach my $d (@refs) {
aef4e921 337 if (!verify_ref("$d~1")) {
d7ad3bed
EW
338 fatal "Commit $d\n",
339 "has no parent commit, and therefore ",
340 "nothing to diff against.\n",
341 "You should be working from a repository ",
342 "originally created by git-svn\n";
48d044b5 343 }
45bf473a
EW
344 unless (defined $last_rev) {
345 (undef, $last_rev, undef) = cmt_metadata("$d~1");
346 unless (defined $last_rev) {
d7ad3bed
EW
347 fatal "Unable to extract revision information ",
348 "from commit $d~1\n";
45bf473a
EW
349 }
350 }
b22d4497
EW
351 if ($_dry_run) {
352 print "diff-tree $d~1 $d\n";
353 } else {
d7ad3bed 354 my %ed_opts = ( r => $last_rev,
61395354 355 log => get_commit_entry($d)->{log},
a8ae2623 356 ra => Git::SVN::Ra->new($url),
61395354
EW
357 tree_a => "$d~1",
358 tree_b => $d,
359 editor_cb => sub {
360 print "Committed r$_[0]\n";
361 $last_rev = $_[0]; },
a8ae2623 362 svn_path => '');
61395354 363 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed
EW
364 print "No changes\n$d~1 == $d\n";
365 }
b22d4497
EW
366 }
367 }
368 return if $_dry_run;
60d9c97a
EW
369 unless ($gs) {
370 warn "Could not determine fetch information for $url\n",
371 "Will not attempt to fetch and rebase commits.\n",
372 "This probably means you have useSvmProps and should\n",
373 "now resync your SVN::Mirror repository.\n";
374 return;
375 }
905f8b7d 376 $_fetch_all ? $gs->fetch_all : $gs->fetch;
d7ad3bed
EW
377 # we always want to rebase against the current HEAD, not any
378 # head that was passed to us
379 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
b22d4497
EW
380 my @finish;
381 if (@diff) {
905f8b7d 382 @finish = rebase_cmd();
d7ad3bed
EW
383 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
384 "using @finish:\n", "@diff";
b22d4497 385 } else {
d7ad3bed
EW
386 print "No changes between current HEAD and ",
387 $gs->refname, "\nResetting to the latest ",
388 $gs->refname, "\n";
4769489a 389 @finish = qw/reset --mixed/;
b22d4497 390 }
d7ad3bed 391 command_noisy(@finish, $gs->refname);
b22d4497
EW
392}
393
905f8b7d
EW
394sub cmd_rebase {
395 command_noisy(qw/update-index --refresh/);
396 my $url = (working_head_info('HEAD'))[0];
397 if (!defined $url) {
398 die "Unable to determine upstream SVN information from ",
399 "working tree history\n";
400 }
401
402 my $gs = Git::SVN->find_by_url($url);
403 if (command(qw/diff-index HEAD --/)) {
404 print STDERR "Cannot rebase with uncommited changes:\n";
405 command_noisy('status');
406 exit 1;
407 }
408 $_fetch_all ? $gs->fetch_all : $gs->fetch;
409 command_noisy(rebase_cmd(), $gs->refname);
410}
411
5969cbe1
EW
412sub cmd_show_ignore {
413 my $gs = Git::SVN->new;
414 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
415 $gs->traverse_ignore(\*STDOUT, '', $r);
a5e0cedc
EW
416}
417
8164b652 418sub cmd_multi_init {
9d55b41a 419 my $url = shift;
98327e58
EW
420 unless (defined $_trunk || defined $_branches || defined $_tags) {
421 usage(1);
9d55b41a 422 }
8164b652
EW
423 do_git_init_db();
424 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
425 if (defined $url) {
426 $url =~ s#/+$##;
427 init_subdir(@_);
428 }
98327e58 429 if (defined $_trunk) {
706587fc
EW
430 my $trunk_ref = $_prefix . 'trunk';
431 # try both old-style and new-style lookups:
432 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 433 unless ($gs_trunk) {
706587fc
EW
434 my ($trunk_url, $trunk_path) =
435 complete_svn_url($url, $_trunk);
436 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
437 undef, $trunk_ref);
98327e58 438 }
c35b96e7 439 }
706587fc 440 return unless defined $_branches || defined $_tags;
e7db67e6
EW
441 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
442 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
443 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
444}
445
1c8443b0 446sub cmd_multi_fetch {
0af9c9f9
EW
447 my $remotes = Git::SVN::read_all_remotes();
448 foreach my $repo_id (sort keys %$remotes) {
db03cd24 449 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
450 Git::SVN::fetch_all($repo_id, $remotes);
451 }
9d55b41a 452 }
9d55b41a
EW
453}
454
44320b9e
EW
455# this command is special because it requires no metadata
456sub cmd_commit_diff {
457 my ($ta, $tb, $url) = @_;
458 my $usage = "Usage: $0 commit-diff -r<revision> ".
459 "<tree-ish> <tree-ish> [<URL>]\n";
460 fatal($usage) if (!defined $ta || !defined $tb);
d3a840dc 461 my $svn_path;
44320b9e
EW
462 if (!defined $url) {
463 my $gs = eval { Git::SVN->new };
464 if (!$gs) {
465 fatal("Needed URL or usable git-svn --id in ",
466 "the command-line\n", $usage);
467 }
468 $url = $gs->{url};
d3a840dc 469 $svn_path = $gs->{path};
44320b9e
EW
470 }
471 unless (defined $_revision) {
472 fatal("-r|--revision is a required argument\n", $usage);
473 }
474 if (defined $_message && defined $_file) {
475 fatal("Both --message/-m and --file/-F specified ",
476 "for the commit message.\n",
477 "I have no idea what you mean\n");
478 }
479 if (defined $_file) {
480 $_message = file_to_s($_file);
481 } else {
482 $_message ||= get_commit_entry($tb)->{log};
483 }
484 my $ra ||= Git::SVN::Ra->new($url);
d3a840dc 485 $svn_path ||= $ra->{svn_path};
44320b9e
EW
486 my $r = $_revision;
487 if ($r eq 'HEAD') {
488 $r = $ra->get_latest_revnum;
489 } elsif ($r !~ /^\d+$/) {
490 die "revision argument: $r not understood by git-svn\n";
491 }
61395354
EW
492 my %ed_opts = ( r => $r,
493 log => $_message,
494 ra => $ra,
495 tree_a => $ta,
496 tree_b => $tb,
497 editor_cb => sub { print "Committed r$_[0]\n" },
498 svn_path => $svn_path );
499 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
500 print "No changes\n$ta == $tb\n";
501 }
44320b9e
EW
502}
503
3397f9df
EW
504########################### utility functions #########################
505
905f8b7d
EW
506sub rebase_cmd {
507 my @cmd = qw/rebase/;
508 push @cmd, '-v' if $_verbose;
509 push @cmd, qw/--merge/ if $_merge;
510 push @cmd, "--strategy=$_strategy" if $_strategy;
511 @cmd;
512}
513
1e889ef3
EW
514sub post_fetch_checkout {
515 return if $_no_checkout;
516 my $gs = $Git::SVN::_head or return;
517 return if verify_ref('refs/heads/master^0');
518
519 my $valid_head = verify_ref('HEAD^0');
520 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
521 return if ($valid_head || !verify_ref('HEAD^0'));
522
523 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
524 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
525 return if -f $index;
526
527 chomp(my $bare = `git config --bool --get core.bare`);
528 return if $bare eq 'true';
529 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
530 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
531 print STDERR "Checked out HEAD:\n ",
532 $gs->full_url, " r", $gs->last_rev, "\n";
533}
534
98327e58
EW
535sub complete_svn_url {
536 my ($url, $path) = @_;
537 $path =~ s#/+$##;
98327e58 538 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
539 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
540 fatal("E: '$path' is not a complete URL ",
541 "and a separate URL is not specified\n");
542 }
706587fc 543 return ($url, $path);
98327e58 544 }
706587fc 545 return ($path, '');
98327e58
EW
546}
547
9d55b41a 548sub complete_url_ls_init {
706587fc
EW
549 my ($ra, $repo_path, $switch, $pfx) = @_;
550 unless ($repo_path) {
9d55b41a
EW
551 print STDERR "W: $switch not specified\n";
552 return;
553 }
706587fc
EW
554 $repo_path =~ s#/+$##;
555 if ($repo_path =~ m#^[a-z\+]+://#) {
556 $ra = Git::SVN::Ra->new($repo_path);
557 $repo_path = '';
e7db67e6 558 } else {
706587fc 559 $repo_path =~ s#^/+##;
e7db67e6 560 unless ($ra) {
706587fc 561 fatal("E: '$repo_path' is not a complete URL ",
e7db67e6 562 "and a separate URL is not specified\n");
8164b652 563 }
e7db67e6 564 }
706587fc 565 my $url = $ra->{url};
b4d57e5e
EW
566 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
567 my $k = "svn-remote.$gs->{repo_id}.url";
568 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
569 if ($orig_url && ($orig_url ne $gs->{url})) {
570 die "$k already set: $orig_url\n",
571 "wanted to set to: $gs->{url}\n";
88cf4107 572 }
b4d57e5e
EW
573 command_oneline('config', $k, $gs->{url}) unless $orig_url;
574 my $remote_path = "$ra->{svn_path}/$repo_path/*";
575 $remote_path =~ s#/+#/#g;
576 $remote_path =~ s#^/##g;
577 my ($n) = ($switch =~ /^--(\w+)/);
578 if (length $pfx && $pfx !~ m#/$#) {
579 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 580 }
b4d57e5e
EW
581 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
582 "$remote_path:refs/remotes/$pfx*");
9d55b41a
EW
583}
584
aef4e921
EW
585sub verify_ref {
586 my ($ref) = @_;
2c5c1d53
EW
587 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
588 { STDERR => 0 }); };
aef4e921
EW
589}
590
a5e0cedc 591sub get_tree_from_treeish {
cf52b8f0 592 my ($treeish) = @_;
44320b9e 593 # $treeish can be a symbolic ref, too:
aef4e921 594 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
595 my $expected;
596 while ($type eq 'tag') {
aef4e921 597 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
598 }
599 if ($type eq 'commit') {
aef4e921
EW
600 $expected = (grep /^tree /, command(qw/cat-file commit/,
601 $treeish))[0];
44320b9e 602 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
603 die "Unable to get tree from $treeish\n" unless $expected;
604 } elsif ($type eq 'tree') {
605 $expected = $treeish;
606 } else {
607 die "$treeish is a $type, expected tree, tag or commit\n";
608 }
a5e0cedc
EW
609 return $expected;
610}
611
44320b9e
EW
612sub get_commit_entry {
613 my ($treeish) = shift;
614 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
615 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
616 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
617 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 618
44320b9e 619 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 620 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 621 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 622 $type, $treeish);
3397f9df
EW
623 my $in_msg = 0;
624 while (<$msg_fh>) {
625 if (!$in_msg) {
626 $in_msg = 1 if (/^\s*$/);
df746c5a 627 } elsif (/^git-svn-id: /) {
44320b9e
EW
628 # skip this for now, we regenerate the
629 # correct one on re-fetch anyways
630 # TODO: set *:merge properties or like...
3397f9df 631 } else {
44320b9e 632 print $log_fh $_ or croak $!;
3397f9df
EW
633 }
634 }
aef4e921 635 command_close_pipe($msg_fh, $ctx);
3397f9df 636 }
44320b9e 637 close $log_fh or croak $!;
3397f9df
EW
638
639 if ($_edit || ($type eq 'tree')) {
640 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
641 # TODO: strip out spaces, comments, like git-commit.sh
642 system($editor, $commit_editmsg);
3397f9df 643 }
44320b9e
EW
644 rename $commit_editmsg, $commit_msg or croak $!;
645 open $log_fh, '<', $commit_msg or croak $!;
646 { local $/; chomp($log_entry{log} = <$log_fh>); }
647 close $log_fh or croak $!;
648 unlink $commit_msg;
649 \%log_entry;
a5e0cedc
EW
650}
651
3397f9df
EW
652sub s_to_file {
653 my ($str, $file, $mode) = @_;
654 open my $fd,'>',$file or croak $!;
655 print $fd $str,"\n" or croak $!;
656 close $fd or croak $!;
657 chmod ($mode &~ umask, $file) if (defined $mode);
658}
659
660sub file_to_s {
661 my $file = shift;
662 open my $fd,'<',$file or croak "$!: file: $file\n";
663 local $/;
664 my $ret = <$fd>;
665 close $fd or croak $!;
666 $ret =~ s/\s*$//s;
667 return $ret;
668}
669
eeb0abe0
EW
670# '<svn username> = real-name <email address>' mapping based on git-svnimport:
671sub load_authors {
672 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 673 my $log = $cmd eq 'log';
eeb0abe0
EW
674 while (<$authors>) {
675 chomp;
8815788e 676 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 677 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
678 if ($log) {
679 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
680 } else {
681 $users{$user} = [$name, $email];
682 }
79bb8d88
EW
683 }
684 close $authors or croak $!;
685}
686
e0d10e1c 687# convert GetOpt::Long specs for use by git-config
b8c92cad 688sub read_repo_config {
706587fc 689 return unless -d $ENV{GIT_DIR};
b8c92cad 690 my $opts = shift;
97ae0911 691 my @config_only;
b8c92cad 692 foreach my $o (keys %$opts) {
97ae0911
EW
693 # if we have mixedCase and a long option-only, then
694 # it's a config-only variable that we don't need for
695 # the command-line.
696 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 697 my $v = $opts->{$o};
97ae0911 698 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 699 $key =~ s/-//g;
e0d10e1c 700 my $arg = 'git-config';
b8c92cad
EW
701 $arg .= ' --int' if ($o =~ /[:=]i$/);
702 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
703 if (ref $v eq 'ARRAY') {
704 chomp(my @tmp = `$arg --get-all svn.$key`);
705 @$v = @tmp if @tmp;
706 } else {
707 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 708 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
709 $$v = $tmp;
710 }
711 }
712 }
97ae0911 713 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
714}
715
79bb8d88 716sub extract_metadata {
c1927a85 717 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
718 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
719 \s([a-f\d\-]+)$/x);
e70dc780 720 if (!defined $rev || !$uuid || !$url) {
79bb8d88 721 # some of the original repositories I made had
82e5a82f 722 # identifiers like this:
79bb8d88
EW
723 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
724 }
725 return ($url, $rev, $uuid);
726}
727
c1927a85
EW
728sub cmt_metadata {
729 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 730 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
731}
732
905f8b7d
EW
733sub working_head_info {
734 my ($head, $refs) = @_;
735 my ($url, $rev, $uuid);
736 my ($fh, $ctx) = command_output_pipe('rev-list', $head);
737 while (<$fh>) {
738 chomp;
739 ($url, $rev, $uuid) = cmt_metadata($_);
740 last if (defined $url && defined $rev && defined $uuid);
741 unshift @$refs, $_ if $refs;
742 }
743 close $fh; # break the pipe
744 ($url, $rev, $uuid);
745}
746
9b981fc6
EW
747package Git::SVN;
748use strict;
749use warnings;
ecc712dd 750use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2
EW
751 $_repack $_repack_flags $_use_svm_props $_head
752 $_use_svnsync_props/;
9b981fc6
EW
753use Carp qw/croak/;
754use File::Path qw/mkpath/;
373274f9 755use File::Copy qw/copy/;
9b981fc6
EW
756use IPC::Open3;
757
ecc712dd 758my $_repack_nr;
9b981fc6
EW
759# properties that we do not log:
760my %SKIP_PROP;
761BEGIN {
762 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
763 svn:special svn:executable
764 svn:entry:committed-rev
765 svn:entry:last-author
766 svn:entry:uuid
767 svn:entry:committed-date/;
91b03282
EW
768
769 # some options are read globally, but can be overridden locally
770 # per [svn-remote "..."] section. Command-line options will *NOT*
771 # override options set in an [svn-remote "..."] section
772 my $e;
62e349d2
EW
773 foreach (qw/follow_parent no_metadata use_svm_props
774 use_svnsync_props/) {
91b03282
EW
775 my $key = $_;
776 $key =~ tr/_//d;
777 $e .= "sub $_ {
778 my (\$self) = \@_;
779 return \$self->{-$_} if exists \$self->{-$_};
780 my \$k = \"svn-remote.\$self->{repo_id}\.$key\";
781 eval { command_oneline(qw/config --get/, \$k) };
782 if (\$@) {
783 \$self->{-$_} = \$Git::SVN::_$_;
784 } else {
785 my \$v = command_oneline(qw/config --bool/,\$k);
786 \$self->{-$_} = \$v eq 'false' ? 0 : 1;
787 }
788 return \$self->{-$_} }\n";
789 }
790 $e .= "1;\n";
791 eval $e or die $@;
9b981fc6
EW
792}
793
373274f9
EW
794my %LOCKFILES;
795END { unlink keys %LOCKFILES if %LOCKFILES }
796
4bb9ed04
EW
797sub resolve_local_globs {
798 my ($url, $fetch, $glob_spec) = @_;
799 return unless defined $glob_spec;
800 my $ref = $glob_spec->{ref};
801 my $path = $glob_spec->{path};
802 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
803 next unless m#^refs/remotes/$ref->{regex}$#;
804 my $p = $1;
805 my $pathname = $path->full_path($p);
806 my $refname = $ref->full_path($p);
807 if (my $existing = $fetch->{$pathname}) {
808 if ($existing ne $refname) {
809 die "Refspec conflict:\n",
810 "existing: refs/remotes/$existing\n",
811 " globbed: refs/remotes/$refname\n";
812 }
813 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 814 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
815 "refs/remotes/$refname: '$url' not found in '$u'\n";
816 if ($pathname ne $u) {
817 warn "W: Refspec glob conflict ",
818 "(ref: refs/remotes/$refname):\n",
819 "expected path: $pathname\n",
820 " real path: $u\n",
821 "Continuing ahead with $u\n";
822 next;
823 }
824 } else {
4bb9ed04
EW
825 $fetch->{$pathname} = $refname;
826 }
827 }
828}
829
e98671e5
EW
830sub parse_revision_argument {
831 my ($base, $head) = @_;
832 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
833 return ($base, $head);
834 }
835 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
836 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
837 return ($head, $head) if ($::_revision eq 'HEAD');
838 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
839 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
840 die "revision argument: $::_revision not understood by git-svn\n";
841}
842
0af9c9f9 843sub fetch_all {
4bb9ed04 844 my ($repo_id, $remotes) = @_;
905f8b7d
EW
845 if (ref $repo_id) {
846 my $gs = $repo_id;
847 $repo_id = undef;
848 $repo_id = $gs->{repo_id};
849 }
850 $remotes ||= read_all_remotes();
7447b4bc
EW
851 my $remote = $remotes->{$repo_id} or
852 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 853 my $fetch = $remote->{fetch};
7447b4bc 854 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 855 my (@gs, @globs);
0af9c9f9 856 my $ra = Git::SVN::Ra->new($url);
26a62d57 857 my $uuid = $ra->get_uuid;
0af9c9f9 858 my $head = $ra->get_latest_revnum;
28710f74 859 my $base = defined $fetch ? $head : 0;
e518192f
EW
860
861 # read the max revs for wildcard expansion (branches/*, tags/*)
862 foreach my $t (qw/branches tags/) {
863 defined $remote->{$t} or next;
864 push @globs, $remote->{$t};
93f2689c
EW
865 my $max_rev = eval { tmp_config(qw/--int --get/,
866 "svn-remote.$repo_id.${t}-maxRev") };
867 if (defined $max_rev && ($max_rev < $base)) {
868 $base = $max_rev;
d6d3346b
EW
869 } elsif (!defined $max_rev) {
870 $base = 0;
e518192f
EW
871 }
872 }
873
db03cd24
EW
874 if ($fetch) {
875 foreach my $p (sort keys %$fetch) {
876 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
877 my $lr = $gs->rev_db_max;
878 if (defined $lr) {
879 $base = $lr if ($lr < $base);
880 }
881 push @gs, $gs;
0af9c9f9 882 }
0af9c9f9 883 }
e98671e5
EW
884
885 ($base, $head) = parse_revision_argument($base, $head);
e518192f 886 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
887}
888
47e39c55
EW
889sub read_all_remotes {
890 my $r = {};
8b8fc068 891 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
47e39c55
EW
892 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
893 $r->{$1}->{fetch}->{$2} = $3;
894 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
895 $r->{$1}->{url} = $2;
4bb9ed04
EW
896 } elsif (m!^(.+)\.(branches|tags)=
897 (.*):refs/remotes/(.+)\s*$/!x) {
898 my ($p, $g) = ($3, $4);
899 my $rs = $r->{$1}->{$2} = {
e518192f 900 t => $2,
93f2689c 901 remote => $1,
4bb9ed04
EW
902 path => Git::SVN::GlobSpec->new($p),
903 ref => Git::SVN::GlobSpec->new($g) };
904 if (length($rs->{ref}->{right}) != 0) {
905 die "The '*' glob character must be the last ",
906 "character of '$g'\n";
907 }
47e39c55
EW
908 }
909 }
910 $r;
911}
912
ecc712dd
EW
913sub init_vars {
914 if (defined $_repack) {
915 $_repack = 1000 if ($_repack <= 0);
916 $_repack_nr = $_repack;
917 $_repack_flags ||= '-d';
918 }
919}
920
b805b44a 921sub verify_remotes_sanity {
536c4b09 922 return unless -d $ENV{GIT_DIR};
b805b44a
EW
923 my %seen;
924 foreach (command(qw/config -l/)) {
925 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
926 if ($seen{$1}) {
927 die "Remote ref refs/remote/$1 is tracked by",
928 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
929 "Please resolve this ambiguity in ",
930 "your git configuration file before ",
931 "continuing\n";
932 }
933 $seen{$1} = $_;
934 }
935 }
936}
937
47e39c55 938# we allow more chars than remotes2config.sh...
706587fc
EW
939sub sanitize_remote_name {
940 my ($name) = @_;
47e39c55 941 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
706587fc
EW
942 $name;
943}
944
e6434f87
EW
945sub find_existing_remote {
946 my ($url, $remotes) = @_;
947 my $existing;
948 foreach my $repo_id (keys %$remotes) {
949 my $u = $remotes->{$repo_id}->{url} or next;
950 next if $u ne $url;
951 $existing = $repo_id;
952 last;
953 }
954 $existing;
955}
b805b44a 956
e6434f87 957sub init_remote_config {
d8115c51 958 my ($self, $url, $no_write) = @_;
e6434f87
EW
959 $url =~ s!/+$!!; # strip trailing slash
960 my $r = read_all_remotes();
961 my $existing = find_existing_remote($url, $r);
962 if ($existing) {
e518192f
EW
963 unless ($no_write) {
964 print STDERR "Using existing ",
965 "[svn-remote \"$existing\"]\n";
966 }
e6434f87
EW
967 $self->{repo_id} = $existing;
968 } else {
969 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
970 $existing = find_existing_remote($min_url, $r);
971 if ($existing) {
e518192f
EW
972 unless ($no_write) {
973 print STDERR "Using existing ",
974 "[svn-remote \"$existing\"]\n";
975 }
e6434f87
EW
976 $self->{repo_id} = $existing;
977 }
978 if ($min_url ne $url) {
e518192f
EW
979 unless ($no_write) {
980 print STDERR "Using higher level of URL: ",
981 "$url => $min_url\n";
982 }
e6434f87
EW
983 my $old_path = $self->{path};
984 $self->{path} = $url;
4e9f6cc7 985 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
986 if (length $old_path) {
987 $self->{path} .= "/$old_path";
988 }
989 $url = $min_url;
990 }
991 }
992 my $orig_url;
993 if (!$existing) {
b805b44a 994 # verify that we aren't overwriting anything:
e6434f87 995 $orig_url = eval {
706587fc 996 command_oneline('config', '--get',
e6434f87 997 "svn-remote.$self->{repo_id}.url")
706587fc 998 };
b805b44a 999 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1000 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1001 "$orig_url\nwanted to set to: $url\n";
1002 }
9b981fc6 1003 }
e6434f87
EW
1004 my ($xrepo_id, $xpath) = find_ref($self->refname);
1005 if (defined $xpath) {
1006 die "svn-remote.$xrepo_id.fetch already set to track ",
1007 "$xpath:refs/remotes/", $self->refname, "\n";
1008 }
d8115c51
EW
1009 unless ($no_write) {
1010 command_noisy('config',
1011 "svn-remote.$self->{repo_id}.url", $url);
1012 command_noisy('config', '--add',
1013 "svn-remote.$self->{repo_id}.fetch",
1014 "$self->{path}:".$self->refname);
1015 }
9b981fc6 1016 $self->{url} = $url;
e6434f87
EW
1017}
1018
a8ae2623
EW
1019sub find_by_url { # repos_root and, path are optional
1020 my ($class, $full_url, $repos_root, $path) = @_;
1021 my $remotes = read_all_remotes();
1022 if (defined $full_url && defined $repos_root && !defined $path) {
1023 $path = $full_url;
1024 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1025 }
1026 foreach my $repo_id (keys %$remotes) {
1027 my $u = $remotes->{$repo_id}->{url} or next;
1028 next if defined $repos_root && $repos_root ne $u;
1029
1030 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1031 foreach (qw/branches tags/) {
1032 resolve_local_globs($u, $fetch,
1033 $remotes->{$repo_id}->{$_});
1034 }
1035 my $p = $path;
1036 unless (defined $p) {
1037 $p = $full_url;
1038 $p =~ s#^\Q$u\E(?:/|$)## or next;
1039 }
1040 foreach my $f (keys %$fetch) {
1041 next if $f ne $p;
1042 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1043 }
1044 }
1045 undef;
1046}
1047
e6434f87 1048sub init {
d8115c51 1049 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1050 my $self = _new($class, $repo_id, $ref_id, $path);
1051 if (defined $url) {
d8115c51 1052 $self->init_remote_config($url, $no_write);
e6434f87 1053 }
9b981fc6
EW
1054 $self;
1055}
1056
706587fc
EW
1057sub find_ref {
1058 my ($ref_id) = @_;
1059 foreach (command(qw/config -l/)) {
1060 next unless m!^svn-remote\.(.+)\.fetch=
1061 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1062 my ($repo_id, $path, $ref) = ($1, $2, $3);
1063 if ($ref eq $ref_id) {
1064 $path = '' if ($path =~ m#^\./?#);
1065 return ($repo_id, $path);
1066 }
1067 }
1068 (undef, undef, undef);
1069}
1070
9b981fc6 1071sub new {
706587fc
EW
1072 my ($class, $ref_id, $repo_id, $path) = @_;
1073 if (defined $ref_id && !defined $repo_id && !defined $path) {
1074 ($repo_id, $path) = find_ref($ref_id);
1075 if (!defined $repo_id) {
1076 die "Could not find a \"svn-remote.*.fetch\" key ",
1077 "in the repository configuration matching: ",
1078 "refs/remotes/$ref_id\n";
1079 }
1080 }
1081 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1082 if (!defined $self->{path} || !length $self->{path}) {
1083 my $fetch = command_oneline('config', '--get',
1084 "svn-remote.$repo_id.fetch",
1085 ":refs/remotes/$ref_id\$") or
1086 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1087 "\":refs/remotes/$ref_id\$\" in config\n";
1088 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1089 }
706587fc
EW
1090 $self->{url} = command_oneline('config', '--get',
1091 "svn-remote.$repo_id.url") or
1092 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1093 $self->rebuild;
9b981fc6
EW
1094 $self;
1095}
1096
706587fc 1097sub refname { "refs/remotes/$_[0]->{ref_id}" }
9b981fc6 1098
26a62d57
EW
1099sub svm_uuid {
1100 my ($self) = @_;
1101 return $self->{svm}->{uuid} if $self->svm;
1102 $self->ra;
1103 unless ($self->{svm}) {
1104 die "SVM UUID not cached, and reading remotely failed\n";
1105 }
1106 $self->{svm}->{uuid};
1107}
8a49ee97 1108
26a62d57
EW
1109sub svm {
1110 my ($self) = @_;
1111 return $self->{svm} if $self->{svm};
1112 my $svm;
8a49ee97
EW
1113 # see if we have it in our config, first:
1114 eval {
26a62d57
EW
1115 my $section = "svn-remote.$self->{repo_id}";
1116 $svm = {
93f2689c
EW
1117 source => tmp_config('--get', "$section.svm-source"),
1118 uuid => tmp_config('--get', "$section.svm-uuid"),
8a49ee97
EW
1119 }
1120 };
26a62d57
EW
1121 $self->{svm} = $svm if ($svm && $svm->{source} && $svm->{uuid});
1122 $self->{svm};
1123}
1124
1125sub _set_svm_vars {
1126 my ($self, $ra) = @_;
db03cd24
EW
1127 return $ra if $self->svm;
1128
1129 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1130 "(svm:source, svm:mirror, svm:mirror) ",
1131 "from the following URLs:\n" );
1132 sub read_svm_props {
1133 my ($self, $props) = @_;
1134 my $src = $props->{'svm:source'};
1135 my $mirror = $props->{'svm:mirror'};
1136 my $uuid = $props->{'svm:uuid'};
1137 return undef if (!$src || !$mirror || !$uuid);
26a62d57 1138
db03cd24 1139 chomp($src, $mirror, $uuid);
26a62d57 1140
db03cd24
EW
1141 $uuid =~ m{^[0-9a-f\-]{30,}$}
1142 or die "doesn't look right - svm:uuid is '$uuid'\n";
8a49ee97
EW
1143 # don't know what a '!' is there for, also the
1144 # username is of no interest
db03cd24
EW
1145 $src =~ s{/?!$}{$mirror};
1146 $src =~ s{/+$}{}; # no trailing slashes please
8a49ee97 1147 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1148
db03cd24
EW
1149 my $section = "svn-remote.$self->{repo_id}";
1150 tmp_config('--add', "$section.svm-source", $src);
93f2689c 1151 tmp_config('--add', "$section.svm-uuid", $uuid);
8a49ee97 1152 $self->{svm} = { source => $src , uuid => $uuid };
db03cd24
EW
1153 return 1;
1154 }
1155
1156 my $r = $ra->get_latest_revnum;
1157 my $path = $self->{path};
1158 my @tried_a = ($path);
1159 while (length $path) {
1160 if ($self->read_svm_props(($ra->get_dir($path, $r))[2])) {
1161 return $ra;
1162 }
1163 $path =~ s#/?[^/]+$## && push @tried_a, $path;
8a49ee97 1164 }
db03cd24
EW
1165 if ($self->read_svm_props(($ra->get_dir('', $r))[2])) {
1166 return $ra;
8a49ee97 1167 }
db03cd24
EW
1168
1169 if ($ra->{repos_root} eq $self->{url}) {
1170 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n";
1171 }
1172
1173 # nope, make sure we're connected to the repository root:
1174 my $ok;
1175 my @tried_b;
1176 $path = $ra->{svn_path};
1177 $path =~ s#/?[^/]+$##; # we already tried this one above
1178 $ra = Git::SVN::Ra->new($ra->{repos_root});
1179 while (length $path) {
1180 $ok = $self->read_svm_props(($ra->get_dir($path, $r))[2]);
1181 last if $ok;
1182 $path =~ s#/?[^/]+$## && push @tried_b, $path;
1183 }
1184 $ok = $self->read_svm_props(($ra->get_dir('', $r))[2]) unless $ok;
1185 if (!$ok) {
1186 die @err, map { " $self->{url}/$_\n" } @tried_a, "\n",
1187 map { " $ra->{url}/$_\n" } @tried_b, "\n"
1188 }
1189 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1190}
1191
62e349d2
EW
1192sub svnsync {
1193 my ($self) = @_;
1194 return $self->{svnsync} if $self->{svnsync};
1195
1196 if ($self->no_metadata) {
1197 die "Can't have both 'noMetadata' and ",
1198 "'useSvnsyncProps' options set!\n";
1199 }
1200 if ($self->rewrite_root) {
1201 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1202 "options set!\n";
1203 }
1204
1205 my $svnsync;
1206 # see if we have it in our config, first:
1207 eval {
1208 my $section = "svn-remote.$self->{repo_id}";
1209 $svnsync = {
1210 url => tmp_config('--get', "$section.svnsync-url"),
1211 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1212 }
1213 };
1214 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1215 return $self->{svnsync} = $svnsync;
1216 }
1217
1218 my $err = "useSvnsyncProps set, but failed to read " .
1219 "svnsync property: svn:sync-from-";
1220 my $rp = $self->ra->rev_proplist(0);
1221
1222 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1223 $url =~ m{^[a-z\+]+://} or
1224 die "doesn't look right - svn:sync-from-url is '$url'\n";
1225
1226 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1227 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1228 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1229
1230 my $section = "svn-remote.$self->{repo_id}";
1231 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1232 tmp_config('--add', "$section.svnsync-url", $url);
1233 return $self->{svnsync} = { url => $url, uuid => $uuid };
1234}
1235
26a62d57
EW
1236# this allows us to memoize our SVN::Ra UUID locally and avoid a
1237# remote lookup (useful for 'git svn log').
1238sub ra_uuid {
1239 my ($self) = @_;
1240 unless ($self->{ra_uuid}) {
1241 my $key = "svn-remote.$self->{repo_id}.uuid";
1242 my $uuid = eval { tmp_config('--get', $key) };
1243 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1244 $self->{ra_uuid} = $uuid;
1245 } else {
1246 die "ra_uuid called without URL\n" unless $self->{url};
1247 $self->{ra_uuid} = $self->ra->get_uuid;
1248 tmp_config('--add', $key, $self->{ra_uuid});
1249 }
1250 }
1251 $self->{ra_uuid};
1252}
1253
9b981fc6
EW
1254sub ra {
1255 my ($self) = shift;
8a49ee97 1256 my $ra = Git::SVN::Ra->new($self->{url});
91b03282
EW
1257 if ($self->use_svm_props && !$self->{svm}) {
1258 if ($self->no_metadata) {
97ae0911
EW
1259 die "Can't have both 'noMetadata' and ",
1260 "'useSvmProps' options set!\n";
62e349d2
EW
1261 } elsif ($self->use_svnsync_props) {
1262 die "Can't have both 'useSvnsyncProps' and ",
1263 "'useSvmProps' options set!\n";
91b03282 1264 }
26a62d57 1265 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
1266 $self->{-want_revprops} = 1;
1267 }
1268 $ra;
9b981fc6
EW
1269}
1270
15710b6f
EW
1271sub rel_path {
1272 my ($self) = @_;
1273 my $repos_root = $self->ra->{repos_root};
1274 return $self->{path} if ($self->{url} eq $repos_root);
4e9f6cc7
EW
1275 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
1276 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
15710b6f
EW
1277}
1278
9b981fc6
EW
1279sub traverse_ignore {
1280 my ($self, $fh, $path, $r) = @_;
1281 $path =~ s#^/+##g;
5d3b7cd5
EW
1282 my $ra = $self->ra;
1283 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
9b981fc6 1284 my $p = $path;
5d3b7cd5 1285 $p =~ s#^\Q$ra->{svn_path}\E/##;
9b981fc6
EW
1286 print $fh length $p ? "\n# $p\n" : "\n# /\n";
1287 if (my $s = $props->{'svn:ignore'}) {
1288 $s =~ s/[\r\n]+/\n/g;
1289 chomp $s;
1290 if (length $p == 0) {
1291 $s =~ s#\n#\n/$p#g;
1292 print $fh "/$s\n";
1293 } else {
1294 $s =~ s#\n#\n/$p/#g;
1295 print $fh "/$p/$s\n";
1296 }
1297 }
1298 foreach (sort keys %$dirent) {
1299 next if $dirent->{$_}->kind != $SVN::Node::dir;
1300 $self->traverse_ignore($fh, "$path/$_", $r);
1301 }
1302}
1303
3ebe8df7
EW
1304sub last_rev { ($_[0]->last_rev_commit)[0] }
1305sub last_commit { ($_[0]->last_rev_commit)[1] }
1306
9b981fc6
EW
1307# returns the newest SVN revision number and newest commit SHA1
1308sub last_rev_commit {
1309 my ($self) = @_;
1310 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1311 return ($self->{last_rev}, $self->{last_commit});
1312 }
d2866f9e 1313 my $c = ::verify_ref($self->refname.'^0');
91b03282 1314 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 1315 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
1316 if (defined $rev) {
1317 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1318 return ($rev, $c);
1319 }
1320 }
26a62d57
EW
1321 my $db_path = $self->db_path;
1322 unless (-e $db_path) {
1323 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1324 return (undef, undef);
1325 }
9b981fc6
EW
1326 my $offset = -41; # from tail
1327 my $rl;
26a62d57 1328 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
ce4b4af7
EW
1329 sysseek($fh, $offset, 2); # don't care for errors
1330 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6 1331 chomp $rl;
ce4b4af7 1332 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
9b981fc6 1333 $offset -= 41;
ce4b4af7
EW
1334 sysseek($fh, $offset, 2); # don't care for errors
1335 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6
EW
1336 chomp $rl;
1337 }
91b03282 1338 if ($c && $c ne $rl) {
26a62d57 1339 die "$db_path and ", $self->refname,
9c93fee5
EW
1340 " inconsistent!:\n$c != $rl\n";
1341 }
ce4b4af7 1342 my $rev = sysseek($fh, 0, 1) or croak $!;
9b981fc6
EW
1343 $rev = ($rev - 41) / 41;
1344 close $fh or croak $!;
1345 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1346 return ($rev, $c);
1347}
1348
3ebe8df7
EW
1349sub get_fetch_range {
1350 my ($self, $min, $max) = @_;
1351 $max ||= $self->ra->get_latest_revnum;
9c93fee5 1352 $min ||= $self->rev_db_max;
3ebe8df7 1353 (++$min, $max);
9b981fc6
EW
1354}
1355
8a49ee97 1356sub tmp_config {
93f2689c 1357 my (@args) = @_;
b7e5348c
EW
1358 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1359 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1360 if (-e $old_def_config && ! -e $config) {
1361 rename $old_def_config, $config or
1362 die "Failed rename $old_def_config => $config: $!\n";
1363 }
8a49ee97 1364 my $old_config = $ENV{GIT_CONFIG};
93f2689c 1365 $ENV{GIT_CONFIG} = $config;
8a49ee97 1366 $@ = undef;
b4d57e5e
EW
1367 my @ret = eval {
1368 unless (-f $config) {
1369 mkfile($config);
1370 open my $fh, '>', $config or
1371 die "Can't open $config: $!\n";
1372 print $fh "; This file is used internally by ",
1373 "git-svn\n" or die
1374 "Couldn't write to $config: $!\n";
1375 print $fh "; You should not have to edit it\n" or
1376 die "Couldn't write to $config: $!\n";
1377 close $fh or die "Couldn't close $config: $!\n";
1378 }
1379 command('config', @args);
1380 };
8a49ee97
EW
1381 my $err = $@;
1382 if (defined $old_config) {
1383 $ENV{GIT_CONFIG} = $old_config;
1384 } else {
1385 delete $ENV{GIT_CONFIG};
1386 }
1387 die $err if $err;
1388 wantarray ? @ret : $ret[0];
1389}
1390
9b981fc6
EW
1391sub tmp_index_do {
1392 my ($self, $sub) = @_;
1393 my $old_index = $ENV{GIT_INDEX_FILE};
1394 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 1395 $@ = undef;
b4d57e5e
EW
1396 my @ret = eval {
1397 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1398 mkpath([$dir]) unless -d $dir;
1399 &$sub;
1400 };
8a49ee97
EW
1401 my $err = $@;
1402 if (defined $old_index) {
9b981fc6
EW
1403 $ENV{GIT_INDEX_FILE} = $old_index;
1404 } else {
1405 delete $ENV{GIT_INDEX_FILE};
1406 }
8a49ee97 1407 die $err if $err;
9b981fc6
EW
1408 wantarray ? @ret : $ret[0];
1409}
1410
1411sub assert_index_clean {
1412 my ($self, $treeish) = @_;
1413
1414 $self->tmp_index_do(sub {
1415 command_noisy('read-tree', $treeish) unless -e $self->{index};
1416 my $x = command_oneline('write-tree');
1417 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1418 /^tree ($::sha1)/mo);
e8d120bd
EW
1419 return if $y eq $x;
1420
1421 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1422 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1423 command_noisy('read-tree', $treeish);
9b981fc6
EW
1424 $x = command_oneline('write-tree');
1425 if ($y ne $x) {
1426 ::fatal "trees ($treeish) $y != $x\n",
1427 "Something is seriously wrong...\n";
1428 }
1429 });
1430}
1431
1432sub get_commit_parents {
0af9c9f9 1433 my ($self, $log_entry) = @_;
9b981fc6 1434 my (%seen, @ret, @tmp);
0af9c9f9
EW
1435 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1436 if (my $ip = $self->{inject_parents}) {
1437 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1438 push @tmp, $commit;
9b981fc6
EW
1439 }
1440 }
d2866f9e 1441 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
1442 push @tmp, $cur;
1443 }
44320b9e 1444 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
1445 while (my $p = shift @tmp) {
1446 next if $seen{$p};
1447 $seen{$p} = 1;
1448 push @ret, $p;
1449 # MAXPARENT is defined to 16 in commit-tree.c:
1450 last if @ret >= 16;
1451 }
1452 if (@tmp) {
44320b9e 1453 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
1454 join("\n\t", @tmp), "\n";
1455 }
1456 @ret;
1457}
1458
aea736cc
EW
1459sub rewrite_root {
1460 my ($self) = @_;
1461 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1462 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1463 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1464 if ($rwr) {
1465 $rwr =~ s#/+$##;
1466 if ($rwr !~ m#^[a-z\+]+://#) {
1467 die "$rwr is not a valid URL (key: $k)\n";
1468 }
1469 }
1470 $self->{-rewrite_root} = $rwr;
1471}
1472
1473sub metadata_url {
1474 my ($self) = @_;
1475 ($self->rewrite_root || $self->{url}) .
1476 (length $self->{path} ? '/' . $self->{path} : '');
1477}
1478
706587fc 1479sub full_url {
9b981fc6 1480 my ($self) = @_;
5d3b7cd5 1481 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
1482}
1483
1484sub do_git_commit {
0af9c9f9 1485 my ($self, $log_entry) = @_;
8a603774
EW
1486 my $lr = $self->last_rev;
1487 if (defined $lr && $lr >= $log_entry->{revision}) {
1488 die "Last fetched revision of ", $self->refname,
1489 " was r$lr, but we are about to fetch: ",
1490 "r$log_entry->{revision}!\n";
1491 }
44320b9e
EW
1492 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1493 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
1494 "Why are we refetching it?\n";
1495 }
db03cd24
EW
1496 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1497 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1498 $log_entry->{email};
44320b9e 1499 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 1500
44320b9e 1501 my $tree = $log_entry->{tree};
9b981fc6
EW
1502 if (!defined $tree) {
1503 $tree = $self->tmp_index_do(sub {
1504 command_oneline('write-tree') });
1505 }
1506 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1507
1508 my @exec = ('git-commit-tree', $tree);
0af9c9f9 1509 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
1510 push @exec, '-p', $_;
1511 }
1512 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1513 or croak $!;
44320b9e 1514 print $msg_fh $log_entry->{log} or croak $!;
91b03282 1515 unless ($self->no_metadata) {
8a49ee97
EW
1516 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1517 or croak $!;
9760adcc 1518 }
9b981fc6
EW
1519 $msg_fh->flush == 0 or croak $!;
1520 close $msg_fh or croak $!;
1521 chomp(my $commit = do { local $/; <$out_fh> });
1522 close $out_fh or croak $!;
1523 waitpid $pid, 0;
1524 croak $? if $?;
1525 if ($commit !~ /^$::sha1$/o) {
1526 die "Failed to commit, invalid sha1: $commit\n";
1527 }
1528
373274f9 1529 $self->rev_db_set($log_entry->{revision}, $commit, 1);
9b981fc6 1530
44320b9e 1531 $self->{last_rev} = $log_entry->{revision};
9b981fc6 1532 $self->{last_commit} = $commit;
8a49ee97
EW
1533 print "r$log_entry->{revision}";
1534 if (defined $log_entry->{svm_revision}) {
1535 print " (\@$log_entry->{svm_revision})";
26a62d57
EW
1536 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1537 0, $self->svm_uuid);
8a49ee97
EW
1538 }
1539 print " = $commit ($self->{ref_id})\n";
ecc712dd
EW
1540 if (defined $_repack && (--$_repack_nr == 0)) {
1541 $_repack_nr = $_repack;
1542 # repack doesn't use any arguments with spaces in them, does it?
1543 print "Running git repack $_repack_flags ...\n";
1544 command_noisy('repack', split(/\s+/, $_repack_flags));
1545 print "Done repacking\n";
1546 }
9b981fc6
EW
1547 return $commit;
1548}
1549
fbcc1737
EW
1550sub match_paths {
1551 my ($self, $paths, $r) = @_;
4e9f6cc7 1552 return 1 if $self->{path} eq '';
d542aedb
EW
1553 if (my $path = $paths->{"/$self->{path}"}) {
1554 return ($path->{action} eq 'D') ? 0 : 1;
1555 }
4e9f6cc7 1556 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
1557 if (grep /$self->{path_regex}/, keys %$paths) {
1558 return 1;
1559 }
1560 my $c = '';
1561 foreach (split m#/#, $self->{path}) {
1562 $c .= "/$_";
74a81227
EW
1563 next unless ($paths->{$c} &&
1564 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
1565 if ($self->ra->check_path($self->{path}, $r) ==
1566 $SVN::Node::dir) {
fbcc1737
EW
1567 return 1;
1568 }
1569 }
1570 return 0;
1571}
1572
15710b6f
EW
1573sub find_parent_branch {
1574 my ($self, $paths, $rev) = @_;
91b03282 1575 return undef unless $self->follow_parent;
e5a0b240 1576 unless (defined $paths) {
c7eba716
EW
1577 my $err_handler = $SVN::Error::handler;
1578 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
1579 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1580 $paths =
1581 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 1582 $SVN::Error::handler = $err_handler;
e5a0b240
EW
1583 }
1584 return undef unless defined $paths;
15710b6f
EW
1585
1586 # look for a parent from another branch:
7f578c55
EW
1587 my @b_path_components = split m#/#, $self->rel_path;
1588 my @a_path_components;
1589 my $i;
1590 while (@b_path_components) {
1591 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 1592 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
1593 unshift(@a_path_components, pop(@b_path_components));
1594 }
74a81227
EW
1595 return undef unless defined $i && defined $i->{copyfrom_path};
1596 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
1597 if (@a_path_components) {
1598 print STDERR "branch_from: $branch_from => ";
1599 $branch_from .= '/'.join('/', @a_path_components);
1600 print STDERR $branch_from, "\n";
1601 }
3ebe8df7 1602 my $r = $i->{copyfrom_rev};
15710b6f
EW
1603 my $repos_root = $self->ra->{repos_root};
1604 my $url = $self->ra->{url};
1605 my $new_url = $repos_root . $branch_from;
1606 print STDERR "Found possible branch point: ",
1607 "$new_url => ", $self->full_url, ", $r\n";
1608 $branch_from =~ s#^/##;
a8ae2623 1609 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
15710b6f 1610 unless ($gs) {
ce2a0f2f
EW
1611 my $ref_id = $self->{ref_id};
1612 $ref_id =~ s/\@\d+$//;
1613 $ref_id .= "\@$r";
15710b6f
EW
1614 # just grow a tail if we're not unique enough :x
1615 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1616 print STDERR "Initializing parent: $ref_id\n";
d8115c51 1617 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
15710b6f
EW
1618 }
1619 my ($r0, $parent) = $gs->find_rev_before($r, 1);
91b03282 1620 if (!defined $r0 || !defined $parent) {
3ebe8df7 1621 $gs->fetch(0, $r);
15710b6f
EW
1622 ($r0, $parent) = $gs->last_rev_commit;
1623 }
ef70de96 1624 if (defined $r0 && defined $parent) {
15710b6f 1625 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
a2003abc 1626 $self->assert_index_clean($parent);
15710b6f
EW
1627 my $ed;
1628 if ($self->ra->can_do_switch) {
8b8fc068 1629 print STDERR "Following parent with do_switch\n";
15710b6f 1630 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1631 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1632 # at the moment), so we can't rely on it
1633 $self->{last_commit} = $parent;
1634 $ed = SVN::Git::Fetcher->new($self);
8a603774 1635 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
1636 $self->full_url, $ed)
1637 or die "SVN connection failed somewhere...\n";
1638 } else {
8b8fc068 1639 print STDERR "Following parent with do_update\n";
15710b6f 1640 $ed = SVN::Git::Fetcher->new($self);
8a603774 1641 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
1642 or die "SVN connection failed somewhere...\n";
1643 }
f7c3fc4a 1644 print STDERR "Successfully followed parent\n";
15710b6f
EW
1645 return $self->make_log_entry($rev, [$parent], $ed);
1646 }
15710b6f
EW
1647 return undef;
1648}
1649
9b981fc6 1650sub do_fetch {
706587fc 1651 my ($self, $paths, $rev) = @_;
15710b6f 1652 my $ed;
9b981fc6 1653 my ($last_rev, @parents);
b9dffd8c
EW
1654 if (my $lc = $self->last_commit) {
1655 # we can have a branch that was deleted, then re-added
1656 # under the same name but copied from another path, in
1657 # which case we'll have multiple parents (we don't
1658 # want to break the original ref, nor lose copypath info):
1659 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1660 push @{$log_entry->{parents}}, $lc;
1661 return $log_entry;
1662 }
15710b6f 1663 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1664 $last_rev = $self->{last_rev};
b9dffd8c
EW
1665 $ed->{c} = $lc;
1666 @parents = ($lc);
9b981fc6
EW
1667 } else {
1668 $last_rev = $rev;
15710b6f
EW
1669 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1670 return $log_entry;
1671 }
1672 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1673 }
8a603774 1674 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
1675 die "SVN connection failed somewhere...\n";
1676 }
1677 $self->make_log_entry($rev, \@parents, $ed);
1678}
1679
97f6987a
EW
1680sub get_untracked {
1681 my ($self, $ed) = @_;
1682 my @out;
1683 my $h = $ed->{empty};
9b981fc6
EW
1684 foreach (sort keys %$h) {
1685 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1686 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1687 warn "W: $act: $_\n";
1688 }
1689 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1690 $h = $ed->{$t} or next;
9b981fc6
EW
1691 foreach my $path (sort keys %$h) {
1692 my $ppath = $path eq '' ? '.' : $path;
1693 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1694 next if $SKIP_PROP{$prop};
9b981fc6 1695 my $v = $h->{$path}->{$prop};
97f6987a
EW
1696 my $t_ppath_prop = "$t: " .
1697 uri_encode($ppath) . ' ' .
1698 uri_encode($prop);
9b981fc6 1699 if (defined $v) {
97f6987a
EW
1700 push @out, " +$t_ppath_prop " .
1701 uri_encode($v);
9b981fc6 1702 } else {
97f6987a 1703 push @out, " -$t_ppath_prop";
9b981fc6
EW
1704 }
1705 }
1706 }
1707 }
1708 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1709 $h = $ed->{$t} or next;
9b981fc6
EW
1710 foreach my $parent (sort keys %$h) {
1711 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1712 push @out, " $t: " .
1713 uri_encode("$parent/$path");
9b981fc6
EW
1714 warn "W: $t: $parent/$path ",
1715 "Insufficient permissions?\n";
1716 }
1717 }
1718 }
97f6987a 1719 \@out;
9b981fc6
EW
1720}
1721
1c8443b0
EW
1722sub parse_svn_date {
1723 my $date = shift || return '+0000 1970-01-01 00:00:00';
1724 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1725 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1726 croak "Unable to parse date: $date\n";
1727 "+0000 $Y-$m-$d $H:$M:$S";
1728}
1729
1730sub check_author {
1731 my ($author) = @_;
1732 if (!defined $author || length $author == 0) {
1733 $author = '(no author)';
1734 }
1735 if (defined $::_authors && ! defined $::users{$author}) {
1736 die "Author: $author not defined in $::_authors file\n";
1737 }
1738 $author;
1739}
1740
9b981fc6 1741sub make_log_entry {
97f6987a
EW
1742 my ($self, $rev, $parents, $ed) = @_;
1743 my $untracked = $self->get_untracked($ed);
1744
9b981fc6 1745 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1746 print $un "r$rev\n" or croak $!;
1747 print $un $_, "\n" foreach @$untracked;
1748 my %log_entry = ( parents => $parents || [], revision => $rev,
1749 log => '');
fbcc1737 1750
8a49ee97 1751 my $headrev;
fbcc1737 1752 my $logged = delete $self->{logged_rev_props};
8a49ee97 1753 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
1754 my $rp = $self->ra->rev_proplist($rev);
1755 foreach (sort keys %$rp) {
1756 my $v = $rp->{$_};
1757 if (/^svn:(author|date|log)$/) {
1758 $log_entry{$1} = $v;
8a49ee97
EW
1759 } elsif ($_ eq 'svm:headrev') {
1760 $headrev = $v;
fbcc1737
EW
1761 } else {
1762 print $un " rev_prop: ", uri_encode($_), ' ',
1763 uri_encode($v), "\n";
1764 }
9b981fc6 1765 }
fbcc1737
EW
1766 } else {
1767 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
1768 }
1769 close $un or croak $!;
97f6987a 1770
9b981fc6 1771 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 1772 $log_entry{log} .= "\n";
db03cd24
EW
1773 my $author = $log_entry{author} = check_author($log_entry{author});
1774 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
1775 : ($author, undef);
91b03282 1776 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
1777 if ($self->rewrite_root) {
1778 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
1779 "options set!\n";
1780 }
8a49ee97
EW
1781 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
1782 if ($uuid ne $self->{svm}->{uuid}) {
1783 die "UUID mismatch on SVM path:\n",
1784 "expected: $self->{svm}->{uuid}\n",
1785 " got: $uuid\n";
1786 }
1787 my $full_url = $self->{svm}->{source};
1788 $full_url .= "/$self->{path}" if length $self->{path};
1789 $log_entry{metadata} = "$full_url\@$r $uuid";
1790 $log_entry{svm_revision} = $r;
db03cd24 1791 $email ||= "$author\@$uuid"
62e349d2
EW
1792 } elsif ($self->use_svnsync_props) {
1793 my $full_url = $self->svnsync->{url};
1794 $full_url .= "/$self->{path}" if length $self->{path};
1795 my $uuid = $self->svnsync->{uuid};
1796 $log_entry{metadata} = "$full_url\@$rev $uuid";
1797 $email ||= "$author\@$uuid"
8a49ee97 1798 } else {
aea736cc 1799 $log_entry{metadata} = $self->metadata_url. "\@$rev " .
26a62d57 1800 $self->ra->get_uuid;
db03cd24 1801 $email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 1802 }
db03cd24
EW
1803 $log_entry{name} = $name;
1804 $log_entry{email} = $email;
9b981fc6
EW
1805 \%log_entry;
1806}
1807
1808sub fetch {
3ebe8df7 1809 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1810 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1811 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 1812 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
1813}
1814
1815sub set_tree_cb {
1816 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
1817 $self->{inject_parents} = { $rev => $tree };
1818 $self->fetch(undef, undef);
9b981fc6
EW
1819}
1820
1821sub set_tree {
1822 my ($self, $tree) = (shift, shift);
1ce255dc 1823 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1824 unless ($self->{last_rev}) {
1825 fatal("Must have an existing revision to commit\n");
1826 }
61395354
EW
1827 my %ed_opts = ( r => $self->{last_rev},
1828 log => $log_entry->{log},
1829 ra => $self->ra,
1830 tree_a => $self->{last_commit},
1831 tree_b => $tree,
1832 editor_cb => sub {
1833 $self->set_tree_cb($log_entry, $tree, @_) },
1834 svn_path => $self->{path} );
1835 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1836 print "No changes\nr$self->{last_rev} = $tree\n";
1837 }
9b981fc6
EW
1838}
1839
f0ecca10
EW
1840sub rebuild {
1841 my ($self) = @_;
26a62d57 1842 my $db_path = $self->db_path;
d6d3346b
EW
1843 return if (-e $db_path && ! -z $db_path);
1844 return unless ::verify_ref($self->refname.'^0');
26a62d57
EW
1845 if (-f $self->{db_root}) {
1846 rename $self->{db_root}, $db_path or die
1847 "rename $self->{db_root} => $db_path failed: $!\n";
1848 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
1849 symlink $base, $self->{db_root} or die
1850 "symlink $base => $self->{db_root} failed: $!\n";
1851 return;
1852 }
1853 print "Rebuilding $db_path ...\n";
f0ecca10
EW
1854 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1855 my $latest;
1856 my $full_url = $self->full_url;
1857 my $svn_uuid;
1858 while (<$rev_list>) {
1859 chomp;
1860 my $c = $_;
1861 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1862 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1863
1864 # ignore merges (from set-tree)
1865 next if (!defined $rev || !$uuid);
1866
1867 # if we merged or otherwise started elsewhere, this is
1868 # how we break out of it
1869 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1870 ($full_url && $url && ($url ne $full_url))) {
1871 next;
1872 }
1873 $latest ||= $rev;
1874 $svn_uuid ||= $uuid;
1875
1876 $self->rev_db_set($rev, $c);
1877 print "r$rev = $c\n";
1878 }
1879 command_close_pipe($rev_list, $ctx);
26a62d57 1880 print "Done rebuilding $db_path\n";
f0ecca10
EW
1881}
1882
9b981fc6
EW
1883# rev_db:
1884# Tie::File seems to be prone to offset errors if revisions get sparse,
1885# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1886# one of my favorite modules is out :< Next up would be one of the DBM
1887# modules, but I'm not sure which is most portable... So I'll just
1888# go with something that's plain-text, but still capable of
1889# being randomly accessed. So here's my ultra-simple fixed-width
1890# database. All records are 40 characters + "\n", so it's easy to seek
1891# to a revision: (41 * rev) is the byte offset.
1892# A record of 40 0s denotes an empty revision.
1893# And yes, it's still pretty fast (faster than Tie::File).
97ae0911 1894# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 1895
26a62d57
EW
1896sub _rev_db_set {
1897 my ($fh, $rev, $commit) = @_;
1898 my $offset = $rev * 41;
1899 # assume that append is the common case:
1900 seek $fh, 0, 2 or croak $!;
1901 my $pos = tell $fh;
1902 if ($pos < $offset) {
1903 for (1 .. (($offset - $pos) / 41)) {
1904 print $fh (('0' x 40),"\n") or croak $!;
1905 }
1906 }
1907 seek $fh, $offset, 0 or croak $!;
1908 print $fh $commit,"\n" or croak $!;
1909}
1910
1911sub mkfile {
1912 my ($path) = @_;
1913 unless (-e $path) {
1914 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
1915 mkpath([$dir]) unless -d $dir;
1916 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
1917 close $fh or die "Couldn't close (create) $path: $!\n";
1918 }
1919}
1920
9b981fc6 1921sub rev_db_set {
26a62d57
EW
1922 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
1923 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
1924 my $db = $self->db_path($uuid);
1925 my $db_lock = "$db.lock";
373274f9
EW
1926 my $sig;
1927 if ($update_ref) {
1928 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1929 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1930 }
26a62d57
EW
1931 mkfile($db);
1932
373274f9 1933 $LOCKFILES{$db_lock} = 1;
97ae0911 1934 my $sync;
97ae0911
EW
1935 # both of these options make our .rev_db file very, very important
1936 # and we can't afford to lose it because rebuild() won't work
1937 if ($self->use_svm_props || $self->no_metadata) {
1938 $sync = 1;
373274f9 1939 copy($db, $db_lock) or die "rev_db_set(@_): ",
26a62d57 1940 "Failed to copy: ",
373274f9
EW
1941 "$db => $db_lock ($!)\n";
1942 } else {
1943 rename $db, $db_lock or die "rev_db_set(@_): ",
26a62d57 1944 "Failed to rename: ",
373274f9
EW
1945 "$db => $db_lock ($!)\n";
1946 }
26a62d57
EW
1947 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
1948 _rev_db_set($fh, $rev, $commit);
97ae0911
EW
1949 if ($sync) {
1950 $fh->flush or die "Couldn't flush $db_lock: $!\n";
1951 $fh->sync or die "Couldn't sync $db_lock: $!\n";
1952 }
9b981fc6 1953 close $fh or croak $!;
373274f9 1954 if ($update_ref) {
1e889ef3 1955 $_head = $self;
373274f9
EW
1956 command_noisy('update-ref', '-m', "r$rev",
1957 $self->refname, $commit);
1958 }
1959 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1960 "$db_lock => $db ($!)\n";
1961 delete $LOCKFILES{$db_lock};
1962 if ($update_ref) {
1963 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1964 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1965 kill $sig, $$ if defined $sig;
1966 }
9b981fc6
EW
1967}
1968
9c93fee5
EW
1969sub rev_db_max {
1970 my ($self) = @_;
d6d3346b 1971 $self->rebuild;
26a62d57
EW
1972 my $db_path = $self->db_path;
1973 my @stat = stat $db_path or return 0;
1974 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
9c93fee5
EW
1975 my $max = $stat[7] / 41;
1976 (($max > 0) ? $max - 1 : 0);
1977}
1978
9b981fc6 1979sub rev_db_get {
26a62d57 1980 my ($self, $rev, $uuid) = @_;
9b981fc6
EW
1981 my $ret;
1982 my $offset = $rev * 41;
26a62d57
EW
1983 my $db_path = $self->db_path($uuid);
1984 return undef unless -e $db_path;
1985 open my $fh, '<', $db_path or croak $!;
ce4b4af7
EW
1986 if (sysseek($fh, $offset, 0) == $offset) {
1987 my $read = sysread($fh, $ret, 40);
1988 $ret = undef if ($read != 40 || $ret eq ('0'x40));
9b981fc6
EW
1989 }
1990 close $fh or croak $!;
1991 $ret;
1992}
1993
15710b6f
EW
1994sub find_rev_before {
1995 my ($self, $rev, $eq_ok) = @_;
1996 --$rev unless $eq_ok;
1997 while ($rev > 0) {
1998 if (my $c = $self->rev_db_get($rev)) {
1999 return ($rev, $c);
2000 }
2001 --$rev;
2002 }
2003 return (undef, undef);
2004}
2005
9b981fc6 2006sub _new {
706587fc
EW
2007 my ($class, $repo_id, $ref_id, $path) = @_;
2008 unless (defined $repo_id && length $repo_id) {
2009 $repo_id = $Git::SVN::default_repo_id;
2010 }
2011 unless (defined $ref_id && length $ref_id) {
8b8fc068 2012 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
2013 }
2014 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2015 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2016 $_[3] = $path = '' unless (defined $path);
b4d57e5e 2017 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
2018 bless {
2019 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 2020 path => $path, config => "$ENV{GIT_DIR}/svn/config",
26a62d57
EW
2021 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2022}
2023
2024sub db_path {
2025 my ($self, $uuid) = @_;
2026 $uuid ||= $self->ra_uuid;
2027 "$self->{db_root}.$uuid";
9b981fc6
EW
2028}
2029
1c8443b0
EW
2030sub uri_encode {
2031 my ($f) = @_;
2032 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2033 $f
2034}
9b981fc6 2035
d976acfd
EW
2036package Git::SVN::Prompt;
2037use strict;
2038use warnings;
2039require SVN::Core;
2040use vars qw/$_no_auth_cache $_username/;
2041
2042sub simple {
30d055aa
EW
2043 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2044 $may_save = undef if $_no_auth_cache;
2045 $default_username = $_username if defined $_username;
2046 if (defined $default_username && length $default_username) {
2047 if (defined $realm && length $realm) {
6f729591
EW
2048 print STDERR "Authentication realm: $realm\n";
2049 STDERR->flush;
30d055aa
EW
2050 }
2051 $cred->username($default_username);
2052 } else {
d976acfd 2053 username($cred, $realm, $may_save, $pool);
30d055aa
EW
2054 }
2055 $cred->password(_read_password("Password for '" .
2056 $cred->username . "': ", $realm));
2057 $cred->may_save($may_save);
2058 $SVN::_Core::SVN_NO_ERROR;
2059}
2060
d976acfd 2061sub ssl_server_trust {
30d055aa
EW
2062 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2063 $may_save = undef if $_no_auth_cache;
6f729591 2064 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 2065 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 2066 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
2067 "authority. Use the\n",
2068 " fingerprint to validate the certificate manually!\n";
2069 }
2070 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 2071 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
2072 }
2073 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 2074 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
2075 }
2076 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 2077 print STDERR " - The certificate has expired.\n";
30d055aa
EW
2078 }
2079 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 2080 print STDERR " - The certificate has an unknown error.\n";
30d055aa 2081 }
6f729591
EW
2082 printf STDERR
2083 "Certificate information:\n".
30d055aa
EW
2084 " - Hostname: %s\n".
2085 " - Valid: from %s until %s\n".
2086 " - Issuer: %s\n".
2087 " - Fingerprint: %s\n",
2088 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 2089 issuer_dname fingerprint);
30d055aa
EW
2090 my $choice;
2091prompt:
6f729591 2092 print STDERR $may_save ?
30d055aa
EW
2093 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2094 "(R)eject or accept (t)emporarily? ";
6f729591 2095 STDERR->flush;
30d055aa
EW
2096 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2097 if ($choice =~ /^t$/i) {
2098 $cred->may_save(undef);
2099 } elsif ($choice =~ /^r$/i) {
2100 return -1;
2101 } elsif ($may_save && $choice =~ /^p$/i) {
2102 $cred->may_save($may_save);
2103 } else {
2104 goto prompt;
2105 }
2106 $cred->accepted_failures($failures);
2107 $SVN::_Core::SVN_NO_ERROR;
2108}
2109
d976acfd 2110sub ssl_client_cert {
30d055aa
EW
2111 my ($cred, $realm, $may_save, $pool) = @_;
2112 $may_save = undef if $_no_auth_cache;
6f729591
EW
2113 print STDERR "Client certificate filename: ";
2114 STDERR->flush;
30d055aa
EW
2115 chomp(my $filename = <STDIN>);
2116 $cred->cert_file($filename);
2117 $cred->may_save($may_save);
2118 $SVN::_Core::SVN_NO_ERROR;
2119}
2120
d976acfd 2121sub ssl_client_cert_pw {
30d055aa
EW
2122 my ($cred, $realm, $may_save, $pool) = @_;
2123 $may_save = undef if $_no_auth_cache;
2124 $cred->password(_read_password("Password: ", $realm));
2125 $cred->may_save($may_save);
2126 $SVN::_Core::SVN_NO_ERROR;
2127}
2128
d976acfd 2129sub username {
30d055aa
EW
2130 my ($cred, $realm, $may_save, $pool) = @_;
2131 $may_save = undef if $_no_auth_cache;
2132 if (defined $realm && length $realm) {
6f729591 2133 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
2134 }
2135 my $username;
2136 if (defined $_username) {
2137 $username = $_username;
2138 } else {
6f729591
EW
2139 print STDERR "Username: ";
2140 STDERR->flush;
30d055aa
EW
2141 chomp($username = <STDIN>);
2142 }
2143 $cred->username($username);
2144 $cred->may_save($may_save);
2145 $SVN::_Core::SVN_NO_ERROR;
2146}
2147
2148sub _read_password {
2149 my ($prompt, $realm) = @_;
6f729591
EW
2150 print STDERR $prompt;
2151 STDERR->flush;
30d055aa
EW
2152 require Term::ReadKey;
2153 Term::ReadKey::ReadMode('noecho');
2154 my $password = '';
2155 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2156 last if $key =~ /[\012\015]/; # \n\r
2157 $password .= $key;
2158 }
2159 Term::ReadKey::ReadMode('restore');
6f729591
EW
2160 print STDERR "\n";
2161 STDERR->flush;
30d055aa
EW
2162 $password;
2163}
2164
d976acfd
EW
2165package main;
2166
b9c85187
EW
2167{
2168 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
2169 $SVN::Node::dir.$SVN::Node::unknown.
2170 $SVN::Node::none.$SVN::Node::file.
2171 $SVN::Node::dir.$SVN::Node::unknown.
2172 $SVN::Auth::SSL::CNMISMATCH.
2173 $SVN::Auth::SSL::NOTYETVALID.
2174 $SVN::Auth::SSL::EXPIRED.
2175 $SVN::Auth::SSL::UNKNOWNCA.
2176 $SVN::Auth::SSL::OTHER;
2177}
2178
27a1a801
EW
2179package SVN::Git::Fetcher;
2180use vars qw/@ISA/;
2181use strict;
2182use warnings;
2183use Carp qw/croak/;
2184use IO::File qw//;
90c1b15d 2185use Digest::MD5;
27a1a801
EW
2186
2187# file baton members: path, mode_a, mode_b, pool, fh, blob, base
2188sub new {
2189 my ($class, $git_svn) = @_;
2190 my $self = SVN::Delta::Editor->new;
2191 bless $self, $class;
1c8443b0 2192 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
2193 $self->{empty} = {};
2194 $self->{dir_prop} = {};
2195 $self->{file_prop} = {};
2196 $self->{absent_dir} = {};
2197 $self->{absent_file} = {};
ef3cfaad 2198 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
2199 $self;
2200}
2201
8b8fc068
EW
2202sub set_path_strip {
2203 my ($self, $path) = @_;
4e9f6cc7 2204 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
2205}
2206
d2a9a87b
EW
2207sub open_root {
2208 { path => '' };
2209}
2210
2211sub open_directory {
2212 my ($self, $path, $pb, $rev) = @_;
2213 { path => $path };
2214}
2215
706587fc
EW
2216sub git_path {
2217 my ($self, $path) = @_;
2b27f6c8
EW
2218 if ($self->{path_strip}) {
2219 $path =~ s!$self->{path_strip}!! or
2220 die "Failed to strip path '$path' ($self->{path_strip})\n";
2221 }
706587fc
EW
2222 $path;
2223}
2224
27a1a801
EW
2225sub delete_entry {
2226 my ($self, $path, $rev, $pb) = @_;
4a87db0e 2227
706587fc 2228 my $gpath = $self->git_path($path);
8a603774
EW
2229 return undef if ($gpath eq '');
2230
4a87db0e 2231 # remove entire directories.
706587fc 2232 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
2233 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2234 -r --name-only -z/,
706587fc 2235 $self->{c}, '--', $gpath);
4a87db0e
EW
2236 local $/ = "\0";
2237 while (<$ls>) {
ef3cfaad
EW
2238 chomp;
2239 $self->{gii}->remove($_);
9e3cdbd4 2240 print "\tD\t$_\n" unless $::_q;
4a87db0e 2241 }
9e3cdbd4 2242 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
2243 command_close_pipe($ls, $ctx);
2244 $self->{empty}->{$path} = 0
2245 } else {
ef3cfaad 2246 $self->{gii}->remove($gpath);
9e3cdbd4 2247 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 2248 }
27a1a801
EW
2249 undef;
2250}
2251
2252sub open_file {
2253 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
2254 my $gpath = $self->git_path($path);
2255 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 2256 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
2257 unless (defined $mode && defined $blob) {
2258 die "$path was not found in commit $self->{c} (r$rev)\n";
2259 }
27a1a801 2260 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 2261 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
2262}
2263
2264sub add_file {
2265 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
2266 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2267 delete $self->{empty}->{$dir};
27a1a801 2268 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 2269 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
2270}
2271
d2a9a87b
EW
2272sub add_directory {
2273 my ($self, $path, $cp_path, $cp_rev) = @_;
2274 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2275 delete $self->{empty}->{$dir};
2276 $self->{empty}->{$path} = 1;
2277 { path => $path };
2278}
2279
2280sub change_dir_prop {
2281 my ($self, $db, $prop, $value) = @_;
2282 $self->{dir_prop}->{$db->{path}} ||= {};
2283 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2284 undef;
2285}
2286
2287sub absent_directory {
2288 my ($self, $path, $pb) = @_;
2289 $self->{absent_dir}->{$pb->{path}} ||= [];
2290 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2291 undef;
2292}
2293
2294sub absent_file {
2295 my ($self, $path, $pb) = @_;
2296 $self->{absent_file}->{$pb->{path}} ||= [];
2297 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2298 undef;
2299}
2300
27a1a801
EW
2301sub change_file_prop {
2302 my ($self, $fb, $prop, $value) = @_;
2303 if ($prop eq 'svn:executable') {
2304 if ($fb->{mode_b} != 120000) {
2305 $fb->{mode_b} = defined $value ? 100755 : 100644;
2306 }
2307 } elsif ($prop eq 'svn:special') {
2308 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
2309 } else {
2310 $self->{file_prop}->{$fb->{path}} ||= {};
2311 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
2312 }
2313 undef;
2314}
2315
2316sub apply_textdelta {
2317 my ($self, $fb, $exp) = @_;
2318 my $fh = IO::File->new_tmpfile;
2319 $fh->autoflush(1);
2320 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2321 # (but $base does not,) so dup() it for reading in close_file
2322 open my $dup, '<&', $fh or croak $!;
2323 my $base = IO::File->new_tmpfile;
2324 $base->autoflush(1);
2325 if ($fb->{blob}) {
2326 defined (my $pid = fork) or croak $!;
2327 if (!$pid) {
2328 open STDOUT, '>&', $base or croak $!;
2329 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2330 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2331 }
2332 waitpid $pid, 0;
2333 croak $? if $?;
2334
2335 if (defined $exp) {
2336 seek $base, 0, 0 or croak $!;
2337 my $md5 = Digest::MD5->new;
2338 $md5->addfile($base);
2339 my $got = $md5->hexdigest;
2340 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2341 "expected: $exp\n",
2342 " got: $got\n" if ($got ne $exp);
2343 }
2344 }
2345 seek $base, 0, 0 or croak $!;
2346 $fb->{fh} = $dup;
2347 $fb->{base} = $base;
2348 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2349}
2350
2351sub close_file {
2352 my ($self, $fb, $exp) = @_;
2353 my $hash;
706587fc 2354 my $path = $self->git_path($fb->{path});
27a1a801
EW
2355 if (my $fh = $fb->{fh}) {
2356 seek($fh, 0, 0) or croak $!;
2357 my $md5 = Digest::MD5->new;
2358 $md5->addfile($fh);
2359 my $got = $md5->hexdigest;
2360 die "Checksum mismatch: $path\n",
2361 "expected: $exp\n got: $got\n" if ($got ne $exp);
2362 seek($fh, 0, 0) or croak $!;
2363 if ($fb->{mode_b} == 120000) {
2364 read($fh, my $buf, 5) == 5 or croak $!;
2365 $buf eq 'link ' or die "$path has mode 120000",
2366 "but is not a link\n";
2367 }
2368 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2369 if (!$pid) {
2370 open STDIN, '<&', $fh or croak $!;
2371 exec qw/git-hash-object -w --stdin/ or croak $!;
2372 }
2373 chomp($hash = do { local $/; <$out> });
2374 close $out or croak $!;
2375 close $fh or croak $!;
2376 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2377 close $fb->{base} or croak $!;
2378 } else {
2379 $hash = $fb->{blob} or die "no blob information\n";
2380 }
2381 $fb->{pool}->clear;
ef3cfaad 2382 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 2383 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
2384 undef;
2385}
2386
2387sub abort_edit {
2388 my $self = shift;
ef3cfaad
EW
2389 $self->{nr} = $self->{gii}->{nr};
2390 delete $self->{gii};
27a1a801
EW
2391 $self->SUPER::abort_edit(@_);
2392}
2393
2394sub close_edit {
2395 my $self = shift;
dad73c0b 2396 $self->{git_commit_ok} = 1;
ef3cfaad
EW
2397 $self->{nr} = $self->{gii}->{nr};
2398 delete $self->{gii};
27a1a801
EW
2399 $self->SUPER::close_edit(@_);
2400}
1a82e793 2401
a5e0cedc 2402package SVN::Git::Editor;
24e22aa8 2403use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
2404use strict;
2405use warnings;
2406use Carp qw/croak/;
2407use IO::File;
90c1b15d 2408use Digest::MD5;
a5e0cedc
EW
2409
2410sub new {
61395354
EW
2411 my ($class, $opts) = @_;
2412 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2413 die "$_ required!\n" unless (defined $opts->{$_});
2414 }
2415
2416 my $pool = SVN::Pool->new;
2417 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2418 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2419 $opts->{r}, $mods);
2420
2421 # $opts->{ra} functions should not be used after this:
2422 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2423 $opts->{editor_cb}, $pool);
2424 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 2425 bless $self, $class;
61395354
EW
2426 foreach (qw/svn_path r tree_a tree_b/) {
2427 $self->{$_} = $opts->{$_};
a5e0cedc 2428 }
61395354
EW
2429 $self->{url} = $opts->{ra}->{url};
2430 $self->{mods} = $mods;
2431 $self->{types} = $types;
2432 $self->{pool} = $pool;
a5e0cedc
EW
2433 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2434 $self->{rm} = { };
d3a840dc
EW
2435 $self->{path_prefix} = length $self->{svn_path} ?
2436 "$self->{svn_path}/" : '';
a5e0cedc
EW
2437 return $self;
2438}
2439
61395354
EW
2440sub generate_diff {
2441 my ($tree_a, $tree_b) = @_;
2442 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
2443 if ($_cp_similarity) {
2444 push @diff_tree, "-C$_cp_similarity";
61395354
EW
2445 } else {
2446 push @diff_tree, '-C';
2447 }
24e22aa8
EW
2448 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2449 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
2450 push @diff_tree, $tree_a, $tree_b;
2451 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2452 local $/ = "\0";
2453 my $state = 'meta';
2454 my @mods;
2455 while (<$diff_fh>) {
2456 chomp $_; # this gets rid of the trailing "\0"
2457 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2458 $::sha1\s($::sha1)\s
2459 ([MTCRAD])\d*$/xo) {
2460 push @mods, { mode_a => $1, mode_b => $2,
2461 sha1_b => $3, chg => $4 };
2462 if ($4 =~ /^(?:C|R)$/) {
2463 $state = 'file_a';
2464 } else {
2465 $state = 'file_b';
2466 }
2467 } elsif ($state eq 'file_a') {
2468 my $x = $mods[$#mods] or croak "Empty array\n";
2469 if ($x->{chg} !~ /^(?:C|R)$/) {
2470 croak "Error parsing $_, $x->{chg}\n";
2471 }
2472 $x->{file_a} = $_;
2473 $state = 'file_b';
2474 } elsif ($state eq 'file_b') {
2475 my $x = $mods[$#mods] or croak "Empty array\n";
2476 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2477 croak "Error parsing $_, $x->{chg}\n";
2478 }
2479 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2480 croak "Error parsing $_, $x->{chg}\n";
2481 }
2482 $x->{file_b} = $_;
2483 $state = 'meta';
2484 } else {
2485 croak "Error parsing $_\n";
2486 }
2487 }
2488 command_close_pipe($diff_fh, $ctx);
2489 \@mods;
2490}
2491
2492sub check_diff_paths {
2493 my ($ra, $pfx, $rev, $mods) = @_;
2494 my %types;
2495 $pfx .= '/' if length $pfx;
2496
2497 sub type_diff_paths {
2498 my ($ra, $types, $path, $rev) = @_;
2499 my @p = split m#/+#, $path;
2500 my $c = shift @p;
2501 unless (defined $types->{$c}) {
2502 $types->{$c} = $ra->check_path($c, $rev);
2503 }
2504 while (@p) {
2505 $c .= '/' . shift @p;
2506 next if defined $types->{$c};
2507 $types->{$c} = $ra->check_path($c, $rev);
2508 }
2509 }
2510
2511 foreach my $m (@$mods) {
2512 foreach my $f (qw/file_a file_b/) {
2513 next unless defined $m->{$f};
2514 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2515 if (length $pfx.$dir && ! defined $types{$dir}) {
2516 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2517 }
2518 }
2519 }
2520 \%types;
2521}
2522
a5e0cedc
EW
2523sub split_path {
2524 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2525}
2526
2527sub repo_path {
d3a840dc
EW
2528 my ($self, $path) = @_;
2529 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
2530}
2531
2532sub url_path {
2533 my ($self, $path) = @_;
6e8548cc 2534 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
2535}
2536
2537sub rmdirs {
61395354 2538 my ($self) = @_;
a5e0cedc
EW
2539 my $rm = $self->{rm};
2540 delete $rm->{''}; # we never delete the url we're tracking
2541 return unless %$rm;
2542
2543 foreach (keys %$rm) {
2544 my @d = split m#/#, $_;
2545 my $c = shift @d;
2546 $rm->{$c} = 1;
2547 while (@d) {
2548 $c .= '/' . shift @d;
2549 $rm->{$c} = 1;
2550 }
2551 }
2552 delete $rm->{$self->{svn_path}};
2553 delete $rm->{''}; # we never delete the url we're tracking
2554 return unless %$rm;
2555
61395354
EW
2556 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2557 $self->{tree_b});
a5e0cedc
EW
2558 local $/ = "\0";
2559 while (<$fh>) {
2560 chomp;
747fa12c 2561 my @dn = split m#/#, $_;
c07eee1f
EW
2562 while (pop @dn) {
2563 delete $rm->{join '/', @dn};
2564 }
2565 unless (%$rm) {
22600a25 2566 close $fh;
c07eee1f
EW
2567 return;
2568 }
a5e0cedc 2569 }
aef4e921 2570 command_close_pipe($fh, $ctx);
c07eee1f 2571
a5e0cedc
EW
2572 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2573 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2574 $self->close_directory($bat->{$d}, $p);
2575 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 2576 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
2577 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2578 delete $bat->{$d};
2579 }
2580}
2581
2582sub open_or_add_dir {
2583 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
2584 my $t = $self->{types}->{$full_path};
2585 if (!defined $t) {
2586 die "$full_path not known in r$self->{r} or we have a bug!\n";
2587 }
a5e0cedc
EW
2588 if ($t == $SVN::Node::none) {
2589 return $self->add_directory($full_path, $baton,
2590 undef, -1, $self->{pool});
2591 } elsif ($t == $SVN::Node::dir) {
2592 return $self->open_directory($full_path, $baton,
2593 $self->{r}, $self->{pool});
2594 }
2595 print STDERR "$full_path already exists in repository at ",
2596 "r$self->{r} and it is not a directory (",
2597 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2598 exit 1;
2599}
2600
2601sub ensure_path {
2602 my ($self, $path) = @_;
2603 my $bat = $self->{bat};
6e8548cc
EW
2604 my $repo_path = $self->repo_path($path);
2605 return $bat->{''} unless (length $repo_path);
2606 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
2607 my $c = shift @p;
2608 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2609 while (@p) {
2610 my $c0 = $c;
2611 $c .= '/' . shift @p;
2612 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2613 }
2614 return $bat->{$c};
2615}
2616
2617sub A {
44320b9e 2618 my ($self, $m) = @_;
a5e0cedc
EW
2619 my ($dir, $file) = split_path($m->{file_b});
2620 my $pbat = $self->ensure_path($dir);
2621 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2622 undef, -1);
44320b9e 2623 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2624 $self->chg_file($fbat, $m);
2625 $self->close_file($fbat,undef,$self->{pool});
2626}
2627
2628sub C {
44320b9e 2629 my ($self, $m) = @_;
a5e0cedc
EW
2630 my ($dir, $file) = split_path($m->{file_b});
2631 my $pbat = $self->ensure_path($dir);
2632 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2633 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2634 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2635 $self->chg_file($fbat, $m);
2636 $self->close_file($fbat,undef,$self->{pool});
2637}
2638
2639sub delete_entry {
2640 my ($self, $path, $pbat) = @_;
2641 my $rpath = $self->repo_path($path);
2642 my ($dir, $file) = split_path($rpath);
2643 $self->{rm}->{$dir} = 1;
2644 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2645}
2646
2647sub R {
44320b9e 2648 my ($self, $m) = @_;
a5e0cedc
EW
2649 my ($dir, $file) = split_path($m->{file_b});
2650 my $pbat = $self->ensure_path($dir);
2651 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2652 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2653 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2654 $self->chg_file($fbat, $m);
2655 $self->close_file($fbat,undef,$self->{pool});
2656
2657 ($dir, $file) = split_path($m->{file_a});
2658 $pbat = $self->ensure_path($dir);
2659 $self->delete_entry($m->{file_a}, $pbat);
2660}
2661
2662sub M {
44320b9e 2663 my ($self, $m) = @_;
a5e0cedc
EW
2664 my ($dir, $file) = split_path($m->{file_b});
2665 my $pbat = $self->ensure_path($dir);
2666 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2667 $pbat,$self->{r},$self->{pool});
44320b9e 2668 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2669 $self->chg_file($fbat, $m);
2670 $self->close_file($fbat,undef,$self->{pool});
2671}
2672
2673sub T { shift->M(@_) }
2674
2675sub change_file_prop {
2676 my ($self, $fbat, $pname, $pval) = @_;
2677 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2678}
2679
2680sub chg_file {
2681 my ($self, $fbat, $m) = @_;
2682 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2683 $self->change_file_prop($fbat,'svn:executable','*');
2684 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2685 $self->change_file_prop($fbat,'svn:executable',undef);
2686 }
2687 my $fh = IO::File->new_tmpfile or croak $!;
2688 if ($m->{mode_b} =~ /^120/) {
2689 print $fh 'link ' or croak $!;
2690 $self->change_file_prop($fbat,'svn:special','*');
2691 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2692 $self->change_file_prop($fbat,'svn:special',undef);
2693 }
2694 defined(my $pid = fork) or croak $!;
2695 if (!$pid) {
2696 open STDOUT, '>&', $fh or croak $!;
2697 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2698 }
2699 waitpid $pid, 0;
2700 croak $? if $?;
2701 $fh->flush == 0 or croak $!;
2702 seek $fh, 0, 0 or croak $!;
2703
2704 my $md5 = Digest::MD5->new;
2705 $md5->addfile($fh) or croak $!;
2706 seek $fh, 0, 0 or croak $!;
2707
2708 my $exp = $md5->hexdigest;
f7197dff
EW
2709 my $pool = SVN::Pool->new;
2710 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2711 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2712 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2713 $pool->clear;
a5e0cedc
EW
2714
2715 close $fh or croak $!;
2716}
2717
2718sub D {
44320b9e 2719 my ($self, $m) = @_;
a5e0cedc
EW
2720 my ($dir, $file) = split_path($m->{file_b});
2721 my $pbat = $self->ensure_path($dir);
44320b9e 2722 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2723 $self->delete_entry($m->{file_b}, $pbat);
2724}
2725
2726sub close_edit {
2727 my ($self) = @_;
2728 my ($p,$bat) = ($self->{pool}, $self->{bat});
2729 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2730 $self->close_directory($bat->{$_}, $p);
2731 }
2732 $self->SUPER::close_edit($p);
2733 $p->clear;
2734}
2735
2736sub abort_edit {
2737 my ($self) = @_;
2738 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2739}
2740
2741sub DESTROY {
2742 my $self = shift;
2743 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2744 $self->{pool}->clear;
2745}
2746
44320b9e
EW
2747# this drives the editor
2748sub apply_diff {
61395354
EW
2749 my ($self) = @_;
2750 my $mods = $self->{mods};
44320b9e 2751 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2752 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2753 my $f = $m->{chg};
2754 if (defined $o{$f}) {
2755 $self->$f($m);
2756 } else {
2757 fatal("Invalid change type: $f\n");
2758 }
2759 }
24e22aa8 2760 $self->rmdirs if $_rmdir;
6e8548cc 2761 if (@$mods == 0) {
44320b9e
EW
2762 $self->abort_edit;
2763 } else {
2764 $self->close_edit;
2765 }
6e8548cc 2766 return scalar @$mods;
44320b9e
EW
2767}
2768
d81bf827 2769package Git::SVN::Ra;
6af1db44 2770use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
2771use strict;
2772use warnings;
2773my ($can_do_switch);
5d3b7cd5 2774my $RA;
d81bf827
EW
2775
2776BEGIN {
2777 # enforce temporary pool usage for some simple functions
2778 my $e;
74a81227 2779 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
d81bf827
EW
2780 $e .= "sub $_ {
2781 my \$self = shift;
2782 my \$pool = SVN::Pool->new;
2783 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2784 \$pool->clear;
2785 wantarray ? \@ret : \$ret[0]; }\n";
2786 }
74a81227
EW
2787
2788 # get_dir needs $pool held in cache for dirents to work,
2789 # check_path is cacheable and rev_proplist is close enough
2790 # for our purposes.
2791 foreach (qw/check_path get_dir rev_proplist/) {
2792 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2793 my \$self = shift;
2794 my \$r = pop;
2795 my \$k = join(\"\\0\", \@_);
2796 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2797 return wantarray ? \@\$x : \$x->[0];
2798 }
2799 my \$pool = SVN::Pool->new;
2800 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2801 if (\$r != \$${_}_rev) {
2802 \%${_}_cache = ( pool => [] );
2803 \$${_}_rev = \$r;
2804 }
2805 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2806 push \@{\$${_}_cache{pool}}, \$pool;
2807 wantarray ? \@ret : \$ret[0]; }\n";
2808 }
2809 $e .= "\n1;";
2810 eval $e or die $@;
d81bf827
EW
2811}
2812
2813sub new {
2814 my ($class, $url) = @_;
f6f09876 2815 $url =~ s!/+$!!;
5d3b7cd5 2816 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 2817
d81bf827
EW
2818 SVN::_Core::svn_config_ensure($config_dir, undef);
2819 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2820 SVN::Client::get_simple_provider(),
2821 SVN::Client::get_ssl_server_trust_file_provider(),
2822 SVN::Client::get_simple_prompt_provider(
2823 \&Git::SVN::Prompt::simple, 2),
2824 SVN::Client::get_ssl_client_cert_prompt_provider(
2825 \&Git::SVN::Prompt::ssl_client_cert, 2),
2826 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2827 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2828 SVN::Client::get_username_provider(),
2829 SVN::Client::get_ssl_server_trust_prompt_provider(
2830 \&Git::SVN::Prompt::ssl_server_trust),
2831 SVN::Client::get_username_prompt_provider(
2832 \&Git::SVN::Prompt::username, 2),
2833 ]);
2834 my $config = SVN::Core::config_get_config($config_dir);
2835 my $self = SVN::Ra->new(url => $url, auth => $baton,
2836 config => $config,
2837 pool => SVN::Pool->new,
2838 auth_provider_callbacks => $callbacks);
2839 $self->{svn_path} = $url;
2840 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 2841 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5d3b7cd5 2842 $RA = bless $self, $class;
d81bf827
EW
2843}
2844
2845sub DESTROY {
5d3b7cd5 2846 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2847}
2848
d81bf827
EW
2849sub get_log {
2850 my ($self, @args) = @_;
2851 my $pool = SVN::Pool->new;
d81bf827
EW
2852 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2853 my $ret = $self->SUPER::get_log(@args, $pool);
2854 $pool->clear;
2855 $ret;
2856}
2857
2858sub get_commit_editor {
44320b9e 2859 my ($self, $log, $cb, $pool) = @_;
d81bf827 2860 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2861 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2862}
2863
d81bf827 2864sub gs_do_update {
8a603774
EW
2865 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2866 my $new = ($rev_a == $rev_b);
2867 my $path = $gs->{path};
2868
d81bf827 2869 my $pool = SVN::Pool->new;
8b8fc068 2870 $editor->set_path_strip($path);
2b27f6c8
EW
2871 my (@pc) = split m#/#, $path;
2872 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 2873 1, $editor, $pool);
d81bf827 2874 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
2875
2876 # Since we can't rely on svn_ra_reparent being available, we'll
2877 # just have to do some magic with set_path to make it so
2878 # we only want a partial path.
2879 my $sp = '';
2880 my $final = join('/', @pc);
2881 while (@pc) {
2882 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2883 $sp .= '/' if length $sp;
2884 $sp .= shift @pc;
2885 }
2886 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2887
2b27f6c8
EW
2888 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2889
d81bf827
EW
2890 $reporter->finish_report($pool);
2891 $pool->clear;
2892 $editor->{git_commit_ok};
2893}
2894
2b27f6c8
EW
2895# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2896# svn_ra_reparent didn't work before 1.4)
d81bf827 2897sub gs_do_switch {
8a603774
EW
2898 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2899 my $path = $gs->{path};
d81bf827 2900 my $pool = SVN::Pool->new;
2b27f6c8
EW
2901
2902 my $full_url = $self->{url};
2903 my $old_url = $full_url;
2904 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
2905 my ($ra, $reparented);
2906 if ($old_url ne $full_url) {
2907 if ($old_url !~ m#^svn(\+ssh)?://#) {
2908 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2909 $pool);
2910 $self->{url} = $full_url;
2911 $reparented = 1;
2912 } else {
2913 $ra = Git::SVN::Ra->new($full_url);
2914 }
2915 }
2916 $ra ||= $self;
8a603774 2917 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 2918 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 2919 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 2920 $reporter->finish_report($pool);
2b27f6c8 2921
5d3b7cd5
EW
2922 if ($reparented) {
2923 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2924 $self->{url} = $old_url;
2925 }
2b27f6c8 2926
d81bf827
EW
2927 $pool->clear;
2928 $editor->{git_commit_ok};
2929}
2930
0af9c9f9 2931sub gs_fetch_loop_common {
e518192f
EW
2932 my ($self, $base, $head, $gsv, $globs) = @_;
2933 return if ($base > $head);
6af1db44 2934 my $inc = $_log_window_size;
0af9c9f9 2935 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
d2ae1434 2936 my %common;
e518192f
EW
2937 my $common_max = scalar @$gsv;
2938
2939 foreach my $gs (@$gsv) {
d2ae1434
EW
2940 my @tmp = split m#/#, $gs->{path};
2941 my $p = '';
2942 foreach (@tmp) {
2943 $p .= length($p) ? "/$_" : $_;
2944 $common{$p} ||= 0;
2945 $common{$p}++;
2946 }
2947 }
e518192f
EW
2948 $globs ||= [];
2949 $common_max += scalar @$globs;
2950 foreach my $glob (@$globs) {
2951 my @tmp = split m#/#, $glob->{path}->{left};
2952 my $p = '';
2953 foreach (@tmp) {
2954 $p .= length($p) ? "/$_" : $_;
2955 $common{$p} ||= 0;
2956 $common{$p}++;
2957 }
2958 }
2959
d2ae1434
EW
2960 my $longest_path = '';
2961 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 2962 if ($common{$_} == $common_max) {
d2ae1434
EW
2963 $longest_path = $_;
2964 last;
2965 }
0af9c9f9
EW
2966 }
2967 while (1) {
d4eff2bd 2968 my %revs;
d2ae1434 2969 my $err;
f7c3fc4a 2970 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
2971 $SVN::Error::handler = sub {
2972 ($err) = @_;
2973 skip_unknown_revs($err);
2974 };
2975 sub _cb {
2976 my ($paths, $r, $author, $date, $log) = @_;
2977 [ dup_changed_paths($paths),
2978 { author => $author, date => $date, log => $log } ];
2979 }
2980 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2981 sub { $revs{$_[1]} = _cb(@_) });
2982 if ($err && $max >= $head) {
2983 print STDERR "Path '$longest_path' ",
2984 "was probably deleted:\n",
2985 $err->expanded_message,
2986 "\nWill attempt to follow ",
2987 "revisions r$min .. r$max ",
2988 "committed before the deletion\n";
2989 my $hi = $max;
2990 while (--$hi >= $min) {
2991 my $ok;
2992 $self->get_log([$longest_path], $min, $hi,
2993 0, 1, 1, sub {
2994 $ok ||= $_[1];
2995 $revs{$_[1]} = _cb(@_) });
2996 if ($ok) {
2997 print STDERR "r$min .. r$ok OK\n";
2998 last;
2999 }
3000 }
3001 }
d4eff2bd 3002 $SVN::Error::handler = $err_handler;
fbcc1737 3003
e518192f 3004 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 3005 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 3006 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
3007
3008 foreach my $gs ($self->match_globs(\%exists, $paths,
3009 $globs, $r)) {
fbcc1737
EW
3010 if ($gs->rev_db_max >= $r) {
3011 next;
3012 }
3013 next unless $gs->match_paths($paths, $r);
3014 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
3015 if (my $last_commit = $gs->last_commit) {
3016 $gs->assert_index_clean($last_commit);
3017 }
fbcc1737
EW
3018 my $log_entry = $gs->do_fetch($paths, $r);
3019 if ($log_entry) {
0af9c9f9
EW
3020 $gs->do_git_commit($log_entry);
3021 }
3022 }
e518192f 3023 foreach my $g (@$globs) {
93f2689c
EW
3024 my $k = "svn-remote.$g->{remote}." .
3025 "$g->{t}-maxRev";
3026 Git::SVN::tmp_config($k, $r);
e518192f 3027 }
0af9c9f9 3028 }
9c93fee5
EW
3029 # pre-fill the .rev_db since it'll eventually get filled in
3030 # with '0' x40 if something new gets committed
e518192f 3031 foreach my $gs (@$gsv) {
9c93fee5
EW
3032 next if defined $gs->rev_db_get($max);
3033 $gs->rev_db_set($max, 0 x40);
3034 }
c3560e53
EW
3035 foreach my $g (@$globs) {
3036 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3037 Git::SVN::tmp_config($k, $max);
3038 }
0af9c9f9
EW
3039 last if $max >= $head;
3040 $min = $max + 1;
3041 $max += $inc;
3042 $max = $head if ($max > $head);
3043 }
0af9c9f9
EW
3044}
3045
e518192f
EW
3046sub match_globs {
3047 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
3048
3049 sub get_dir_check {
3050 my ($self, $exists, $g, $r) = @_;
3051 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3052 return unless scalar @x == 3;
3053 my $dirents = $x[0];
3054 foreach my $de (keys %$dirents) {
3055 next if $dirents->{$de}->kind != $SVN::Node::dir;
3056 my $p = $g->{path}->full_path($de);
3057 next if $exists->{$p};
3058 next if (length $g->{path}->{right} &&
3059 ($self->check_path($p, $r) !=
3060 $SVN::Node::dir));
3061 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3062 $g->{ref}->full_path($de), 1);
3063 }
3064 }
e518192f 3065 foreach my $g (@$globs) {
74a81227
EW
3066 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3067 if ($path->{action} =~ /^[AR]$/) {
3068 get_dir_check($self, $exists, $g, $r);
3069 }
3070 }
e518192f 3071 foreach (keys %$paths) {
28710f74
EW
3072 if (/$g->{path}->{left_regex}/ &&
3073 !/$g->{path}->{regex}/) {
74a81227
EW
3074 next if $paths->{$_}->{action} !~ /^[AR]$/;
3075 get_dir_check($self, $exists, $g, $r);
3076 }
e518192f
EW
3077 next unless /$g->{path}->{regex}/;
3078 my $p = $1;
3079 my $pathname = $g->{path}->full_path($p);
3080 next if $exists->{$pathname};
3081 $exists->{$pathname} = Git::SVN->init(
3082 $self->{url}, $pathname, undef,
3083 $g->{ref}->full_path($p), 1);
3084 }
3085 my $c = '';
3086 foreach (split m#/#, $g->{path}->{left}) {
3087 $c .= "/$_";
3088 next unless ($paths->{$c} &&
74a81227
EW
3089 ($paths->{$c}->{action} =~ /^[AR]$/));
3090 get_dir_check($self, $exists, $g, $r);
e518192f
EW
3091 }
3092 }
3093 values %$exists;
3094}
3095
e6434f87
EW
3096sub minimize_url {
3097 my ($self) = @_;
3098 return $self->{url} if ($self->{url} eq $self->{repos_root});
3099 my $url = $self->{repos_root};
3100 my @components = split(m!/!, $self->{svn_path});
3101 my $c = '';
3102 do {
3103 $url .= "/$c" if length $c;
3104 eval { (ref $self)->new($url)->get_latest_revnum };
3105 } while ($@ && ($c = shift @components));
3106 $url;
3107}
3108
d81bf827
EW
3109sub can_do_switch {
3110 my $self = shift;
3111 unless (defined $can_do_switch) {
3112 my $pool = SVN::Pool->new;
3113 my $rep = eval {
3114 $self->do_switch(1, '', 0, $self->{url},
3115 SVN::Delta::Editor->new, $pool);
3116 };
3117 if ($@) {
3118 $can_do_switch = 0;
3119 } else {
3120 $rep->abort_report($pool);
3121 $can_do_switch = 1;
3122 }
3123 $pool->clear;
3124 }
3125 $can_do_switch;
3126}
3127
0af9c9f9
EW
3128sub skip_unknown_revs {
3129 my ($err) = @_;
3130 my $errno = $err->apr_err();
3131 # Maybe the branch we're tracking didn't
3132 # exist when the repo started, so it's
3133 # not an error if it doesn't, just continue
3134 #
3135 # Wonderfully consistent library, eh?
3136 # 160013 - svn:// and file://
3137 # 175002 - http(s)://
3138 # 175007 - http(s):// (this repo required authorization, too...)
3139 # More codes may be discovered later...
3140 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
6af1db44
EW
3141 warn "W: Ignoring error from SVN, path probably ",
3142 "does not exist: ($errno): ",
3143 $err->expanded_message,"\n";
0af9c9f9
EW
3144 return;
3145 }
3146 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3147}
3148
3149# svn_log_changed_path_t objects passed to get_log are likely to be
3150# overwritten even if only the refs are copied to an external variable,
3151# so we should dup the structures in their entirety. Using an externally
3152# passed pool (instead of our temporary and quickly cleared pool in
3153# Git::SVN::Ra) does not help matters at all...
3154sub dup_changed_paths {
3155 my ($paths) = @_;
3156 return undef unless $paths;
3157 my %ret;
3158 foreach my $p (keys %$paths) {
3159 my $i = $paths->{$p};
3160 my %s = map { $_ => $i->$_ }
3161 qw/copyfrom_path copyfrom_rev action/;
3162 $ret{$p} = \%s;
3163 }
3164 \%ret;
3165}
3166
f8c9d1d2
EW
3167package Git::SVN::Log;
3168use strict;
3169use warnings;
3170use POSIX qw/strftime/;
3171use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3172 %rusers $show_commit $incremental/;
3173my $l_fmt;
3174
3175sub cmt_showable {
3176 my ($c) = @_;
3177 return 1 if defined $c->{r};
3178 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3179 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
44320b9e
EW
3180 my @log = command(qw/cat-file commit/, $c->{c});
3181 shift @log while ($log[0] ne "\n");
3182 shift @log;
3183 @{$c->{l}} = grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
3184
3185 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 3186 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
3187 }
3188 return defined $c->{r};
3189}
3190
3191sub log_use_color {
3192 return 1 if $color;
3193 my ($dc, $dcvar);
3194 $dcvar = 'color.diff';
3195 $dc = `git-config --get $dcvar`;
3196 if ($dc eq '') {
3197 # nothing at all; fallback to "diff.color"
3198 $dcvar = 'diff.color';
3199 $dc = `git-config --get $dcvar`;
3200 }
3201 chomp($dc);
3202 if ($dc eq 'auto') {
3203 my $pc;
3204 $pc = `git-config --get color.pager`;
3205 if ($pc eq '') {
3206 # does not have it -- fallback to pager.color
3207 $pc = `git-config --bool --get pager.color`;
3208 }
3209 else {
3210 $pc = `git-config --bool --get color.pager`;
3211 if ($?) {
3212 $pc = 'false';
3213 }
3214 }
3215 chomp($pc);
3216 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3217 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3218 }
3219 return 0;
3220 }
3221 return 0 if $dc eq 'never';
3222 return 1 if $dc eq 'always';
3223 chomp($dc = `git-config --bool --get $dcvar`);
3224 return ($dc eq 'true');
3225}
3226
3227sub git_svn_log_cmd {
3bc718ba
EW
3228 my ($r_min, $r_max, @args) = @_;
3229 my $head = 'HEAD';
3230 foreach my $x (@args) {
3231 last if $x eq '--';
3232 next unless ::verify_ref("$x^0");
3233 $head = $x;
3234 last;
3235 }
3236
905f8b7d 3237 my $url = (::working_head_info($head))[0];
3bc718ba 3238 my $gs = Git::SVN->find_by_url($url) || Git::SVN->_new;
f8c9d1d2
EW
3239 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3240 $gs->refname);
3241 push @cmd, '-r' unless $non_recursive;
3242 push @cmd, qw/--raw --name-status/ if $verbose;
3243 push @cmd, '--color' if log_use_color();
3244 return @cmd unless defined $r_max;
3245 if ($r_max == $r_min) {
3246 push @cmd, '--max-count=1';
3247 if (my $c = $gs->rev_db_get($r_max)) {
3248 push @cmd, $c;
3249 }
3250 } else {
3251 my ($c_min, $c_max);
3252 $c_max = $gs->rev_db_get($r_max);
3253 $c_min = $gs->rev_db_get($r_min);
3254 if (defined $c_min && defined $c_max) {
3255 if ($r_max > $r_max) {
3256 push @cmd, "$c_min..$c_max";
3257 } else {
3258 push @cmd, "$c_max..$c_min";
3259 }
3260 } elsif ($r_max > $r_min) {
3261 push @cmd, $c_max;
3262 } else {
3263 push @cmd, $c_min;
3264 }
3265 }
3266 return @cmd;
3267}
3268
3269# adapted from pager.c
3270sub config_pager {
3271 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3272 if (!defined $pager) {
3273 $pager = 'less';
3274 } elsif (length $pager == 0 || $pager eq 'cat') {
3275 $pager = undef;
3276 }
3277}
3278
3279sub run_pager {
3280 return unless -t *STDOUT;
3281 pipe my $rfd, my $wfd or return;
3282 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
3283 if (!$pid) {
3284 open STDOUT, '>&', $wfd or
3285 ::fatal "Can't redirect to stdout: $!\n";
3286 return;
3287 }
3288 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
3289 $ENV{LESS} ||= 'FRSX';
3290 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
3291}
3292
21819a37
EW
3293sub tz_to_s_offset {
3294 my ($tz) = @_;
3295 $tz =~ s/(\d\d)$//;
3296 return ($1 * 60) + ($tz * 3600);
3297}
3298
f8c9d1d2
EW
3299sub get_author_info {
3300 my ($dest, $author, $t, $tz) = @_;
3301 $author =~ s/(?:^\s*|\s*$)//g;
3302 $dest->{a_raw} = $author;
3303 my $au;
1c8443b0 3304 if ($::_authors) {
f8c9d1d2
EW
3305 $au = $rusers{$author} || undef;
3306 }
3307 if (!$au) {
3308 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3309 }
3310 $dest->{t} = $t;
3311 $dest->{tz} = $tz;
3312 $dest->{a} = $au;
3313 # Date::Parse isn't in the standard Perl distro :(
3314 if ($tz =~ s/^\+//) {
21819a37 3315 $t += tz_to_s_offset($tz);
f8c9d1d2 3316 } elsif ($tz =~ s/^\-//) {
21819a37 3317 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
3318 }
3319 $dest->{t_utc} = $t;
3320}
3321
3322sub process_commit {
3323 my ($c, $r_min, $r_max, $defer) = @_;
3324 if (defined $r_min && defined $r_max) {
3325 if ($r_min == $c->{r} && $r_min == $r_max) {
3326 show_commit($c);
3327 return 0;
3328 }
3329 return 1 if $r_min == $r_max;
3330 if ($r_min < $r_max) {
3331 # we need to reverse the print order
3332 return 0 if (defined $limit && --$limit < 0);
3333 push @$defer, $c;
3334 return 1;
3335 }
3336 if ($r_min != $r_max) {
3337 return 1 if ($r_min < $c->{r});
3338 return 1 if ($r_max > $c->{r});
3339 }
3340 }
3341 return 0 if (defined $limit && --$limit < 0);
3342 show_commit($c);
3343 return 1;
3344}
3345
3346sub show_commit {
3347 my $c = shift;
3348 if ($oneline) {
3349 my $x = "\n";
3350 if (my $l = $c->{l}) {
3351 while ($l->[0] =~ /^\s*$/) { shift @$l }
3352 $x = $l->[0];
3353 }
3354 $l_fmt ||= 'A' . length($c->{r});
3355 print 'r',pack($l_fmt, $c->{r}),' | ';
3356 print "$c->{c} | " if $show_commit;
3357 print $x;
3358 } else {
3359 show_commit_normal($c);
3360 }
3361}
3362
3363sub show_commit_changed_paths {
3364 my ($c) = @_;
3365 return unless $c->{changed};
3366 print "Changed paths:\n", @{$c->{changed}};
3367}
3368
3369sub show_commit_normal {
3370 my ($c) = @_;
3371 print '-' x72, "\nr$c->{r} | ";
3372 print "$c->{c} | " if $show_commit;
3373 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3374 localtime($c->{t_utc})), ' | ';
3375 my $nr_line = 0;
3376
3377 if (my $l = $c->{l}) {
3378 while ($l->[$#$l] eq "\n" && $#$l > 0
3379 && $l->[($#$l - 1)] eq "\n") {
3380 pop @$l;
3381 }
3382 $nr_line = scalar @$l;
3383 if (!$nr_line) {
3384 print "1 line\n\n\n";
3385 } else {
3386 if ($nr_line == 1) {
3387 $nr_line = '1 line';
3388 } else {
3389 $nr_line .= ' lines';
3390 }
3391 print $nr_line, "\n";
3392 show_commit_changed_paths($c);
3393 print "\n";
3394 print $_ foreach @$l;
3395 }
3396 } else {
3397 print "1 line\n";
3398 show_commit_changed_paths($c);
3399 print "\n";
3400
3401 }
488a63ec 3402 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
3403 if ($c->{$x}) {
3404 print "\n";
3405 print $_ foreach @{$c->{$x}}
3406 }
3407 }
3408}
3409
3410sub cmd_show_log {
3411 my (@args) = @_;
3412 my ($r_min, $r_max);
3413 my $r_last = -1; # prevent dupes
3414 if (defined $TZ) {
3415 $ENV{TZ} = $TZ;
3416 } else {
3417 delete $ENV{TZ};
3418 }
3419 if (defined $::_revision) {
3420 if ($::_revision =~ /^(\d+):(\d+)$/) {
3421 ($r_min, $r_max) = ($1, $2);
3422 } elsif ($::_revision =~ /^\d+$/) {
3423 $r_min = $r_max = $::_revision;
3424 } else {
3425 ::fatal "-r$::_revision is not supported, use ",
3426 "standard \'git log\' arguments instead\n";
3427 }
3428 }
3429
3430 config_pager();
3bc718ba 3431 @args = (git_svn_log_cmd($r_min, $r_max, @args), @args);
f8c9d1d2
EW
3432 my $log = command_output_pipe(@args);
3433 run_pager();
488a63ec 3434 my (@k, $c, $d, $stat);
f8c9d1d2
EW
3435 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
3436 while (<$log>) {
3437 if (/^${esc_color}commit ($::sha1_short)/o) {
3438 my $cmt = $1;
3439 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
3440 $r_last = $c->{r};
3441 process_commit($c, $r_min, $r_max, \@k) or
3442 goto out;
3443 }
3444 $d = undef;
3445 $c = { c => $cmt };
3446 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
3447 get_author_info($c, $1, $2, $3);
3448 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
3449 # ignore
3450 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
3451 push @{$c->{raw}}, $_;
3452 } elsif (/^${esc_color}[ACRMDT]\t/) {
3453 # we could add $SVN->{svn_path} here, but that requires
3454 # remote access at the moment (repo_path_split)...
3455 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
3456 push @{$c->{changed}}, $_;
3457 } elsif (/^${esc_color}diff /o) {
3458 $d = 1;
3459 push @{$c->{diff}}, $_;
3460 } elsif ($d) {
3461 push @{$c->{diff}}, $_;
488a63ec
EW
3462 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
3463 $esc_color*[\+\-]*$esc_color$/x) {
3464 $stat = 1;
3465 push @{$c->{stat}}, $_;
3466 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
3467 push @{$c->{stat}}, $_;
3468 $stat = undef;
f8c9d1d2
EW
3469 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
3470 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
3471 } elsif (s/^${esc_color} //o) {
3472 push @{$c->{l}}, $_;
3473 }
3474 }
3475 if ($c && defined $c->{r} && $c->{r} != $r_last) {
3476 $r_last = $c->{r};
3477 process_commit($c, $r_min, $r_max, \@k);
3478 }
3479 if (@k) {
3480 my $swap = $r_max;
3481 $r_max = $r_min;
3482 $r_min = $swap;
3483 process_commit($_, $r_min, $r_max) foreach reverse @k;
3484 }
3485out:
c843c464 3486 close $log;
f8c9d1d2
EW
3487 print '-' x72,"\n" unless $incremental || $oneline;
3488}
3489
706587fc
EW
3490package Git::SVN::Migration;
3491# these version numbers do NOT correspond to actual version numbers
3492# of git nor git-svn. They are just relative.
3493#
3494# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3495#
3496# v1 layout: .git/$id/info/url, refs/remotes/$id
3497#
3498# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3499#
3500# v3 layout: .git/svn/$id, refs/remotes/$id
3501# - info/url may remain for backwards compatibility
3502# - this is what we migrate up to this layout automatically,
3503# - this will be used by git svn init on single branches
26a62d57
EW
3504# v3.1 layout (auto migrated):
3505# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
3506# for backwards compatibility
706587fc
EW
3507#
3508# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3509# - this is only created for newly multi-init-ed
3510# repositories. Similar in spirit to the
3511# --use-separate-remotes option in git-clone (now default)
3512# - we do not automatically migrate to this (following
3513# the example set by core git)
3514use strict;
3515use warnings;
3516use Carp qw/croak/;
3517use File::Path qw/mkpath/;
47e39c55
EW
3518use File::Basename qw/dirname basename/;
3519use vars qw/$_minimize/;
706587fc
EW
3520
3521sub migrate_from_v0 {
3522 my $git_dir = $ENV{GIT_DIR};
3523 return undef unless -d $git_dir;
3524 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3525 my $migrated = 0;
3526 while (<$fh>) {
3527 chomp;
3528 my ($id, $orig_ref) = ($_, $_);
3529 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3530 next unless -f "$git_dir/$id/info/url";
3531 my $new_ref = "refs/remotes/$id";
3532 if (::verify_ref("$new_ref^0")) {
3533 print STDERR "W: $orig_ref is probably an old ",
3534 "branch used by an ancient version of ",
3535 "git-svn.\n",
3536 "However, $new_ref also exists.\n",
3537 "We will not be able ",
3538 "to use this branch until this ",
3539 "ambiguity is resolved.\n";
3540 next;
3541 }
3542 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3543 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3544 command_noisy('update-ref', $new_ref, $orig_ref);
3545 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3546 $migrated++;
3547 }
3548 command_close_pipe($fh, $ctx);
3549 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3550 $migrated;
3551}
3552
3553sub migrate_from_v1 {
3554 my $git_dir = $ENV{GIT_DIR};
3555 my $migrated = 0;
3556 return $migrated unless -d $git_dir;
3557 my $svn_dir = "$git_dir/svn";
3558
3559 # just in case somebody used 'svn' as their $id at some point...
3560 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3561
3562 print STDERR "Migrating from a git-svn v1 layout...\n";
3563 mkpath([$svn_dir]);
3564 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3565 "$svn_dir\n\t(required for this version ",
3566 "($::VERSION) of git-svn) does not. exist\n";
3567 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3568 while (<$fh>) {
3569 my $x = $_;
3570 next unless $x =~ s#^refs/remotes/##;
3571 chomp $x;
3572 next unless -f "$git_dir/$x/info/url";
3573 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3574 next unless $u;
3575 my $dn = dirname("$git_dir/svn/$x");
3576 mkpath([$dn]) unless -d $dn;
3577 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3578 mkpath(["$git_dir/svn/svn"]);
3579 print STDERR " - $git_dir/$x/info => ",
3580 "$git_dir/svn/$x/info\n";
3581 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3582 croak "$!: $x";
3583 # don't worry too much about these, they probably
3584 # don't exist with repos this old (save for index,
3585 # and we can easily regenerate that)
3586 foreach my $f (qw/unhandled.log index .rev_db/) {
3587 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3588 }
3589 } else {
3590 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3591 rename "$git_dir/$x", "$git_dir/svn/$x" or
3592 croak "$!: $x";
3593 }
3594 $migrated++;
3595 }
3596 command_close_pipe($fh, $ctx);
3597 print STDERR "Done migrating from a git-svn v1 layout\n";
3598 $migrated;
3599}
3600
3601sub read_old_urls {
3602 my ($l_map, $pfx, $path) = @_;
3603 my @dir;
3604 foreach (<$path/*>) {
3605 if (-r "$_/info/url") {
3606 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3607 my $ref_id = $pfx . basename $_;
3608 my $url = ::file_to_s("$_/info/url");
3609 $l_map->{$ref_id} = $url;
3610 } elsif (-d $_) {
3611 push @dir, $_;
3612 }
3613 }
3614 foreach (@dir) {
3615 my $x = $_;
3616 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3617 read_old_urls($l_map, $x, $_);
3618 }
3619}
3620
3621sub migrate_from_v2 {
3622 my @cfg = command(qw/config -l/);
3623 return if grep /^svn-remote\..+\.url=/, @cfg;
3624 my %l_map;
3625 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3626 my $migrated = 0;
3627
3628 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
3629 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3630 if ($@) {
3631 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3632 }
706587fc
EW
3633 $migrated++;
3634 }
3635 $migrated;
3636}
3637
47e39c55
EW
3638sub minimize_connections {
3639 my $r = Git::SVN::read_all_remotes();
3640 my $new_urls = {};
3641 my $root_repos = {};
3642 foreach my $repo_id (keys %$r) {
3643 my $url = $r->{$repo_id}->{url} or next;
3644 my $fetch = $r->{$repo_id}->{fetch} or next;
3645 my $ra = Git::SVN::Ra->new($url);
3646
3647 # skip existing cases where we already connect to the root
3648 if (($ra->{url} eq $ra->{repos_root}) ||
3649 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3650 $repo_id)) {
3651 $root_repos->{$ra->{url}} = $repo_id;
3652 next;
3653 }
3654
3655 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3656 my $root_path = $ra->{url};
4e9f6cc7 3657 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
3658 foreach my $path (keys %$fetch) {
3659 my $ref_id = $fetch->{$path};
3660 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3661
3662 # make sure we can read when connecting to
3663 # a higher level of a repository
3664 my ($last_rev, undef) = $gs->last_rev_commit;