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