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