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