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