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