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