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