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