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