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