git-svn: remove the 'rebuild' command and make the functionality automatic
[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) = @_;
44320b9e
EW
984 if (my $c = $self->rev_db_get($log_entry->{revision})) {
985 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
986 "Why are we refetching it?\n";
987 }
1c8443b0
EW
988 my $author = $log_entry->{author};
989 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
990 : ($author, "$author\@".$self->ra->uuid));
9b981fc6
EW
991 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
992 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
44320b9e 993 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 994
44320b9e 995 my $tree = $log_entry->{tree};
9b981fc6
EW
996 if (!defined $tree) {
997 $tree = $self->tmp_index_do(sub {
998 command_oneline('write-tree') });
999 }
1000 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1001
1002 my @exec = ('git-commit-tree', $tree);
0af9c9f9 1003 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
1004 push @exec, '-p', $_;
1005 }
1006 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1007 or croak $!;
44320b9e 1008 print $msg_fh $log_entry->{log} or croak $!;
706587fc 1009 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
44320b9e
EW
1010 $log_entry->{revision}, ' ',
1011 $self->ra->uuid, "\n" or croak $!;
9b981fc6
EW
1012 $msg_fh->flush == 0 or croak $!;
1013 close $msg_fh or croak $!;
1014 chomp(my $commit = do { local $/; <$out_fh> });
1015 close $out_fh or croak $!;
1016 waitpid $pid, 0;
1017 croak $? if $?;
1018 if ($commit !~ /^$::sha1$/o) {
1019 die "Failed to commit, invalid sha1: $commit\n";
1020 }
1021
1022 command_noisy('update-ref',$self->refname, $commit);
44320b9e 1023 $self->rev_db_set($log_entry->{revision}, $commit);
9b981fc6 1024
44320b9e 1025 $self->{last_rev} = $log_entry->{revision};
9b981fc6 1026 $self->{last_commit} = $commit;
44320b9e 1027 print "r$log_entry->{revision} = $commit\n";
9b981fc6
EW
1028 return $commit;
1029}
1030
15710b6f
EW
1031sub revisions_eq {
1032 my ($self, $r0, $r1) = @_;
1033 return 1 if $r0 == $r1;
1034 my $nr = 0;
1035 $self->ra->get_log([$self->{path}], $r0, $r1,
1036 0, 0, 1, sub { $nr++ });
1037 return 0 if ($nr > 1);
1038 return 1;
1039}
1040
28937057
EW
1041sub match_paths {
1042 my ($self, $paths) = @_;
1043 return 1 if $paths->{'/'};
1044 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\/?/;
1045 grep /$self->{path_regex}/, keys %$paths and return 1;
1046 my $c = '';
1047 foreach (split m#/#, $self->rel_path) {
1048 $c .= "/$_";
1049 return 1 if $paths->{$c};
1050 }
1051 return 0;
1052}
1053
15710b6f
EW
1054sub find_parent_branch {
1055 my ($self, $paths, $rev) = @_;
9bf04637 1056 return undef unless $::_follow_parent;
e5a0b240 1057 unless (defined $paths) {
3ebe8df7
EW
1058 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
1059 sub { $paths = dup_changed_paths($_[0]) });
e5a0b240
EW
1060 }
1061 return undef unless defined $paths;
15710b6f
EW
1062
1063 # look for a parent from another branch:
7f578c55
EW
1064 my @b_path_components = split m#/#, $self->rel_path;
1065 my @a_path_components;
1066 my $i;
1067 while (@b_path_components) {
1068 $i = $paths->{'/'.join('/', @b_path_components)};
1069 last if $i;
1070 unshift(@a_path_components, pop(@b_path_components));
1071 }
1072 goto not_found unless defined $i;
3ebe8df7 1073 my $branch_from = $i->{copyfrom_path} or goto not_found;
7f578c55
EW
1074 if (@a_path_components) {
1075 print STDERR "branch_from: $branch_from => ";
1076 $branch_from .= '/'.join('/', @a_path_components);
1077 print STDERR $branch_from, "\n";
1078 }
3ebe8df7 1079 my $r = $i->{copyfrom_rev};
15710b6f
EW
1080 my $repos_root = $self->ra->{repos_root};
1081 my $url = $self->ra->{url};
1082 my $new_url = $repos_root . $branch_from;
1083 print STDERR "Found possible branch point: ",
1084 "$new_url => ", $self->full_url, ", $r\n";
1085 $branch_from =~ s#^/##;
1086 my $remotes = read_all_remotes();
1087 my $gs;
1088 foreach my $repo_id (keys %$remotes) {
1089 my $u = $remotes->{$repo_id}->{url} or next;
1090 next if $url ne $u;
1091 my $fetch = $remotes->{$repo_id}->{fetch};
1092 foreach my $f (keys %$fetch) {
1093 next if $f ne $branch_from;
1094 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1095 last;
1096 }
1097 last if $gs;
1098 }
1099 unless ($gs) {
ce2a0f2f
EW
1100 my $ref_id = $self->{ref_id};
1101 $ref_id =~ s/\@\d+$//;
1102 $ref_id .= "\@$r";
15710b6f
EW
1103 # just grow a tail if we're not unique enough :x
1104 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1105 print STDERR "Initializing parent: $ref_id\n";
15710b6f
EW
1106 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id);
1107 }
1108 my ($r0, $parent) = $gs->find_rev_before($r, 1);
1109 if ($::_follow_parent && (!defined $r0 || !defined $parent)) {
3ebe8df7 1110 $gs->fetch(0, $r);
15710b6f
EW
1111 ($r0, $parent) = $gs->last_rev_commit;
1112 }
1113 if (defined $r0 && defined $parent && $gs->revisions_eq($r0, $r)) {
1114 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
a2003abc 1115 $self->assert_index_clean($parent);
15710b6f
EW
1116 my $ed;
1117 if ($self->ra->can_do_switch) {
8b8fc068 1118 print STDERR "Following parent with do_switch\n";
15710b6f 1119 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1120 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1121 # at the moment), so we can't rely on it
1122 $self->{last_commit} = $parent;
1123 $ed = SVN::Git::Fetcher->new($self);
1124 $gs->ra->gs_do_switch($r0, $rev, $gs->{path}, 1,
1125 $self->full_url, $ed)
1126 or die "SVN connection failed somewhere...\n";
1127 } else {
8b8fc068 1128 print STDERR "Following parent with do_update\n";
15710b6f
EW
1129 $ed = SVN::Git::Fetcher->new($self);
1130 $self->ra->gs_do_update($rev, $rev, $self->{path},
1131 1, $ed)
1132 or die "SVN connection failed somewhere...\n";
1133 }
f7c3fc4a 1134 print STDERR "Successfully followed parent\n";
2fa6a23e 1135 $ed->{new_fetch} = 1;
15710b6f
EW
1136 return $self->make_log_entry($rev, [$parent], $ed);
1137 }
9bf04637 1138not_found:
7f578c55 1139 print STDERR "Branch parent for path: '/",
3ebe8df7
EW
1140 $self->rel_path, "' @ r$rev not found:\n";
1141 return undef unless $paths;
1142 print STDERR "Changed paths:\n";
1143 foreach my $x (sort keys %$paths) {
1144 my $p = $paths->{$x};
1145 print STDERR "\t$p->{action}\t$x";
1146 if ($p->{copyfrom_path}) {
1147 print STDERR "(from $p->{copyfrom_path}: ",
1148 "$p->{copyfrom_rev})";
1149 }
1150 print STDERR "\n";
1151 }
1152 print STDERR '-'x72, "\n";
15710b6f
EW
1153 return undef;
1154}
1155
9b981fc6 1156sub do_fetch {
706587fc 1157 my ($self, $paths, $rev) = @_;
15710b6f 1158 my $ed;
9b981fc6
EW
1159 my ($last_rev, @parents);
1160 if ($self->{last_commit}) {
15710b6f 1161 $ed = SVN::Git::Fetcher->new($self);
9b981fc6
EW
1162 $last_rev = $self->{last_rev};
1163 $ed->{c} = $self->{last_commit};
1164 @parents = ($self->{last_commit});
1165 } else {
1166 $last_rev = $rev;
15710b6f
EW
1167 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1168 return $log_entry;
1169 }
1170 $ed = SVN::Git::Fetcher->new($self);
2fa6a23e 1171 $ed->{new_fetch} = 1;
9b981fc6 1172 }
706587fc
EW
1173 unless ($self->ra->gs_do_update($last_rev, $rev,
1174 $self->{path}, 1, $ed)) {
9b981fc6
EW
1175 die "SVN connection failed somewhere...\n";
1176 }
1177 $self->make_log_entry($rev, \@parents, $ed);
1178}
1179
97f6987a
EW
1180sub get_untracked {
1181 my ($self, $ed) = @_;
1182 my @out;
1183 my $h = $ed->{empty};
9b981fc6
EW
1184 foreach (sort keys %$h) {
1185 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1186 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1187 warn "W: $act: $_\n";
1188 }
1189 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1190 $h = $ed->{$t} or next;
9b981fc6
EW
1191 foreach my $path (sort keys %$h) {
1192 my $ppath = $path eq '' ? '.' : $path;
1193 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1194 next if $SKIP_PROP{$prop};
9b981fc6 1195 my $v = $h->{$path}->{$prop};
97f6987a
EW
1196 my $t_ppath_prop = "$t: " .
1197 uri_encode($ppath) . ' ' .
1198 uri_encode($prop);
9b981fc6 1199 if (defined $v) {
97f6987a
EW
1200 push @out, " +$t_ppath_prop " .
1201 uri_encode($v);
9b981fc6 1202 } else {
97f6987a 1203 push @out, " -$t_ppath_prop";
9b981fc6
EW
1204 }
1205 }
1206 }
1207 }
1208 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1209 $h = $ed->{$t} or next;
9b981fc6
EW
1210 foreach my $parent (sort keys %$h) {
1211 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1212 push @out, " $t: " .
1213 uri_encode("$parent/$path");
9b981fc6
EW
1214 warn "W: $t: $parent/$path ",
1215 "Insufficient permissions?\n";
1216 }
1217 }
1218 }
97f6987a 1219 \@out;
9b981fc6
EW
1220}
1221
1c8443b0
EW
1222sub parse_svn_date {
1223 my $date = shift || return '+0000 1970-01-01 00:00:00';
1224 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1225 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1226 croak "Unable to parse date: $date\n";
1227 "+0000 $Y-$m-$d $H:$M:$S";
1228}
1229
1230sub check_author {
1231 my ($author) = @_;
1232 if (!defined $author || length $author == 0) {
1233 $author = '(no author)';
1234 }
1235 if (defined $::_authors && ! defined $::users{$author}) {
1236 die "Author: $author not defined in $::_authors file\n";
1237 }
1238 $author;
1239}
1240
9b981fc6 1241sub make_log_entry {
97f6987a
EW
1242 my ($self, $rev, $parents, $ed) = @_;
1243 my $untracked = $self->get_untracked($ed);
1244
2fa6a23e 1245 return undef if (! $ed->{new_fetch} && ! $ed->{nr} && ! @$untracked);
e5a0b240 1246
9b981fc6 1247 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1248 print $un "r$rev\n" or croak $!;
1249 print $un $_, "\n" foreach @$untracked;
1250 my %log_entry = ( parents => $parents || [], revision => $rev,
1251 log => '');
1252 my $rp = $self->ra->rev_proplist($rev);
9b981fc6
EW
1253 foreach (sort keys %$rp) {
1254 my $v = $rp->{$_};
1255 if (/^svn:(author|date|log)$/) {
1256 $log_entry{$1} = $v;
1257 } else {
1258 print $un " rev_prop: ", uri_encode($_), ' ',
1259 uri_encode($v), "\n";
1260 }
1261 }
1262 close $un or croak $!;
97f6987a 1263
9b981fc6
EW
1264 $log_entry{date} = parse_svn_date($log_entry{date});
1265 $log_entry{author} = check_author($log_entry{author});
1266 $log_entry{log} .= "\n";
1267 \%log_entry;
1268}
1269
1270sub fetch {
3ebe8df7 1271 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1272 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1273 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
9b981fc6 1274 return if ($base > $head);
0af9c9f9 1275 $self->ra->gs_fetch_loop_common($base, $head, $self);
9b981fc6
EW
1276}
1277
1278sub set_tree_cb {
1279 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1280 # TODO: enable and test optimized commits:
1281 if (0 && $rev == ($self->{last_rev} + 1)) {
1282 $log_entry->{revision} = $rev;
1283 $log_entry->{author} = $author;
1284 $self->do_git_commit($log_entry, "$rev=$tree");
1285 } else {
0af9c9f9
EW
1286 $self->{inject_parents} = { $rev => $tree };
1287 $self->fetch(undef, undef);
9b981fc6
EW
1288 }
1289}
1290
1291sub set_tree {
1292 my ($self, $tree) = (shift, shift);
1ce255dc 1293 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1294 unless ($self->{last_rev}) {
1295 fatal("Must have an existing revision to commit\n");
1296 }
61395354
EW
1297 my %ed_opts = ( r => $self->{last_rev},
1298 log => $log_entry->{log},
1299 ra => $self->ra,
1300 tree_a => $self->{last_commit},
1301 tree_b => $tree,
1302 editor_cb => sub {
1303 $self->set_tree_cb($log_entry, $tree, @_) },
1304 svn_path => $self->{path} );
1305 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1306 print "No changes\nr$self->{last_rev} = $tree\n";
1307 }
9b981fc6
EW
1308}
1309
f0ecca10
EW
1310sub rebuild {
1311 my ($self) = @_;
1312 print "Rebuilding $self->{db_path} ...\n";
1313 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1314 my $latest;
1315 my $full_url = $self->full_url;
1316 my $svn_uuid;
1317 while (<$rev_list>) {
1318 chomp;
1319 my $c = $_;
1320 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1321 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1322
1323 # ignore merges (from set-tree)
1324 next if (!defined $rev || !$uuid);
1325
1326 # if we merged or otherwise started elsewhere, this is
1327 # how we break out of it
1328 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1329 ($full_url && $url && ($url ne $full_url))) {
1330 next;
1331 }
1332 $latest ||= $rev;
1333 $svn_uuid ||= $uuid;
1334
1335 $self->rev_db_set($rev, $c);
1336 print "r$rev = $c\n";
1337 }
1338 command_close_pipe($rev_list, $ctx);
1339 print "Done rebuilding $self->{db_path}\n";
1340}
1341
9b981fc6
EW
1342# rev_db:
1343# Tie::File seems to be prone to offset errors if revisions get sparse,
1344# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1345# one of my favorite modules is out :< Next up would be one of the DBM
1346# modules, but I'm not sure which is most portable... So I'll just
1347# go with something that's plain-text, but still capable of
1348# being randomly accessed. So here's my ultra-simple fixed-width
1349# database. All records are 40 characters + "\n", so it's easy to seek
1350# to a revision: (41 * rev) is the byte offset.
1351# A record of 40 0s denotes an empty revision.
1352# And yes, it's still pretty fast (faster than Tie::File).
1353
1354sub rev_db_set {
1355 my ($self, $rev, $commit) = @_;
1356 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
1357 open my $fh, '+<', $self->{db_path} or croak $!;
1358 my $offset = $rev * 41;
1359 # assume that append is the common case:
1360 seek $fh, 0, 2 or croak $!;
1361 my $pos = tell $fh;
1362 if ($pos < $offset) {
1363 print $fh (('0' x 40),"\n") x (($offset - $pos) / 41)
1364 or croak $!;
1365 }
1366 seek $fh, $offset, 0 or croak $!;
1367 print $fh $commit,"\n" or croak $!;
1368 close $fh or croak $!;
1369}
1370
1371sub rev_db_get {
1372 my ($self, $rev) = @_;
1373 my $ret;
1374 my $offset = $rev * 41;
1375 open my $fh, '<', $self->{db_path} or croak $!;
1376 if (seek $fh, $offset, 0) {
1377 $ret = readline $fh;
1378 if (defined $ret) {
1379 chomp $ret;
1380 $ret = undef if ($ret =~ /^0{40}$/);
1381 }
1382 }
1383 close $fh or croak $!;
1384 $ret;
1385}
1386
15710b6f
EW
1387sub find_rev_before {
1388 my ($self, $rev, $eq_ok) = @_;
1389 --$rev unless $eq_ok;
1390 while ($rev > 0) {
1391 if (my $c = $self->rev_db_get($rev)) {
1392 return ($rev, $c);
1393 }
1394 --$rev;
1395 }
1396 return (undef, undef);
1397}
1398
9b981fc6 1399sub _new {
706587fc
EW
1400 my ($class, $repo_id, $ref_id, $path) = @_;
1401 unless (defined $repo_id && length $repo_id) {
1402 $repo_id = $Git::SVN::default_repo_id;
1403 }
1404 unless (defined $ref_id && length $ref_id) {
8b8fc068 1405 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
1406 }
1407 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1408 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1409 $_[3] = $path = '' unless (defined $path);
8b8fc068
EW
1410 mkpath([$dir]);
1411 unless (-f "$dir/.rev_db") {
1412 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1413 close $fh or croak $!;
1414 }
706587fc
EW
1415 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1416 path => $path,
1417 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
9b981fc6
EW
1418}
1419
1c8443b0
EW
1420sub uri_encode {
1421 my ($f) = @_;
1422 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1423 $f
1424}
9b981fc6 1425
d976acfd
EW
1426package Git::SVN::Prompt;
1427use strict;
1428use warnings;
1429require SVN::Core;
1430use vars qw/$_no_auth_cache $_username/;
1431
1432sub simple {
30d055aa
EW
1433 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1434 $may_save = undef if $_no_auth_cache;
1435 $default_username = $_username if defined $_username;
1436 if (defined $default_username && length $default_username) {
1437 if (defined $realm && length $realm) {
6f729591
EW
1438 print STDERR "Authentication realm: $realm\n";
1439 STDERR->flush;
30d055aa
EW
1440 }
1441 $cred->username($default_username);
1442 } else {
d976acfd 1443 username($cred, $realm, $may_save, $pool);
30d055aa
EW
1444 }
1445 $cred->password(_read_password("Password for '" .
1446 $cred->username . "': ", $realm));
1447 $cred->may_save($may_save);
1448 $SVN::_Core::SVN_NO_ERROR;
1449}
1450
d976acfd 1451sub ssl_server_trust {
30d055aa
EW
1452 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1453 $may_save = undef if $_no_auth_cache;
6f729591 1454 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 1455 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 1456 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
1457 "authority. Use the\n",
1458 " fingerprint to validate the certificate manually!\n";
1459 }
1460 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 1461 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
1462 }
1463 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 1464 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
1465 }
1466 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 1467 print STDERR " - The certificate has expired.\n";
30d055aa
EW
1468 }
1469 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 1470 print STDERR " - The certificate has an unknown error.\n";
30d055aa 1471 }
6f729591
EW
1472 printf STDERR
1473 "Certificate information:\n".
30d055aa
EW
1474 " - Hostname: %s\n".
1475 " - Valid: from %s until %s\n".
1476 " - Issuer: %s\n".
1477 " - Fingerprint: %s\n",
1478 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 1479 issuer_dname fingerprint);
30d055aa
EW
1480 my $choice;
1481prompt:
6f729591 1482 print STDERR $may_save ?
30d055aa
EW
1483 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1484 "(R)eject or accept (t)emporarily? ";
6f729591 1485 STDERR->flush;
30d055aa
EW
1486 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1487 if ($choice =~ /^t$/i) {
1488 $cred->may_save(undef);
1489 } elsif ($choice =~ /^r$/i) {
1490 return -1;
1491 } elsif ($may_save && $choice =~ /^p$/i) {
1492 $cred->may_save($may_save);
1493 } else {
1494 goto prompt;
1495 }
1496 $cred->accepted_failures($failures);
1497 $SVN::_Core::SVN_NO_ERROR;
1498}
1499
d976acfd 1500sub ssl_client_cert {
30d055aa
EW
1501 my ($cred, $realm, $may_save, $pool) = @_;
1502 $may_save = undef if $_no_auth_cache;
6f729591
EW
1503 print STDERR "Client certificate filename: ";
1504 STDERR->flush;
30d055aa
EW
1505 chomp(my $filename = <STDIN>);
1506 $cred->cert_file($filename);
1507 $cred->may_save($may_save);
1508 $SVN::_Core::SVN_NO_ERROR;
1509}
1510
d976acfd 1511sub ssl_client_cert_pw {
30d055aa
EW
1512 my ($cred, $realm, $may_save, $pool) = @_;
1513 $may_save = undef if $_no_auth_cache;
1514 $cred->password(_read_password("Password: ", $realm));
1515 $cred->may_save($may_save);
1516 $SVN::_Core::SVN_NO_ERROR;
1517}
1518
d976acfd 1519sub username {
30d055aa
EW
1520 my ($cred, $realm, $may_save, $pool) = @_;
1521 $may_save = undef if $_no_auth_cache;
1522 if (defined $realm && length $realm) {
6f729591 1523 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
1524 }
1525 my $username;
1526 if (defined $_username) {
1527 $username = $_username;
1528 } else {
6f729591
EW
1529 print STDERR "Username: ";
1530 STDERR->flush;
30d055aa
EW
1531 chomp($username = <STDIN>);
1532 }
1533 $cred->username($username);
1534 $cred->may_save($may_save);
1535 $SVN::_Core::SVN_NO_ERROR;
1536}
1537
1538sub _read_password {
1539 my ($prompt, $realm) = @_;
6f729591
EW
1540 print STDERR $prompt;
1541 STDERR->flush;
30d055aa
EW
1542 require Term::ReadKey;
1543 Term::ReadKey::ReadMode('noecho');
1544 my $password = '';
1545 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1546 last if $key =~ /[\012\015]/; # \n\r
1547 $password .= $key;
1548 }
1549 Term::ReadKey::ReadMode('restore');
6f729591
EW
1550 print STDERR "\n";
1551 STDERR->flush;
30d055aa
EW
1552 $password;
1553}
1554
d976acfd
EW
1555package main;
1556
b9c85187
EW
1557{
1558 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1559 $SVN::Node::dir.$SVN::Node::unknown.
1560 $SVN::Node::none.$SVN::Node::file.
1561 $SVN::Node::dir.$SVN::Node::unknown.
1562 $SVN::Auth::SSL::CNMISMATCH.
1563 $SVN::Auth::SSL::NOTYETVALID.
1564 $SVN::Auth::SSL::EXPIRED.
1565 $SVN::Auth::SSL::UNKNOWNCA.
1566 $SVN::Auth::SSL::OTHER;
1567}
1568
27a1a801
EW
1569package SVN::Git::Fetcher;
1570use vars qw/@ISA/;
1571use strict;
1572use warnings;
1573use Carp qw/croak/;
1574use IO::File qw//;
90c1b15d 1575use Digest::MD5;
27a1a801
EW
1576
1577# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1578sub new {
1579 my ($class, $git_svn) = @_;
1580 my $self = SVN::Delta::Editor->new;
1581 bless $self, $class;
1c8443b0 1582 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
1583 $self->{empty} = {};
1584 $self->{dir_prop} = {};
1585 $self->{file_prop} = {};
1586 $self->{absent_dir} = {};
1587 $self->{absent_file} = {};
ef3cfaad 1588 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
1589 $self;
1590}
1591
8b8fc068
EW
1592sub set_path_strip {
1593 my ($self, $path) = @_;
1594 $self->{path_strip} = qr/^\Q$path\E\/?/;
1595}
1596
d2a9a87b
EW
1597sub open_root {
1598 { path => '' };
1599}
1600
1601sub open_directory {
1602 my ($self, $path, $pb, $rev) = @_;
1603 { path => $path };
1604}
1605
706587fc
EW
1606sub git_path {
1607 my ($self, $path) = @_;
2b27f6c8
EW
1608 if ($self->{path_strip}) {
1609 $path =~ s!$self->{path_strip}!! or
1610 die "Failed to strip path '$path' ($self->{path_strip})\n";
1611 }
706587fc
EW
1612 $path;
1613}
1614
27a1a801
EW
1615sub delete_entry {
1616 my ($self, $path, $rev, $pb) = @_;
4a87db0e 1617
706587fc 1618 my $gpath = $self->git_path($path);
4a87db0e 1619 # remove entire directories.
706587fc 1620 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
1621 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1622 -r --name-only -z/,
706587fc 1623 $self->{c}, '--', $gpath);
4a87db0e
EW
1624 local $/ = "\0";
1625 while (<$ls>) {
ef3cfaad
EW
1626 chomp;
1627 $self->{gii}->remove($_);
4a87db0e
EW
1628 print "\tD\t$_\n" unless $self->{q};
1629 }
706587fc 1630 print "\tD\t$gpath/\n" unless $self->{q};
4a87db0e
EW
1631 command_close_pipe($ls, $ctx);
1632 $self->{empty}->{$path} = 0
1633 } else {
ef3cfaad 1634 $self->{gii}->remove($gpath);
706587fc 1635 print "\tD\t$gpath\n" unless $self->{q};
4a87db0e 1636 }
27a1a801
EW
1637 undef;
1638}
1639
1640sub open_file {
1641 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
1642 my $gpath = $self->git_path($path);
1643 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 1644 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
1645 unless (defined $mode && defined $blob) {
1646 die "$path was not found in commit $self->{c} (r$rev)\n";
1647 }
27a1a801 1648 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 1649 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
1650}
1651
1652sub add_file {
1653 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
1654 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1655 delete $self->{empty}->{$dir};
27a1a801 1656 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 1657 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
1658}
1659
d2a9a87b
EW
1660sub add_directory {
1661 my ($self, $path, $cp_path, $cp_rev) = @_;
1662 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1663 delete $self->{empty}->{$dir};
1664 $self->{empty}->{$path} = 1;
1665 { path => $path };
1666}
1667
1668sub change_dir_prop {
1669 my ($self, $db, $prop, $value) = @_;
1670 $self->{dir_prop}->{$db->{path}} ||= {};
1671 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1672 undef;
1673}
1674
1675sub absent_directory {
1676 my ($self, $path, $pb) = @_;
1677 $self->{absent_dir}->{$pb->{path}} ||= [];
1678 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1679 undef;
1680}
1681
1682sub absent_file {
1683 my ($self, $path, $pb) = @_;
1684 $self->{absent_file}->{$pb->{path}} ||= [];
1685 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1686 undef;
1687}
1688
27a1a801
EW
1689sub change_file_prop {
1690 my ($self, $fb, $prop, $value) = @_;
1691 if ($prop eq 'svn:executable') {
1692 if ($fb->{mode_b} != 120000) {
1693 $fb->{mode_b} = defined $value ? 100755 : 100644;
1694 }
1695 } elsif ($prop eq 'svn:special') {
1696 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
1697 } else {
1698 $self->{file_prop}->{$fb->{path}} ||= {};
1699 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
1700 }
1701 undef;
1702}
1703
1704sub apply_textdelta {
1705 my ($self, $fb, $exp) = @_;
1706 my $fh = IO::File->new_tmpfile;
1707 $fh->autoflush(1);
1708 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1709 # (but $base does not,) so dup() it for reading in close_file
1710 open my $dup, '<&', $fh or croak $!;
1711 my $base = IO::File->new_tmpfile;
1712 $base->autoflush(1);
1713 if ($fb->{blob}) {
1714 defined (my $pid = fork) or croak $!;
1715 if (!$pid) {
1716 open STDOUT, '>&', $base or croak $!;
1717 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1718 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1719 }
1720 waitpid $pid, 0;
1721 croak $? if $?;
1722
1723 if (defined $exp) {
1724 seek $base, 0, 0 or croak $!;
1725 my $md5 = Digest::MD5->new;
1726 $md5->addfile($base);
1727 my $got = $md5->hexdigest;
1728 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1729 "expected: $exp\n",
1730 " got: $got\n" if ($got ne $exp);
1731 }
1732 }
1733 seek $base, 0, 0 or croak $!;
1734 $fb->{fh} = $dup;
1735 $fb->{base} = $base;
1736 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1737}
1738
1739sub close_file {
1740 my ($self, $fb, $exp) = @_;
1741 my $hash;
706587fc 1742 my $path = $self->git_path($fb->{path});
27a1a801
EW
1743 if (my $fh = $fb->{fh}) {
1744 seek($fh, 0, 0) or croak $!;
1745 my $md5 = Digest::MD5->new;
1746 $md5->addfile($fh);
1747 my $got = $md5->hexdigest;
1748 die "Checksum mismatch: $path\n",
1749 "expected: $exp\n got: $got\n" if ($got ne $exp);
1750 seek($fh, 0, 0) or croak $!;
1751 if ($fb->{mode_b} == 120000) {
1752 read($fh, my $buf, 5) == 5 or croak $!;
1753 $buf eq 'link ' or die "$path has mode 120000",
1754 "but is not a link\n";
1755 }
1756 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1757 if (!$pid) {
1758 open STDIN, '<&', $fh or croak $!;
1759 exec qw/git-hash-object -w --stdin/ or croak $!;
1760 }
1761 chomp($hash = do { local $/; <$out> });
1762 close $out or croak $!;
1763 close $fh or croak $!;
1764 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1765 close $fb->{base} or croak $!;
1766 } else {
1767 $hash = $fb->{blob} or die "no blob information\n";
1768 }
1769 $fb->{pool}->clear;
ef3cfaad 1770 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
0864e3ba 1771 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
27a1a801
EW
1772 undef;
1773}
1774
1775sub abort_edit {
1776 my $self = shift;
ef3cfaad
EW
1777 $self->{nr} = $self->{gii}->{nr};
1778 delete $self->{gii};
27a1a801
EW
1779 $self->SUPER::abort_edit(@_);
1780}
1781
1782sub close_edit {
1783 my $self = shift;
dad73c0b 1784 $self->{git_commit_ok} = 1;
ef3cfaad
EW
1785 $self->{nr} = $self->{gii}->{nr};
1786 delete $self->{gii};
27a1a801
EW
1787 $self->SUPER::close_edit(@_);
1788}
1a82e793 1789
a5e0cedc 1790package SVN::Git::Editor;
24e22aa8 1791use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
1792use strict;
1793use warnings;
1794use Carp qw/croak/;
1795use IO::File;
90c1b15d 1796use Digest::MD5;
a5e0cedc
EW
1797
1798sub new {
61395354
EW
1799 my ($class, $opts) = @_;
1800 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1801 die "$_ required!\n" unless (defined $opts->{$_});
1802 }
1803
1804 my $pool = SVN::Pool->new;
1805 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1806 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1807 $opts->{r}, $mods);
1808
1809 # $opts->{ra} functions should not be used after this:
1810 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
1811 $opts->{editor_cb}, $pool);
1812 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 1813 bless $self, $class;
61395354
EW
1814 foreach (qw/svn_path r tree_a tree_b/) {
1815 $self->{$_} = $opts->{$_};
a5e0cedc 1816 }
61395354
EW
1817 $self->{url} = $opts->{ra}->{url};
1818 $self->{mods} = $mods;
1819 $self->{types} = $types;
1820 $self->{pool} = $pool;
a5e0cedc
EW
1821 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1822 $self->{rm} = { };
d3a840dc
EW
1823 $self->{path_prefix} = length $self->{svn_path} ?
1824 "$self->{svn_path}/" : '';
a5e0cedc
EW
1825 return $self;
1826}
1827
61395354
EW
1828sub generate_diff {
1829 my ($tree_a, $tree_b) = @_;
1830 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
1831 if ($_cp_similarity) {
1832 push @diff_tree, "-C$_cp_similarity";
61395354
EW
1833 } else {
1834 push @diff_tree, '-C';
1835 }
24e22aa8
EW
1836 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1837 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
1838 push @diff_tree, $tree_a, $tree_b;
1839 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1840 local $/ = "\0";
1841 my $state = 'meta';
1842 my @mods;
1843 while (<$diff_fh>) {
1844 chomp $_; # this gets rid of the trailing "\0"
1845 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1846 $::sha1\s($::sha1)\s
1847 ([MTCRAD])\d*$/xo) {
1848 push @mods, { mode_a => $1, mode_b => $2,
1849 sha1_b => $3, chg => $4 };
1850 if ($4 =~ /^(?:C|R)$/) {
1851 $state = 'file_a';
1852 } else {
1853 $state = 'file_b';
1854 }
1855 } elsif ($state eq 'file_a') {
1856 my $x = $mods[$#mods] or croak "Empty array\n";
1857 if ($x->{chg} !~ /^(?:C|R)$/) {
1858 croak "Error parsing $_, $x->{chg}\n";
1859 }
1860 $x->{file_a} = $_;
1861 $state = 'file_b';
1862 } elsif ($state eq 'file_b') {
1863 my $x = $mods[$#mods] or croak "Empty array\n";
1864 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1865 croak "Error parsing $_, $x->{chg}\n";
1866 }
1867 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1868 croak "Error parsing $_, $x->{chg}\n";
1869 }
1870 $x->{file_b} = $_;
1871 $state = 'meta';
1872 } else {
1873 croak "Error parsing $_\n";
1874 }
1875 }
1876 command_close_pipe($diff_fh, $ctx);
1877 \@mods;
1878}
1879
1880sub check_diff_paths {
1881 my ($ra, $pfx, $rev, $mods) = @_;
1882 my %types;
1883 $pfx .= '/' if length $pfx;
1884
1885 sub type_diff_paths {
1886 my ($ra, $types, $path, $rev) = @_;
1887 my @p = split m#/+#, $path;
1888 my $c = shift @p;
1889 unless (defined $types->{$c}) {
1890 $types->{$c} = $ra->check_path($c, $rev);
1891 }
1892 while (@p) {
1893 $c .= '/' . shift @p;
1894 next if defined $types->{$c};
1895 $types->{$c} = $ra->check_path($c, $rev);
1896 }
1897 }
1898
1899 foreach my $m (@$mods) {
1900 foreach my $f (qw/file_a file_b/) {
1901 next unless defined $m->{$f};
1902 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
1903 if (length $pfx.$dir && ! defined $types{$dir}) {
1904 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
1905 }
1906 }
1907 }
1908 \%types;
1909}
1910
a5e0cedc
EW
1911sub split_path {
1912 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
1913}
1914
1915sub repo_path {
d3a840dc
EW
1916 my ($self, $path) = @_;
1917 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
1918}
1919
1920sub url_path {
1921 my ($self, $path) = @_;
6e8548cc 1922 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
1923}
1924
1925sub rmdirs {
61395354 1926 my ($self) = @_;
a5e0cedc
EW
1927 my $rm = $self->{rm};
1928 delete $rm->{''}; # we never delete the url we're tracking
1929 return unless %$rm;
1930
1931 foreach (keys %$rm) {
1932 my @d = split m#/#, $_;
1933 my $c = shift @d;
1934 $rm->{$c} = 1;
1935 while (@d) {
1936 $c .= '/' . shift @d;
1937 $rm->{$c} = 1;
1938 }
1939 }
1940 delete $rm->{$self->{svn_path}};
1941 delete $rm->{''}; # we never delete the url we're tracking
1942 return unless %$rm;
1943
61395354
EW
1944 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
1945 $self->{tree_b});
a5e0cedc
EW
1946 local $/ = "\0";
1947 while (<$fh>) {
1948 chomp;
747fa12c 1949 my @dn = split m#/#, $_;
c07eee1f
EW
1950 while (pop @dn) {
1951 delete $rm->{join '/', @dn};
1952 }
1953 unless (%$rm) {
22600a25 1954 close $fh;
c07eee1f
EW
1955 return;
1956 }
a5e0cedc 1957 }
aef4e921 1958 command_close_pipe($fh, $ctx);
c07eee1f 1959
a5e0cedc
EW
1960 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
1961 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
1962 $self->close_directory($bat->{$d}, $p);
1963 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 1964 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
1965 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
1966 delete $bat->{$d};
1967 }
1968}
1969
1970sub open_or_add_dir {
1971 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
1972 my $t = $self->{types}->{$full_path};
1973 if (!defined $t) {
1974 die "$full_path not known in r$self->{r} or we have a bug!\n";
1975 }
a5e0cedc
EW
1976 if ($t == $SVN::Node::none) {
1977 return $self->add_directory($full_path, $baton,
1978 undef, -1, $self->{pool});
1979 } elsif ($t == $SVN::Node::dir) {
1980 return $self->open_directory($full_path, $baton,
1981 $self->{r}, $self->{pool});
1982 }
1983 print STDERR "$full_path already exists in repository at ",
1984 "r$self->{r} and it is not a directory (",
1985 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
1986 exit 1;
1987}
1988
1989sub ensure_path {
1990 my ($self, $path) = @_;
1991 my $bat = $self->{bat};
6e8548cc
EW
1992 my $repo_path = $self->repo_path($path);
1993 return $bat->{''} unless (length $repo_path);
1994 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
1995 my $c = shift @p;
1996 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
1997 while (@p) {
1998 my $c0 = $c;
1999 $c .= '/' . shift @p;
2000 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2001 }
2002 return $bat->{$c};
2003}
2004
2005sub A {
44320b9e 2006 my ($self, $m) = @_;
a5e0cedc
EW
2007 my ($dir, $file) = split_path($m->{file_b});
2008 my $pbat = $self->ensure_path($dir);
2009 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2010 undef, -1);
44320b9e 2011 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2012 $self->chg_file($fbat, $m);
2013 $self->close_file($fbat,undef,$self->{pool});
2014}
2015
2016sub C {
44320b9e 2017 my ($self, $m) = @_;
a5e0cedc
EW
2018 my ($dir, $file) = split_path($m->{file_b});
2019 my $pbat = $self->ensure_path($dir);
2020 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2021 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2022 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2023 $self->chg_file($fbat, $m);
2024 $self->close_file($fbat,undef,$self->{pool});
2025}
2026
2027sub delete_entry {
2028 my ($self, $path, $pbat) = @_;
2029 my $rpath = $self->repo_path($path);
2030 my ($dir, $file) = split_path($rpath);
2031 $self->{rm}->{$dir} = 1;
2032 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2033}
2034
2035sub R {
44320b9e 2036 my ($self, $m) = @_;
a5e0cedc
EW
2037 my ($dir, $file) = split_path($m->{file_b});
2038 my $pbat = $self->ensure_path($dir);
2039 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2040 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2041 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2042 $self->chg_file($fbat, $m);
2043 $self->close_file($fbat,undef,$self->{pool});
2044
2045 ($dir, $file) = split_path($m->{file_a});
2046 $pbat = $self->ensure_path($dir);
2047 $self->delete_entry($m->{file_a}, $pbat);
2048}
2049
2050sub M {
44320b9e 2051 my ($self, $m) = @_;
a5e0cedc
EW
2052 my ($dir, $file) = split_path($m->{file_b});
2053 my $pbat = $self->ensure_path($dir);
2054 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2055 $pbat,$self->{r},$self->{pool});
44320b9e 2056 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2057 $self->chg_file($fbat, $m);
2058 $self->close_file($fbat,undef,$self->{pool});
2059}
2060
2061sub T { shift->M(@_) }
2062
2063sub change_file_prop {
2064 my ($self, $fbat, $pname, $pval) = @_;
2065 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2066}
2067
2068sub chg_file {
2069 my ($self, $fbat, $m) = @_;
2070 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2071 $self->change_file_prop($fbat,'svn:executable','*');
2072 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2073 $self->change_file_prop($fbat,'svn:executable',undef);
2074 }
2075 my $fh = IO::File->new_tmpfile or croak $!;
2076 if ($m->{mode_b} =~ /^120/) {
2077 print $fh 'link ' or croak $!;
2078 $self->change_file_prop($fbat,'svn:special','*');
2079 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2080 $self->change_file_prop($fbat,'svn:special',undef);
2081 }
2082 defined(my $pid = fork) or croak $!;
2083 if (!$pid) {
2084 open STDOUT, '>&', $fh or croak $!;
2085 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2086 }
2087 waitpid $pid, 0;
2088 croak $? if $?;
2089 $fh->flush == 0 or croak $!;
2090 seek $fh, 0, 0 or croak $!;
2091
2092 my $md5 = Digest::MD5->new;
2093 $md5->addfile($fh) or croak $!;
2094 seek $fh, 0, 0 or croak $!;
2095
2096 my $exp = $md5->hexdigest;
f7197dff
EW
2097 my $pool = SVN::Pool->new;
2098 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2099 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2100 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2101 $pool->clear;
a5e0cedc
EW
2102
2103 close $fh or croak $!;
2104}
2105
2106sub D {
44320b9e 2107 my ($self, $m) = @_;
a5e0cedc
EW
2108 my ($dir, $file) = split_path($m->{file_b});
2109 my $pbat = $self->ensure_path($dir);
44320b9e 2110 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2111 $self->delete_entry($m->{file_b}, $pbat);
2112}
2113
2114sub close_edit {
2115 my ($self) = @_;
2116 my ($p,$bat) = ($self->{pool}, $self->{bat});
2117 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2118 $self->close_directory($bat->{$_}, $p);
2119 }
2120 $self->SUPER::close_edit($p);
2121 $p->clear;
2122}
2123
2124sub abort_edit {
2125 my ($self) = @_;
2126 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2127}
2128
2129sub DESTROY {
2130 my $self = shift;
2131 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2132 $self->{pool}->clear;
2133}
2134
44320b9e
EW
2135# this drives the editor
2136sub apply_diff {
61395354
EW
2137 my ($self) = @_;
2138 my $mods = $self->{mods};
44320b9e 2139 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2140 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2141 my $f = $m->{chg};
2142 if (defined $o{$f}) {
2143 $self->$f($m);
2144 } else {
2145 fatal("Invalid change type: $f\n");
2146 }
2147 }
24e22aa8 2148 $self->rmdirs if $_rmdir;
6e8548cc 2149 if (@$mods == 0) {
44320b9e
EW
2150 $self->abort_edit;
2151 } else {
2152 $self->close_edit;
2153 }
6e8548cc 2154 return scalar @$mods;
44320b9e
EW
2155}
2156
d81bf827
EW
2157package Git::SVN::Ra;
2158use vars qw/@ISA $config_dir/;
2159use strict;
2160use warnings;
2161my ($can_do_switch);
5d3b7cd5 2162my $RA;
d81bf827
EW
2163
2164BEGIN {
2165 # enforce temporary pool usage for some simple functions
2166 my $e;
2167 foreach (qw/get_latest_revnum rev_proplist get_file
2168 check_path get_dir get_uuid get_repos_root/) {
2169 $e .= "sub $_ {
2170 my \$self = shift;
2171 my \$pool = SVN::Pool->new;
2172 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2173 \$pool->clear;
2174 wantarray ? \@ret : \$ret[0]; }\n";
2175 }
2176 eval $e;
2177}
2178
2179sub new {
2180 my ($class, $url) = @_;
f6f09876 2181 $url =~ s!/+$!!;
5d3b7cd5 2182 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 2183
d81bf827
EW
2184 SVN::_Core::svn_config_ensure($config_dir, undef);
2185 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2186 SVN::Client::get_simple_provider(),
2187 SVN::Client::get_ssl_server_trust_file_provider(),
2188 SVN::Client::get_simple_prompt_provider(
2189 \&Git::SVN::Prompt::simple, 2),
2190 SVN::Client::get_ssl_client_cert_prompt_provider(
2191 \&Git::SVN::Prompt::ssl_client_cert, 2),
2192 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2193 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2194 SVN::Client::get_username_provider(),
2195 SVN::Client::get_ssl_server_trust_prompt_provider(
2196 \&Git::SVN::Prompt::ssl_server_trust),
2197 SVN::Client::get_username_prompt_provider(
2198 \&Git::SVN::Prompt::username, 2),
2199 ]);
2200 my $config = SVN::Core::config_get_config($config_dir);
2201 my $self = SVN::Ra->new(url => $url, auth => $baton,
2202 config => $config,
2203 pool => SVN::Pool->new,
2204 auth_provider_callbacks => $callbacks);
2205 $self->{svn_path} = $url;
2206 $self->{repos_root} = $self->get_repos_root;
2207 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
5d3b7cd5 2208 $RA = bless $self, $class;
d81bf827
EW
2209}
2210
2211sub DESTROY {
5d3b7cd5 2212 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2213}
2214
d81bf827
EW
2215sub get_log {
2216 my ($self, @args) = @_;
2217 my $pool = SVN::Pool->new;
d81bf827
EW
2218 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2219 my $ret = $self->SUPER::get_log(@args, $pool);
2220 $pool->clear;
2221 $ret;
2222}
2223
2224sub get_commit_editor {
44320b9e 2225 my ($self, $log, $cb, $pool) = @_;
d81bf827 2226 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2227 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2228}
2229
2230sub uuid {
2231 my ($self) = @_;
2232 $self->{uuid} ||= $self->get_uuid;
2233}
2234
2235sub gs_do_update {
2236 my ($self, $rev_a, $rev_b, $path, $recurse, $editor) = @_;
2237 my $pool = SVN::Pool->new;
8b8fc068 2238 $editor->set_path_strip($path);
2b27f6c8
EW
2239 my (@pc) = split m#/#, $path;
2240 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
2241 $recurse, $editor, $pool);
d81bf827 2242 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
2243
2244 # Since we can't rely on svn_ra_reparent being available, we'll
2245 # just have to do some magic with set_path to make it so
2246 # we only want a partial path.
2247 my $sp = '';
2248 my $final = join('/', @pc);
2249 while (@pc) {
2250 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2251 $sp .= '/' if length $sp;
2252 $sp .= shift @pc;
2253 }
2254 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2255
d81bf827 2256 my $new = ($rev_a == $rev_b);
2b27f6c8
EW
2257 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2258
d81bf827
EW
2259 $reporter->finish_report($pool);
2260 $pool->clear;
2261 $editor->{git_commit_ok};
2262}
2263
2b27f6c8
EW
2264# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2265# svn_ra_reparent didn't work before 1.4)
d81bf827
EW
2266sub gs_do_switch {
2267 my ($self, $rev_a, $rev_b, $path, $recurse, $url_b, $editor) = @_;
2268 my $pool = SVN::Pool->new;
2b27f6c8
EW
2269
2270 my $full_url = $self->{url};
2271 my $old_url = $full_url;
2272 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
2273 my ($ra, $reparented);
2274 if ($old_url ne $full_url) {
2275 if ($old_url !~ m#^svn(\+ssh)?://#) {
2276 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2277 $pool);
2278 $self->{url} = $full_url;
2279 $reparented = 1;
2280 } else {
2281 $ra = Git::SVN::Ra->new($full_url);
2282 }
2283 }
2284 $ra ||= $self;
2285 my $reporter = $ra->do_switch($rev_b, '',
2286 $recurse, $url_b, $editor, $pool);
d81bf827 2287 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 2288 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 2289 $reporter->finish_report($pool);
2b27f6c8 2290
5d3b7cd5
EW
2291 if ($reparented) {
2292 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2293 $self->{url} = $old_url;
2294 }
2b27f6c8 2295
d81bf827
EW
2296 $pool->clear;
2297 $editor->{git_commit_ok};
2298}
2299
0af9c9f9
EW
2300sub gs_fetch_loop_common {
2301 my ($self, $base, $head, @gs) = @_;
2302 my $inc = 1000;
2303 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
0af9c9f9
EW
2304 my @paths = @gs == 1 ? ($gs[0]->{path}) : ('');
2305 foreach my $gs (@gs) {
2306 if (my $last_commit = $gs->last_commit) {
2307 $gs->assert_index_clean($last_commit);
2308 }
0af9c9f9
EW
2309 }
2310 while (1) {
2311 my @revs;
f7c3fc4a
EW
2312 my $err;
2313 my $err_handler = $SVN::Error::handler;
2314 $SVN::Error::handler = sub {
2315 ($err) = @_;
2316 skip_unknown_revs($err);
2317 };
0af9c9f9
EW
2318 $self->get_log(\@paths, $min, $max, 0, 1, 1,
2319 sub { push @revs, [ dup_changed_paths($_[0]), $_[1] ]; });
f7c3fc4a
EW
2320 $SVN::Error::handler = $err_handler;
2321
0af9c9f9
EW
2322 if (! @revs && $err && $max >= $head) {
2323 print STDERR "Branch probably deleted:\n ",
2324 $err->expanded_message,
2325 "\nWill attempt to follow revisions ",
2326 "r$min .. r$max ",
2327 "committed before the deletion\n";
2328 @revs = map { [ undef, $_ ] } ($min .. $max);
2329 }
2330 foreach (@revs) {
2331 my ($paths, $r) = @$_;
2332 foreach my $gs (@gs) {
2333 if ($paths) {
28937057 2334 $gs->match_paths($paths) or next;
0af9c9f9
EW
2335 }
2336 next if defined $gs->rev_db_get($r);
2337 if (my $log_entry = $gs->do_fetch($paths, $r)) {
2338 $gs->do_git_commit($log_entry);
2339 }
2340 }
2341 }
2342 last if $max >= $head;
2343 $min = $max + 1;
2344 $max += $inc;
2345 $max = $head if ($max > $head);
2346 }
0af9c9f9
EW
2347}
2348
e6434f87
EW
2349sub minimize_url {
2350 my ($self) = @_;
2351 return $self->{url} if ($self->{url} eq $self->{repos_root});
2352 my $url = $self->{repos_root};
2353 my @components = split(m!/!, $self->{svn_path});
2354 my $c = '';
2355 do {
2356 $url .= "/$c" if length $c;
2357 eval { (ref $self)->new($url)->get_latest_revnum };
2358 } while ($@ && ($c = shift @components));
2359 $url;
2360}
2361
d81bf827
EW
2362sub can_do_switch {
2363 my $self = shift;
2364 unless (defined $can_do_switch) {
2365 my $pool = SVN::Pool->new;
2366 my $rep = eval {
2367 $self->do_switch(1, '', 0, $self->{url},
2368 SVN::Delta::Editor->new, $pool);
2369 };
2370 if ($@) {
2371 $can_do_switch = 0;
2372 } else {
2373 $rep->abort_report($pool);
2374 $can_do_switch = 1;
2375 }
2376 $pool->clear;
2377 }
2378 $can_do_switch;
2379}
2380
0af9c9f9
EW
2381sub skip_unknown_revs {
2382 my ($err) = @_;
2383 my $errno = $err->apr_err();
2384 # Maybe the branch we're tracking didn't
2385 # exist when the repo started, so it's
2386 # not an error if it doesn't, just continue
2387 #
2388 # Wonderfully consistent library, eh?
2389 # 160013 - svn:// and file://
2390 # 175002 - http(s)://
2391 # 175007 - http(s):// (this repo required authorization, too...)
2392 # More codes may be discovered later...
2393 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2394 return;
2395 }
2396 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2397}
2398
2399# svn_log_changed_path_t objects passed to get_log are likely to be
2400# overwritten even if only the refs are copied to an external variable,
2401# so we should dup the structures in their entirety. Using an externally
2402# passed pool (instead of our temporary and quickly cleared pool in
2403# Git::SVN::Ra) does not help matters at all...
2404sub dup_changed_paths {
2405 my ($paths) = @_;
2406 return undef unless $paths;
2407 my %ret;
2408 foreach my $p (keys %$paths) {
2409 my $i = $paths->{$p};
2410 my %s = map { $_ => $i->$_ }
2411 qw/copyfrom_path copyfrom_rev action/;
2412 $ret{$p} = \%s;
2413 }
2414 \%ret;
2415}
2416
f8c9d1d2
EW
2417package Git::SVN::Log;
2418use strict;
2419use warnings;
2420use POSIX qw/strftime/;
2421use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2422 %rusers $show_commit $incremental/;
2423my $l_fmt;
2424
2425sub cmt_showable {
2426 my ($c) = @_;
2427 return 1 if defined $c->{r};
2428 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2429 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
44320b9e
EW
2430 my @log = command(qw/cat-file commit/, $c->{c});
2431 shift @log while ($log[0] ne "\n");
2432 shift @log;
2433 @{$c->{l}} = grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
2434
2435 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 2436 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
2437 }
2438 return defined $c->{r};
2439}
2440
2441sub log_use_color {
2442 return 1 if $color;
2443 my ($dc, $dcvar);
2444 $dcvar = 'color.diff';
2445 $dc = `git-config --get $dcvar`;
2446 if ($dc eq '') {
2447 # nothing at all; fallback to "diff.color"
2448 $dcvar = 'diff.color';
2449 $dc = `git-config --get $dcvar`;
2450 }
2451 chomp($dc);
2452 if ($dc eq 'auto') {
2453 my $pc;
2454 $pc = `git-config --get color.pager`;
2455 if ($pc eq '') {
2456 # does not have it -- fallback to pager.color
2457 $pc = `git-config --bool --get pager.color`;
2458 }
2459 else {
2460 $pc = `git-config --bool --get color.pager`;
2461 if ($?) {
2462 $pc = 'false';
2463 }
2464 }
2465 chomp($pc);
2466 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2467 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2468 }
2469 return 0;
2470 }
2471 return 0 if $dc eq 'never';
2472 return 1 if $dc eq 'always';
2473 chomp($dc = `git-config --bool --get $dcvar`);
2474 return ($dc eq 'true');
2475}
2476
2477sub git_svn_log_cmd {
2478 my ($r_min, $r_max) = @_;
2479 my $gs = Git::SVN->_new;
2480 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2481 $gs->refname);
2482 push @cmd, '-r' unless $non_recursive;
2483 push @cmd, qw/--raw --name-status/ if $verbose;
2484 push @cmd, '--color' if log_use_color();
2485 return @cmd unless defined $r_max;
2486 if ($r_max == $r_min) {
2487 push @cmd, '--max-count=1';
2488 if (my $c = $gs->rev_db_get($r_max)) {
2489 push @cmd, $c;
2490 }
2491 } else {
2492 my ($c_min, $c_max);
2493 $c_max = $gs->rev_db_get($r_max);
2494 $c_min = $gs->rev_db_get($r_min);
2495 if (defined $c_min && defined $c_max) {
2496 if ($r_max > $r_max) {
2497 push @cmd, "$c_min..$c_max";
2498 } else {
2499 push @cmd, "$c_max..$c_min";
2500 }
2501 } elsif ($r_max > $r_min) {
2502 push @cmd, $c_max;
2503 } else {
2504 push @cmd, $c_min;
2505 }
2506 }
2507 return @cmd;
2508}
2509
2510# adapted from pager.c
2511sub config_pager {
2512 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2513 if (!defined $pager) {
2514 $pager = 'less';
2515 } elsif (length $pager == 0 || $pager eq 'cat') {
2516 $pager = undef;
2517 }
2518}
2519
2520sub run_pager {
2521 return unless -t *STDOUT;
2522 pipe my $rfd, my $wfd or return;
2523 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2524 if (!$pid) {
2525 open STDOUT, '>&', $wfd or
2526 ::fatal "Can't redirect to stdout: $!\n";
2527 return;
2528 }
2529 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2530 $ENV{LESS} ||= 'FRSX';
2531 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2532}
2533
21819a37
EW
2534sub tz_to_s_offset {
2535 my ($tz) = @_;
2536 $tz =~ s/(\d\d)$//;
2537 return ($1 * 60) + ($tz * 3600);
2538}
2539
f8c9d1d2
EW
2540sub get_author_info {
2541 my ($dest, $author, $t, $tz) = @_;
2542 $author =~ s/(?:^\s*|\s*$)//g;
2543 $dest->{a_raw} = $author;
2544 my $au;
1c8443b0 2545 if ($::_authors) {
f8c9d1d2
EW
2546 $au = $rusers{$author} || undef;
2547 }
2548 if (!$au) {
2549 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2550 }
2551 $dest->{t} = $t;
2552 $dest->{tz} = $tz;
2553 $dest->{a} = $au;
2554 # Date::Parse isn't in the standard Perl distro :(
2555 if ($tz =~ s/^\+//) {
21819a37 2556 $t += tz_to_s_offset($tz);
f8c9d1d2 2557 } elsif ($tz =~ s/^\-//) {
21819a37 2558 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
2559 }
2560 $dest->{t_utc} = $t;
2561}
2562
2563sub process_commit {
2564 my ($c, $r_min, $r_max, $defer) = @_;
2565 if (defined $r_min && defined $r_max) {
2566 if ($r_min == $c->{r} && $r_min == $r_max) {
2567 show_commit($c);
2568 return 0;
2569 }
2570 return 1 if $r_min == $r_max;
2571 if ($r_min < $r_max) {
2572 # we need to reverse the print order
2573 return 0 if (defined $limit && --$limit < 0);
2574 push @$defer, $c;
2575 return 1;
2576 }
2577 if ($r_min != $r_max) {
2578 return 1 if ($r_min < $c->{r});
2579 return 1 if ($r_max > $c->{r});
2580 }
2581 }
2582 return 0 if (defined $limit && --$limit < 0);
2583 show_commit($c);
2584 return 1;
2585}
2586
2587sub show_commit {
2588 my $c = shift;
2589 if ($oneline) {
2590 my $x = "\n";
2591 if (my $l = $c->{l}) {
2592 while ($l->[0] =~ /^\s*$/) { shift @$l }
2593 $x = $l->[0];
2594 }
2595 $l_fmt ||= 'A' . length($c->{r});
2596 print 'r',pack($l_fmt, $c->{r}),' | ';
2597 print "$c->{c} | " if $show_commit;
2598 print $x;
2599 } else {
2600 show_commit_normal($c);
2601 }
2602}
2603
2604sub show_commit_changed_paths {
2605 my ($c) = @_;
2606 return unless $c->{changed};
2607 print "Changed paths:\n", @{$c->{changed}};
2608}
2609
2610sub show_commit_normal {
2611 my ($c) = @_;
2612 print '-' x72, "\nr$c->{r} | ";
2613 print "$c->{c} | " if $show_commit;
2614 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2615 localtime($c->{t_utc})), ' | ';
2616 my $nr_line = 0;
2617
2618 if (my $l = $c->{l}) {
2619 while ($l->[$#$l] eq "\n" && $#$l > 0
2620 && $l->[($#$l - 1)] eq "\n") {
2621 pop @$l;
2622 }
2623 $nr_line = scalar @$l;
2624 if (!$nr_line) {
2625 print "1 line\n\n\n";
2626 } else {
2627 if ($nr_line == 1) {
2628 $nr_line = '1 line';
2629 } else {
2630 $nr_line .= ' lines';
2631 }
2632 print $nr_line, "\n";
2633 show_commit_changed_paths($c);
2634 print "\n";
2635 print $_ foreach @$l;
2636 }
2637 } else {
2638 print "1 line\n";
2639 show_commit_changed_paths($c);
2640 print "\n";
2641
2642 }
2643 foreach my $x (qw/raw diff/) {
2644 if ($c->{$x}) {
2645 print "\n";
2646 print $_ foreach @{$c->{$x}}
2647 }
2648 }
2649}
2650
2651sub cmd_show_log {
2652 my (@args) = @_;
2653 my ($r_min, $r_max);
2654 my $r_last = -1; # prevent dupes
2655 if (defined $TZ) {
2656 $ENV{TZ} = $TZ;
2657 } else {
2658 delete $ENV{TZ};
2659 }
2660 if (defined $::_revision) {
2661 if ($::_revision =~ /^(\d+):(\d+)$/) {
2662 ($r_min, $r_max) = ($1, $2);
2663 } elsif ($::_revision =~ /^\d+$/) {
2664 $r_min = $r_max = $::_revision;
2665 } else {
2666 ::fatal "-r$::_revision is not supported, use ",
2667 "standard \'git log\' arguments instead\n";
2668 }
2669 }
2670
2671 config_pager();
2672 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2673 my $log = command_output_pipe(@args);
2674 run_pager();
2675 my (@k, $c, $d);
2676 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2677 while (<$log>) {
2678 if (/^${esc_color}commit ($::sha1_short)/o) {
2679 my $cmt = $1;
2680 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2681 $r_last = $c->{r};
2682 process_commit($c, $r_min, $r_max, \@k) or
2683 goto out;
2684 }
2685 $d = undef;
2686 $c = { c => $cmt };
2687 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2688 get_author_info($c, $1, $2, $3);
2689 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2690 # ignore
2691 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2692 push @{$c->{raw}}, $_;
2693 } elsif (/^${esc_color}[ACRMDT]\t/) {
2694 # we could add $SVN->{svn_path} here, but that requires
2695 # remote access at the moment (repo_path_split)...
2696 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2697 push @{$c->{changed}}, $_;
2698 } elsif (/^${esc_color}diff /o) {
2699 $d = 1;
2700 push @{$c->{diff}}, $_;
2701 } elsif ($d) {
2702 push @{$c->{diff}}, $_;
2703 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2704 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2705 } elsif (s/^${esc_color} //o) {
2706 push @{$c->{l}}, $_;
2707 }
2708 }
2709 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2710 $r_last = $c->{r};
2711 process_commit($c, $r_min, $r_max, \@k);
2712 }
2713 if (@k) {
2714 my $swap = $r_max;
2715 $r_max = $r_min;
2716 $r_min = $swap;
2717 process_commit($_, $r_min, $r_max) foreach reverse @k;
2718 }
2719out:
c843c464 2720 close $log;
f8c9d1d2
EW
2721 print '-' x72,"\n" unless $incremental || $oneline;
2722}
2723
706587fc
EW
2724package Git::SVN::Migration;
2725# these version numbers do NOT correspond to actual version numbers
2726# of git nor git-svn. They are just relative.
2727#
2728# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2729#
2730# v1 layout: .git/$id/info/url, refs/remotes/$id
2731#
2732# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2733#
2734# v3 layout: .git/svn/$id, refs/remotes/$id
2735# - info/url may remain for backwards compatibility
2736# - this is what we migrate up to this layout automatically,
2737# - this will be used by git svn init on single branches
2738#
2739# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2740# - this is only created for newly multi-init-ed
2741# repositories. Similar in spirit to the
2742# --use-separate-remotes option in git-clone (now default)
2743# - we do not automatically migrate to this (following
2744# the example set by core git)
2745use strict;
2746use warnings;
2747use Carp qw/croak/;
2748use File::Path qw/mkpath/;
47e39c55
EW
2749use File::Basename qw/dirname basename/;
2750use vars qw/$_minimize/;
706587fc
EW
2751
2752sub migrate_from_v0 {
2753 my $git_dir = $ENV{GIT_DIR};
2754 return undef unless -d $git_dir;
2755 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2756 my $migrated = 0;
2757 while (<$fh>) {
2758 chomp;
2759 my ($id, $orig_ref) = ($_, $_);
2760 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2761 next unless -f "$git_dir/$id/info/url";
2762 my $new_ref = "refs/remotes/$id";
2763 if (::verify_ref("$new_ref^0")) {
2764 print STDERR "W: $orig_ref is probably an old ",
2765 "branch used by an ancient version of ",
2766 "git-svn.\n",
2767 "However, $new_ref also exists.\n",
2768 "We will not be able ",
2769 "to use this branch until this ",
2770 "ambiguity is resolved.\n";
2771 next;
2772 }
2773 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2774 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2775 command_noisy('update-ref', $new_ref, $orig_ref);
2776 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2777 $migrated++;
2778 }
2779 command_close_pipe($fh, $ctx);
2780 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2781 $migrated;
2782}
2783
2784sub migrate_from_v1 {
2785 my $git_dir = $ENV{GIT_DIR};
2786 my $migrated = 0;
2787 return $migrated unless -d $git_dir;
2788 my $svn_dir = "$git_dir/svn";
2789
2790 # just in case somebody used 'svn' as their $id at some point...
2791 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2792
2793 print STDERR "Migrating from a git-svn v1 layout...\n";
2794 mkpath([$svn_dir]);
2795 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2796 "$svn_dir\n\t(required for this version ",
2797 "($::VERSION) of git-svn) does not. exist\n";
2798 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2799 while (<$fh>) {
2800 my $x = $_;
2801 next unless $x =~ s#^refs/remotes/##;
2802 chomp $x;
2803 next unless -f "$git_dir/$x/info/url";
2804 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2805 next unless $u;
2806 my $dn = dirname("$git_dir/svn/$x");
2807 mkpath([$dn]) unless -d $dn;
2808 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2809 mkpath(["$git_dir/svn/svn"]);
2810 print STDERR " - $git_dir/$x/info => ",
2811 "$git_dir/svn/$x/info\n";
2812 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2813 croak "$!: $x";
2814 # don't worry too much about these, they probably
2815 # don't exist with repos this old (save for index,
2816 # and we can easily regenerate that)
2817 foreach my $f (qw/unhandled.log index .rev_db/) {
2818 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2819 }
2820 } else {
2821 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2822 rename "$git_dir/$x", "$git_dir/svn/$x" or
2823 croak "$!: $x";
2824 }
2825 $migrated++;
2826 }
2827 command_close_pipe($fh, $ctx);
2828 print STDERR "Done migrating from a git-svn v1 layout\n";
2829 $migrated;
2830}
2831
2832sub read_old_urls {
2833 my ($l_map, $pfx, $path) = @_;
2834 my @dir;
2835 foreach (<$path/*>) {
2836 if (-r "$_/info/url") {
2837 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2838 my $ref_id = $pfx . basename $_;
2839 my $url = ::file_to_s("$_/info/url");
2840 $l_map->{$ref_id} = $url;
2841 } elsif (-d $_) {
2842 push @dir, $_;
2843 }
2844 }
2845 foreach (@dir) {
2846 my $x = $_;
2847 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2848 read_old_urls($l_map, $x, $_);
2849 }
2850}
2851
2852sub migrate_from_v2 {
2853 my @cfg = command(qw/config -l/);
2854 return if grep /^svn-remote\..+\.url=/, @cfg;
2855 my %l_map;
2856 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2857 my $migrated = 0;
2858
2859 foreach my $ref_id (sort keys %l_map) {
47e39c55 2860 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
706587fc
EW
2861 $migrated++;
2862 }
2863 $migrated;
2864}
2865
47e39c55
EW
2866sub minimize_connections {
2867 my $r = Git::SVN::read_all_remotes();
2868 my $new_urls = {};
2869 my $root_repos = {};
2870 foreach my $repo_id (keys %$r) {
2871 my $url = $r->{$repo_id}->{url} or next;
2872 my $fetch = $r->{$repo_id}->{fetch} or next;
2873 my $ra = Git::SVN::Ra->new($url);
2874
2875 # skip existing cases where we already connect to the root
2876 if (($ra->{url} eq $ra->{repos_root}) ||
2877 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
2878 $repo_id)) {
2879 $root_repos->{$ra->{url}} = $repo_id;
2880 next;
2881 }
2882
2883 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
2884 my $root_path = $ra->{url};
2885 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
2886 foreach my $path (keys %$fetch) {
2887 my $ref_id = $fetch->{$path};
2888 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
2889
2890 # make sure we can read when connecting to
2891 # a higher level of a repository
2892 my ($last_rev, undef) = $gs->last_rev_commit;
2893 if (!defined $last_rev) {
2894 $last_rev = eval {
2895 $root_ra->get_latest_revnum;
2896 };
2897 next if $@;
2898 }
2899 my $new = $root_path;
2900 $new .= length $path ? "/$path" : '';
2901 eval {
2902 $root_ra->get_log([$new], $last_rev, $last_rev,
2903 0, 0, 1, sub { });
2904 };
2905 next if $@;
2906 $new_urls->{$ra->{repos_root}}->{$new} =
2907 { ref_id => $ref_id,
2908 old_repo_id => $repo_id,
2909 old_path => $path };
2910 }
2911 }
2912
2913 my @emptied;
2914 foreach my $url (keys %$new_urls) {
2915 # see if we can re-use an existing [svn-remote "repo_id"]
2916 # instead of creating a(n ugly) new section:
2917 my $repo_id = $root_repos->{$url} ||
2918 Git::SVN::sanitize_remote_name($url);
2919
2920 my $fetch = $new_urls->{$url};
2921 foreach my $path (keys %$fetch) {
2922 my $x = $fetch->{$path};
2923 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
2924 my $pfx = "svn-remote.$x->{old_repo_id}";
2925
2926 my $old_fetch = quotemeta("$x->{old_path}:".
2927 "refs/remotes/$x->{ref_id}");
8b8fc068 2928 command_noisy(qw/config --unset/,
47e39c55
EW
2929 "$pfx.fetch", '^'. $old_fetch . '$');
2930 delete $r->{$x->{old_repo_id}}->
2931 {fetch}->{$x->{old_path}};
2932 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 2933 command_noisy(qw/config --unset/,
47e39c55
EW
2934 "$pfx.url");
2935 push @emptied, $x->{old_repo_id}
2936 }
2937 }
2938 }
2939 if (@emptied) {
2940 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
2941 "$ENV{GIT_DIR}/config";
2942 print STDERR <<EOF;
2943The following [svn-remote] sections in your config file ($file) are empty
2944and can be safely removed:
2945EOF
2946 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
2947 }
2948}
2949
706587fc
EW
2950sub migration_check {
2951 migrate_from_v0();
2952 migrate_from_v1();
2953 migrate_from_v2();
47e39c55 2954 minimize_connections() if $_minimize;
706587fc
EW
2955}
2956
ef3cfaad
EW
2957package Git::IndexInfo;
2958use strict;
2959use warnings;
2960use Git qw/command_input_pipe command_close_pipe/;
2961
2962sub new {
2963 my ($class) = @_;
2964 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
2965 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
2966}
2967
2968sub remove {
2969 my ($self, $path) = @_;
2970 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
2971 return ++$self->{nr};
2972 }
2973 undef;
2974}
2975
2976sub update {
2977 my ($self, $mode, $hash, $path) = @_;
2978 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
2979 return ++$self->{nr};
2980 }
2981 undef;
2982}
2983
2984sub DESTROY {
2985 my ($self) = @_;
2986 command_close_pipe($self->{gui}, $self->{ctx});
2987}
2988
3397f9df
EW
2989__END__
2990
2991Data structures:
2992
44320b9e 2993$log_entry hashref as returned by libsvn_log_entry()
3397f9df 2994{
44320b9e 2995 log => 'whitespace-formatted log entry
3397f9df
EW
2996', # trailing newline is preserved
2997 revision => '8', # integer
2998 date => '2004-02-24T17:01:44.108345Z', # commit date
2999 author => 'committer name'
3000};
3001
6e8548cc
EW
3002
3003# this is generated by generate_diff();
3397f9df
EW
3004@mods = array of diff-index line hashes, each element represents one line
3005 of diff-index output
3006
3007diff-index line ($m hash)
3008{
3009 mode_a => first column of diff-index output, no leading ':',
3010 mode_b => second column of diff-index output,
3011 sha1_b => sha1sum of the final blob,
ac8e0b91 3012 chg => change type [MCRADT],
3397f9df
EW
3013 file_a => original file name of a file (iff chg is 'C' or 'R')
3014 file_b => new/current file name of a file (any chg)
3015}
3016;
a5e0cedc 3017
a00439ac
EW
3018# retval of read_url_paths{,_all}();
3019$l_map = {
3020 # repository root url
3021 'https://svn.musicpd.org' => {
3022 # repository path # GIT_SVN_ID
3023 'mpd/trunk' => 'trunk',
3024 'mpd/tags/0.11.5' => 'tags/0.11.5',
3025 },
3026}
3027
a5e0cedc
EW
3028Notes:
3029 I don't trust the each() function on unless I created %hash myself
3030 because the internal iterator may not have started at base.