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