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