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