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