]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
git-svn: reintroduce using a single get_log() to fetch
[thirdparty/git.git] / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
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
fbcc1737
EW
1115sub match_paths {
1116 my ($self, $paths, $r) = @_;
1117 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\/?/;
1118 if (grep /$self->{path_regex}/, keys %$paths) {
1119 return 1;
1120 }
1121 my $c = '';
1122 foreach (split m#/#, $self->{path}) {
1123 $c .= "/$_";
1124 next unless ($paths->{$c} && ($paths->{$c}->{action} eq 'A'));
1125 my @x = eval { $self->ra->get_dir($self->{path}, $r) };
1126 if (scalar @x == 3) {
1127 return 1;
1128 }
1129 }
1130 return 0;
1131}
1132
15710b6f
EW
1133sub find_parent_branch {
1134 my ($self, $paths, $rev) = @_;
9760adcc 1135 return undef unless $_follow_parent;
e5a0b240 1136 unless (defined $paths) {
c7eba716
EW
1137 my $err_handler = $SVN::Error::handler;
1138 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
1139 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1140 $paths =
1141 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 1142 $SVN::Error::handler = $err_handler;
e5a0b240
EW
1143 }
1144 return undef unless defined $paths;
15710b6f
EW
1145
1146 # look for a parent from another branch:
7f578c55
EW
1147 my @b_path_components = split m#/#, $self->rel_path;
1148 my @a_path_components;
1149 my $i;
1150 while (@b_path_components) {
1151 $i = $paths->{'/'.join('/', @b_path_components)};
1152 last if $i;
1153 unshift(@a_path_components, pop(@b_path_components));
1154 }
1155 goto not_found unless defined $i;
3ebe8df7 1156 my $branch_from = $i->{copyfrom_path} or goto not_found;
7f578c55
EW
1157 if (@a_path_components) {
1158 print STDERR "branch_from: $branch_from => ";
1159 $branch_from .= '/'.join('/', @a_path_components);
1160 print STDERR $branch_from, "\n";
1161 }
3ebe8df7 1162 my $r = $i->{copyfrom_rev};
15710b6f
EW
1163 my $repos_root = $self->ra->{repos_root};
1164 my $url = $self->ra->{url};
1165 my $new_url = $repos_root . $branch_from;
1166 print STDERR "Found possible branch point: ",
1167 "$new_url => ", $self->full_url, ", $r\n";
1168 $branch_from =~ s#^/##;
1169 my $remotes = read_all_remotes();
1170 my $gs;
1171 foreach my $repo_id (keys %$remotes) {
1172 my $u = $remotes->{$repo_id}->{url} or next;
1173 next if $url ne $u;
1174 my $fetch = $remotes->{$repo_id}->{fetch};
1175 foreach my $f (keys %$fetch) {
1176 next if $f ne $branch_from;
1177 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1178 last;
1179 }
1180 last if $gs;
1181 }
1182 unless ($gs) {
ce2a0f2f
EW
1183 my $ref_id = $self->{ref_id};
1184 $ref_id =~ s/\@\d+$//;
1185 $ref_id .= "\@$r";
15710b6f
EW
1186 # just grow a tail if we're not unique enough :x
1187 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1188 print STDERR "Initializing parent: $ref_id\n";
d8115c51 1189 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
15710b6f
EW
1190 }
1191 my ($r0, $parent) = $gs->find_rev_before($r, 1);
9760adcc 1192 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
3ebe8df7 1193 $gs->fetch(0, $r);
15710b6f
EW
1194 ($r0, $parent) = $gs->last_rev_commit;
1195 }
ef70de96 1196 if (defined $r0 && defined $parent) {
15710b6f 1197 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
a2003abc 1198 $self->assert_index_clean($parent);
15710b6f
EW
1199 my $ed;
1200 if ($self->ra->can_do_switch) {
8b8fc068 1201 print STDERR "Following parent with do_switch\n";
15710b6f 1202 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1203 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1204 # at the moment), so we can't rely on it
1205 $self->{last_commit} = $parent;
1206 $ed = SVN::Git::Fetcher->new($self);
8a603774 1207 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
1208 $self->full_url, $ed)
1209 or die "SVN connection failed somewhere...\n";
1210 } else {
8b8fc068 1211 print STDERR "Following parent with do_update\n";
15710b6f 1212 $ed = SVN::Git::Fetcher->new($self);
8a603774 1213 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
1214 or die "SVN connection failed somewhere...\n";
1215 }
f7c3fc4a 1216 print STDERR "Successfully followed parent\n";
15710b6f
EW
1217 return $self->make_log_entry($rev, [$parent], $ed);
1218 }
9bf04637 1219not_found:
7f578c55 1220 print STDERR "Branch parent for path: '/",
3ebe8df7
EW
1221 $self->rel_path, "' @ r$rev not found:\n";
1222 return undef unless $paths;
1223 print STDERR "Changed paths:\n";
1224 foreach my $x (sort keys %$paths) {
1225 my $p = $paths->{$x};
1226 print STDERR "\t$p->{action}\t$x";
1227 if ($p->{copyfrom_path}) {
1228 print STDERR "(from $p->{copyfrom_path}: ",
1229 "$p->{copyfrom_rev})";
1230 }
1231 print STDERR "\n";
1232 }
1233 print STDERR '-'x72, "\n";
15710b6f
EW
1234 return undef;
1235}
1236
9b981fc6 1237sub do_fetch {
706587fc 1238 my ($self, $paths, $rev) = @_;
15710b6f 1239 my $ed;
9b981fc6
EW
1240 my ($last_rev, @parents);
1241 if ($self->{last_commit}) {
15710b6f 1242 $ed = SVN::Git::Fetcher->new($self);
9b981fc6
EW
1243 $last_rev = $self->{last_rev};
1244 $ed->{c} = $self->{last_commit};
1245 @parents = ($self->{last_commit});
1246 } else {
1247 $last_rev = $rev;
15710b6f
EW
1248 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1249 return $log_entry;
1250 }
1251 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1252 }
8a603774 1253 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
1254 die "SVN connection failed somewhere...\n";
1255 }
1256 $self->make_log_entry($rev, \@parents, $ed);
1257}
1258
97f6987a
EW
1259sub get_untracked {
1260 my ($self, $ed) = @_;
1261 my @out;
1262 my $h = $ed->{empty};
9b981fc6
EW
1263 foreach (sort keys %$h) {
1264 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1265 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1266 warn "W: $act: $_\n";
1267 }
1268 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1269 $h = $ed->{$t} or next;
9b981fc6
EW
1270 foreach my $path (sort keys %$h) {
1271 my $ppath = $path eq '' ? '.' : $path;
1272 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1273 next if $SKIP_PROP{$prop};
9b981fc6 1274 my $v = $h->{$path}->{$prop};
97f6987a
EW
1275 my $t_ppath_prop = "$t: " .
1276 uri_encode($ppath) . ' ' .
1277 uri_encode($prop);
9b981fc6 1278 if (defined $v) {
97f6987a
EW
1279 push @out, " +$t_ppath_prop " .
1280 uri_encode($v);
9b981fc6 1281 } else {
97f6987a 1282 push @out, " -$t_ppath_prop";
9b981fc6
EW
1283 }
1284 }
1285 }
1286 }
1287 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1288 $h = $ed->{$t} or next;
9b981fc6
EW
1289 foreach my $parent (sort keys %$h) {
1290 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1291 push @out, " $t: " .
1292 uri_encode("$parent/$path");
9b981fc6
EW
1293 warn "W: $t: $parent/$path ",
1294 "Insufficient permissions?\n";
1295 }
1296 }
1297 }
97f6987a 1298 \@out;
9b981fc6
EW
1299}
1300
1c8443b0
EW
1301sub parse_svn_date {
1302 my $date = shift || return '+0000 1970-01-01 00:00:00';
1303 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1304 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1305 croak "Unable to parse date: $date\n";
1306 "+0000 $Y-$m-$d $H:$M:$S";
1307}
1308
1309sub check_author {
1310 my ($author) = @_;
1311 if (!defined $author || length $author == 0) {
1312 $author = '(no author)';
1313 }
1314 if (defined $::_authors && ! defined $::users{$author}) {
1315 die "Author: $author not defined in $::_authors file\n";
1316 }
1317 $author;
1318}
1319
9b981fc6 1320sub make_log_entry {
97f6987a
EW
1321 my ($self, $rev, $parents, $ed) = @_;
1322 my $untracked = $self->get_untracked($ed);
1323
9b981fc6 1324 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1325 print $un "r$rev\n" or croak $!;
1326 print $un $_, "\n" foreach @$untracked;
1327 my %log_entry = ( parents => $parents || [], revision => $rev,
1328 log => '');
fbcc1737
EW
1329
1330 my $logged = delete $self->{logged_rev_props};
1331 if (!$logged || $self->{-want_extra_revprops}) {
1332 my $rp = $self->ra->rev_proplist($rev);
1333 foreach (sort keys %$rp) {
1334 my $v = $rp->{$_};
1335 if (/^svn:(author|date|log)$/) {
1336 $log_entry{$1} = $v;
1337 } else {
1338 print $un " rev_prop: ", uri_encode($_), ' ',
1339 uri_encode($v), "\n";
1340 }
9b981fc6 1341 }
fbcc1737
EW
1342 } else {
1343 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
1344 }
1345 close $un or croak $!;
97f6987a 1346
9b981fc6
EW
1347 $log_entry{date} = parse_svn_date($log_entry{date});
1348 $log_entry{author} = check_author($log_entry{author});
1349 $log_entry{log} .= "\n";
1350 \%log_entry;
1351}
1352
1353sub fetch {
3ebe8df7 1354 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1355 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1356 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
9b981fc6 1357 return if ($base > $head);
0af9c9f9 1358 $self->ra->gs_fetch_loop_common($base, $head, $self);
9b981fc6
EW
1359}
1360
1361sub set_tree_cb {
1362 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1363 # TODO: enable and test optimized commits:
1364 if (0 && $rev == ($self->{last_rev} + 1)) {
1365 $log_entry->{revision} = $rev;
1366 $log_entry->{author} = $author;
1367 $self->do_git_commit($log_entry, "$rev=$tree");
1368 } else {
0af9c9f9
EW
1369 $self->{inject_parents} = { $rev => $tree };
1370 $self->fetch(undef, undef);
9b981fc6
EW
1371 }
1372}
1373
1374sub set_tree {
1375 my ($self, $tree) = (shift, shift);
1ce255dc 1376 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1377 unless ($self->{last_rev}) {
1378 fatal("Must have an existing revision to commit\n");
1379 }
61395354
EW
1380 my %ed_opts = ( r => $self->{last_rev},
1381 log => $log_entry->{log},
1382 ra => $self->ra,
1383 tree_a => $self->{last_commit},
1384 tree_b => $tree,
1385 editor_cb => sub {
1386 $self->set_tree_cb($log_entry, $tree, @_) },
1387 svn_path => $self->{path} );
1388 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1389 print "No changes\nr$self->{last_rev} = $tree\n";
1390 }
9b981fc6
EW
1391}
1392
f0ecca10
EW
1393sub rebuild {
1394 my ($self) = @_;
1395 print "Rebuilding $self->{db_path} ...\n";
1396 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1397 my $latest;
1398 my $full_url = $self->full_url;
1399 my $svn_uuid;
1400 while (<$rev_list>) {
1401 chomp;
1402 my $c = $_;
1403 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1404 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1405
1406 # ignore merges (from set-tree)
1407 next if (!defined $rev || !$uuid);
1408
1409 # if we merged or otherwise started elsewhere, this is
1410 # how we break out of it
1411 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1412 ($full_url && $url && ($url ne $full_url))) {
1413 next;
1414 }
1415 $latest ||= $rev;
1416 $svn_uuid ||= $uuid;
1417
1418 $self->rev_db_set($rev, $c);
1419 print "r$rev = $c\n";
1420 }
1421 command_close_pipe($rev_list, $ctx);
1422 print "Done rebuilding $self->{db_path}\n";
1423}
1424
9b981fc6
EW
1425# rev_db:
1426# Tie::File seems to be prone to offset errors if revisions get sparse,
1427# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1428# one of my favorite modules is out :< Next up would be one of the DBM
1429# modules, but I'm not sure which is most portable... So I'll just
1430# go with something that's plain-text, but still capable of
1431# being randomly accessed. So here's my ultra-simple fixed-width
1432# database. All records are 40 characters + "\n", so it's easy to seek
1433# to a revision: (41 * rev) is the byte offset.
1434# A record of 40 0s denotes an empty revision.
1435# And yes, it's still pretty fast (faster than Tie::File).
373274f9 1436# These files are disposable unless --no-metadata is set
9b981fc6
EW
1437
1438sub rev_db_set {
373274f9 1439 my ($self, $rev, $commit, $update_ref) = @_;
9b981fc6 1440 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
373274f9
EW
1441 my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1442 my $sig;
1443 if ($update_ref) {
1444 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1445 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1446 }
1447 $LOCKFILES{$db_lock} = 1;
1448 if ($_no_metadata) {
1449 copy($db, $db_lock) or die "rev_db_set(@_): ",
1450 "Failed to copy: ",
1451 "$db => $db_lock ($!)\n";
1452 } else {
1453 rename $db, $db_lock or die "rev_db_set(@_): ",
1454 "Failed to rename: ",
1455 "$db => $db_lock ($!)\n";
1456 }
1457 open my $fh, '+<', $db_lock or croak $!;
9b981fc6
EW
1458 my $offset = $rev * 41;
1459 # assume that append is the common case:
1460 seek $fh, 0, 2 or croak $!;
1461 my $pos = tell $fh;
1462 if ($pos < $offset) {
47a0b75e
EW
1463 for (1 .. (($offset - $pos) / 41)) {
1464 print $fh (('0' x 40),"\n") or croak $!;
1465 }
9b981fc6
EW
1466 }
1467 seek $fh, $offset, 0 or croak $!;
1468 print $fh $commit,"\n" or croak $!;
1469 close $fh or croak $!;
373274f9
EW
1470 if ($update_ref) {
1471 command_noisy('update-ref', '-m', "r$rev",
1472 $self->refname, $commit);
1473 }
1474 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1475 "$db_lock => $db ($!)\n";
1476 delete $LOCKFILES{$db_lock};
1477 if ($update_ref) {
1478 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1479 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1480 kill $sig, $$ if defined $sig;
1481 }
9b981fc6
EW
1482}
1483
9c93fee5
EW
1484sub rev_db_max {
1485 my ($self) = @_;
1486 my @stat = stat $self->{db_path} or
1487 die "Couldn't stat $self->{db_path}: $!\n";
1488 ($stat[7] % 41) == 0 or
1489 die "$self->{db_path} inconsistent size:$stat[7]\n";
1490 my $max = $stat[7] / 41;
1491 (($max > 0) ? $max - 1 : 0);
1492}
1493
9b981fc6
EW
1494sub rev_db_get {
1495 my ($self, $rev) = @_;
1496 my $ret;
1497 my $offset = $rev * 41;
1498 open my $fh, '<', $self->{db_path} or croak $!;
ce4b4af7
EW
1499 if (sysseek($fh, $offset, 0) == $offset) {
1500 my $read = sysread($fh, $ret, 40);
1501 $ret = undef if ($read != 40 || $ret eq ('0'x40));
9b981fc6
EW
1502 }
1503 close $fh or croak $!;
1504 $ret;
1505}
1506
15710b6f
EW
1507sub find_rev_before {
1508 my ($self, $rev, $eq_ok) = @_;
1509 --$rev unless $eq_ok;
1510 while ($rev > 0) {
1511 if (my $c = $self->rev_db_get($rev)) {
1512 return ($rev, $c);
1513 }
1514 --$rev;
1515 }
1516 return (undef, undef);
1517}
1518
9b981fc6 1519sub _new {
706587fc
EW
1520 my ($class, $repo_id, $ref_id, $path) = @_;
1521 unless (defined $repo_id && length $repo_id) {
1522 $repo_id = $Git::SVN::default_repo_id;
1523 }
1524 unless (defined $ref_id && length $ref_id) {
8b8fc068 1525 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
1526 }
1527 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1528 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1529 $_[3] = $path = '' unless (defined $path);
8b8fc068
EW
1530 mkpath([$dir]);
1531 unless (-f "$dir/.rev_db") {
1532 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1533 close $fh or croak $!;
1534 }
706587fc
EW
1535 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1536 path => $path,
1537 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
9b981fc6
EW
1538}
1539
1c8443b0
EW
1540sub uri_encode {
1541 my ($f) = @_;
1542 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1543 $f
1544}
9b981fc6 1545
d976acfd
EW
1546package Git::SVN::Prompt;
1547use strict;
1548use warnings;
1549require SVN::Core;
1550use vars qw/$_no_auth_cache $_username/;
1551
1552sub simple {
30d055aa
EW
1553 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1554 $may_save = undef if $_no_auth_cache;
1555 $default_username = $_username if defined $_username;
1556 if (defined $default_username && length $default_username) {
1557 if (defined $realm && length $realm) {
6f729591
EW
1558 print STDERR "Authentication realm: $realm\n";
1559 STDERR->flush;
30d055aa
EW
1560 }
1561 $cred->username($default_username);
1562 } else {
d976acfd 1563 username($cred, $realm, $may_save, $pool);
30d055aa
EW
1564 }
1565 $cred->password(_read_password("Password for '" .
1566 $cred->username . "': ", $realm));
1567 $cred->may_save($may_save);
1568 $SVN::_Core::SVN_NO_ERROR;
1569}
1570
d976acfd 1571sub ssl_server_trust {
30d055aa
EW
1572 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1573 $may_save = undef if $_no_auth_cache;
6f729591 1574 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 1575 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 1576 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
1577 "authority. Use the\n",
1578 " fingerprint to validate the certificate manually!\n";
1579 }
1580 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 1581 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
1582 }
1583 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 1584 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
1585 }
1586 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 1587 print STDERR " - The certificate has expired.\n";
30d055aa
EW
1588 }
1589 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 1590 print STDERR " - The certificate has an unknown error.\n";
30d055aa 1591 }
6f729591
EW
1592 printf STDERR
1593 "Certificate information:\n".
30d055aa
EW
1594 " - Hostname: %s\n".
1595 " - Valid: from %s until %s\n".
1596 " - Issuer: %s\n".
1597 " - Fingerprint: %s\n",
1598 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 1599 issuer_dname fingerprint);
30d055aa
EW
1600 my $choice;
1601prompt:
6f729591 1602 print STDERR $may_save ?
30d055aa
EW
1603 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1604 "(R)eject or accept (t)emporarily? ";
6f729591 1605 STDERR->flush;
30d055aa
EW
1606 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1607 if ($choice =~ /^t$/i) {
1608 $cred->may_save(undef);
1609 } elsif ($choice =~ /^r$/i) {
1610 return -1;
1611 } elsif ($may_save && $choice =~ /^p$/i) {
1612 $cred->may_save($may_save);
1613 } else {
1614 goto prompt;
1615 }
1616 $cred->accepted_failures($failures);
1617 $SVN::_Core::SVN_NO_ERROR;
1618}
1619
d976acfd 1620sub ssl_client_cert {
30d055aa
EW
1621 my ($cred, $realm, $may_save, $pool) = @_;
1622 $may_save = undef if $_no_auth_cache;
6f729591
EW
1623 print STDERR "Client certificate filename: ";
1624 STDERR->flush;
30d055aa
EW
1625 chomp(my $filename = <STDIN>);
1626 $cred->cert_file($filename);
1627 $cred->may_save($may_save);
1628 $SVN::_Core::SVN_NO_ERROR;
1629}
1630
d976acfd 1631sub ssl_client_cert_pw {
30d055aa
EW
1632 my ($cred, $realm, $may_save, $pool) = @_;
1633 $may_save = undef if $_no_auth_cache;
1634 $cred->password(_read_password("Password: ", $realm));
1635 $cred->may_save($may_save);
1636 $SVN::_Core::SVN_NO_ERROR;
1637}
1638
d976acfd 1639sub username {
30d055aa
EW
1640 my ($cred, $realm, $may_save, $pool) = @_;
1641 $may_save = undef if $_no_auth_cache;
1642 if (defined $realm && length $realm) {
6f729591 1643 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
1644 }
1645 my $username;
1646 if (defined $_username) {
1647 $username = $_username;
1648 } else {
6f729591
EW
1649 print STDERR "Username: ";
1650 STDERR->flush;
30d055aa
EW
1651 chomp($username = <STDIN>);
1652 }
1653 $cred->username($username);
1654 $cred->may_save($may_save);
1655 $SVN::_Core::SVN_NO_ERROR;
1656}
1657
1658sub _read_password {
1659 my ($prompt, $realm) = @_;
6f729591
EW
1660 print STDERR $prompt;
1661 STDERR->flush;
30d055aa
EW
1662 require Term::ReadKey;
1663 Term::ReadKey::ReadMode('noecho');
1664 my $password = '';
1665 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1666 last if $key =~ /[\012\015]/; # \n\r
1667 $password .= $key;
1668 }
1669 Term::ReadKey::ReadMode('restore');
6f729591
EW
1670 print STDERR "\n";
1671 STDERR->flush;
30d055aa
EW
1672 $password;
1673}
1674
d976acfd
EW
1675package main;
1676
b9c85187
EW
1677{
1678 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1679 $SVN::Node::dir.$SVN::Node::unknown.
1680 $SVN::Node::none.$SVN::Node::file.
1681 $SVN::Node::dir.$SVN::Node::unknown.
1682 $SVN::Auth::SSL::CNMISMATCH.
1683 $SVN::Auth::SSL::NOTYETVALID.
1684 $SVN::Auth::SSL::EXPIRED.
1685 $SVN::Auth::SSL::UNKNOWNCA.
1686 $SVN::Auth::SSL::OTHER;
1687}
1688
27a1a801
EW
1689package SVN::Git::Fetcher;
1690use vars qw/@ISA/;
1691use strict;
1692use warnings;
1693use Carp qw/croak/;
1694use IO::File qw//;
90c1b15d 1695use Digest::MD5;
27a1a801
EW
1696
1697# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1698sub new {
1699 my ($class, $git_svn) = @_;
1700 my $self = SVN::Delta::Editor->new;
1701 bless $self, $class;
1c8443b0 1702 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
1703 $self->{empty} = {};
1704 $self->{dir_prop} = {};
1705 $self->{file_prop} = {};
1706 $self->{absent_dir} = {};
1707 $self->{absent_file} = {};
ef3cfaad 1708 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
1709 $self;
1710}
1711
8b8fc068
EW
1712sub set_path_strip {
1713 my ($self, $path) = @_;
1714 $self->{path_strip} = qr/^\Q$path\E\/?/;
1715}
1716
d2a9a87b
EW
1717sub open_root {
1718 { path => '' };
1719}
1720
1721sub open_directory {
1722 my ($self, $path, $pb, $rev) = @_;
1723 { path => $path };
1724}
1725
706587fc
EW
1726sub git_path {
1727 my ($self, $path) = @_;
2b27f6c8
EW
1728 if ($self->{path_strip}) {
1729 $path =~ s!$self->{path_strip}!! or
1730 die "Failed to strip path '$path' ($self->{path_strip})\n";
1731 }
706587fc
EW
1732 $path;
1733}
1734
27a1a801
EW
1735sub delete_entry {
1736 my ($self, $path, $rev, $pb) = @_;
4a87db0e 1737
706587fc 1738 my $gpath = $self->git_path($path);
8a603774
EW
1739 return undef if ($gpath eq '');
1740
4a87db0e 1741 # remove entire directories.
706587fc 1742 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
1743 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1744 -r --name-only -z/,
706587fc 1745 $self->{c}, '--', $gpath);
4a87db0e
EW
1746 local $/ = "\0";
1747 while (<$ls>) {
ef3cfaad
EW
1748 chomp;
1749 $self->{gii}->remove($_);
4a87db0e
EW
1750 print "\tD\t$_\n" unless $self->{q};
1751 }
706587fc 1752 print "\tD\t$gpath/\n" unless $self->{q};
4a87db0e
EW
1753 command_close_pipe($ls, $ctx);
1754 $self->{empty}->{$path} = 0
1755 } else {
ef3cfaad 1756 $self->{gii}->remove($gpath);
706587fc 1757 print "\tD\t$gpath\n" unless $self->{q};
4a87db0e 1758 }
27a1a801
EW
1759 undef;
1760}
1761
1762sub open_file {
1763 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
1764 my $gpath = $self->git_path($path);
1765 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 1766 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
1767 unless (defined $mode && defined $blob) {
1768 die "$path was not found in commit $self->{c} (r$rev)\n";
1769 }
27a1a801 1770 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 1771 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
1772}
1773
1774sub add_file {
1775 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
1776 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1777 delete $self->{empty}->{$dir};
27a1a801 1778 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 1779 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
1780}
1781
d2a9a87b
EW
1782sub add_directory {
1783 my ($self, $path, $cp_path, $cp_rev) = @_;
1784 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1785 delete $self->{empty}->{$dir};
1786 $self->{empty}->{$path} = 1;
1787 { path => $path };
1788}
1789
1790sub change_dir_prop {
1791 my ($self, $db, $prop, $value) = @_;
1792 $self->{dir_prop}->{$db->{path}} ||= {};
1793 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1794 undef;
1795}
1796
1797sub absent_directory {
1798 my ($self, $path, $pb) = @_;
1799 $self->{absent_dir}->{$pb->{path}} ||= [];
1800 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1801 undef;
1802}
1803
1804sub absent_file {
1805 my ($self, $path, $pb) = @_;
1806 $self->{absent_file}->{$pb->{path}} ||= [];
1807 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1808 undef;
1809}
1810
27a1a801
EW
1811sub change_file_prop {
1812 my ($self, $fb, $prop, $value) = @_;
1813 if ($prop eq 'svn:executable') {
1814 if ($fb->{mode_b} != 120000) {
1815 $fb->{mode_b} = defined $value ? 100755 : 100644;
1816 }
1817 } elsif ($prop eq 'svn:special') {
1818 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
1819 } else {
1820 $self->{file_prop}->{$fb->{path}} ||= {};
1821 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
1822 }
1823 undef;
1824}
1825
1826sub apply_textdelta {
1827 my ($self, $fb, $exp) = @_;
1828 my $fh = IO::File->new_tmpfile;
1829 $fh->autoflush(1);
1830 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1831 # (but $base does not,) so dup() it for reading in close_file
1832 open my $dup, '<&', $fh or croak $!;
1833 my $base = IO::File->new_tmpfile;
1834 $base->autoflush(1);
1835 if ($fb->{blob}) {
1836 defined (my $pid = fork) or croak $!;
1837 if (!$pid) {
1838 open STDOUT, '>&', $base or croak $!;
1839 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1840 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1841 }
1842 waitpid $pid, 0;
1843 croak $? if $?;
1844
1845 if (defined $exp) {
1846 seek $base, 0, 0 or croak $!;
1847 my $md5 = Digest::MD5->new;
1848 $md5->addfile($base);
1849 my $got = $md5->hexdigest;
1850 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1851 "expected: $exp\n",
1852 " got: $got\n" if ($got ne $exp);
1853 }
1854 }
1855 seek $base, 0, 0 or croak $!;
1856 $fb->{fh} = $dup;
1857 $fb->{base} = $base;
1858 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1859}
1860
1861sub close_file {
1862 my ($self, $fb, $exp) = @_;
1863 my $hash;
706587fc 1864 my $path = $self->git_path($fb->{path});
27a1a801
EW
1865 if (my $fh = $fb->{fh}) {
1866 seek($fh, 0, 0) or croak $!;
1867 my $md5 = Digest::MD5->new;
1868 $md5->addfile($fh);
1869 my $got = $md5->hexdigest;
1870 die "Checksum mismatch: $path\n",
1871 "expected: $exp\n got: $got\n" if ($got ne $exp);
1872 seek($fh, 0, 0) or croak $!;
1873 if ($fb->{mode_b} == 120000) {
1874 read($fh, my $buf, 5) == 5 or croak $!;
1875 $buf eq 'link ' or die "$path has mode 120000",
1876 "but is not a link\n";
1877 }
1878 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1879 if (!$pid) {
1880 open STDIN, '<&', $fh or croak $!;
1881 exec qw/git-hash-object -w --stdin/ or croak $!;
1882 }
1883 chomp($hash = do { local $/; <$out> });
1884 close $out or croak $!;
1885 close $fh or croak $!;
1886 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1887 close $fb->{base} or croak $!;
1888 } else {
1889 $hash = $fb->{blob} or die "no blob information\n";
1890 }
1891 $fb->{pool}->clear;
ef3cfaad 1892 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
0864e3ba 1893 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $self->{q};
27a1a801
EW
1894 undef;
1895}
1896
1897sub abort_edit {
1898 my $self = shift;
ef3cfaad
EW
1899 $self->{nr} = $self->{gii}->{nr};
1900 delete $self->{gii};
27a1a801
EW
1901 $self->SUPER::abort_edit(@_);
1902}
1903
1904sub close_edit {
1905 my $self = shift;
dad73c0b 1906 $self->{git_commit_ok} = 1;
ef3cfaad
EW
1907 $self->{nr} = $self->{gii}->{nr};
1908 delete $self->{gii};
27a1a801
EW
1909 $self->SUPER::close_edit(@_);
1910}
1a82e793 1911
a5e0cedc 1912package SVN::Git::Editor;
24e22aa8 1913use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
1914use strict;
1915use warnings;
1916use Carp qw/croak/;
1917use IO::File;
90c1b15d 1918use Digest::MD5;
a5e0cedc
EW
1919
1920sub new {
61395354
EW
1921 my ($class, $opts) = @_;
1922 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1923 die "$_ required!\n" unless (defined $opts->{$_});
1924 }
1925
1926 my $pool = SVN::Pool->new;
1927 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1928 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1929 $opts->{r}, $mods);
1930
1931 # $opts->{ra} functions should not be used after this:
1932 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
1933 $opts->{editor_cb}, $pool);
1934 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 1935 bless $self, $class;
61395354
EW
1936 foreach (qw/svn_path r tree_a tree_b/) {
1937 $self->{$_} = $opts->{$_};
a5e0cedc 1938 }
61395354
EW
1939 $self->{url} = $opts->{ra}->{url};
1940 $self->{mods} = $mods;
1941 $self->{types} = $types;
1942 $self->{pool} = $pool;
a5e0cedc
EW
1943 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1944 $self->{rm} = { };
d3a840dc
EW
1945 $self->{path_prefix} = length $self->{svn_path} ?
1946 "$self->{svn_path}/" : '';
a5e0cedc
EW
1947 return $self;
1948}
1949
61395354
EW
1950sub generate_diff {
1951 my ($tree_a, $tree_b) = @_;
1952 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
1953 if ($_cp_similarity) {
1954 push @diff_tree, "-C$_cp_similarity";
61395354
EW
1955 } else {
1956 push @diff_tree, '-C';
1957 }
24e22aa8
EW
1958 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1959 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
1960 push @diff_tree, $tree_a, $tree_b;
1961 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1962 local $/ = "\0";
1963 my $state = 'meta';
1964 my @mods;
1965 while (<$diff_fh>) {
1966 chomp $_; # this gets rid of the trailing "\0"
1967 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1968 $::sha1\s($::sha1)\s
1969 ([MTCRAD])\d*$/xo) {
1970 push @mods, { mode_a => $1, mode_b => $2,
1971 sha1_b => $3, chg => $4 };
1972 if ($4 =~ /^(?:C|R)$/) {
1973 $state = 'file_a';
1974 } else {
1975 $state = 'file_b';
1976 }
1977 } elsif ($state eq 'file_a') {
1978 my $x = $mods[$#mods] or croak "Empty array\n";
1979 if ($x->{chg} !~ /^(?:C|R)$/) {
1980 croak "Error parsing $_, $x->{chg}\n";
1981 }
1982 $x->{file_a} = $_;
1983 $state = 'file_b';
1984 } elsif ($state eq 'file_b') {
1985 my $x = $mods[$#mods] or croak "Empty array\n";
1986 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
1987 croak "Error parsing $_, $x->{chg}\n";
1988 }
1989 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
1990 croak "Error parsing $_, $x->{chg}\n";
1991 }
1992 $x->{file_b} = $_;
1993 $state = 'meta';
1994 } else {
1995 croak "Error parsing $_\n";
1996 }
1997 }
1998 command_close_pipe($diff_fh, $ctx);
1999 \@mods;
2000}
2001
2002sub check_diff_paths {
2003 my ($ra, $pfx, $rev, $mods) = @_;
2004 my %types;
2005 $pfx .= '/' if length $pfx;
2006
2007 sub type_diff_paths {
2008 my ($ra, $types, $path, $rev) = @_;
2009 my @p = split m#/+#, $path;
2010 my $c = shift @p;
2011 unless (defined $types->{$c}) {
2012 $types->{$c} = $ra->check_path($c, $rev);
2013 }
2014 while (@p) {
2015 $c .= '/' . shift @p;
2016 next if defined $types->{$c};
2017 $types->{$c} = $ra->check_path($c, $rev);
2018 }
2019 }
2020
2021 foreach my $m (@$mods) {
2022 foreach my $f (qw/file_a file_b/) {
2023 next unless defined $m->{$f};
2024 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2025 if (length $pfx.$dir && ! defined $types{$dir}) {
2026 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2027 }
2028 }
2029 }
2030 \%types;
2031}
2032
a5e0cedc
EW
2033sub split_path {
2034 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2035}
2036
2037sub repo_path {
d3a840dc
EW
2038 my ($self, $path) = @_;
2039 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
2040}
2041
2042sub url_path {
2043 my ($self, $path) = @_;
6e8548cc 2044 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
2045}
2046
2047sub rmdirs {
61395354 2048 my ($self) = @_;
a5e0cedc
EW
2049 my $rm = $self->{rm};
2050 delete $rm->{''}; # we never delete the url we're tracking
2051 return unless %$rm;
2052
2053 foreach (keys %$rm) {
2054 my @d = split m#/#, $_;
2055 my $c = shift @d;
2056 $rm->{$c} = 1;
2057 while (@d) {
2058 $c .= '/' . shift @d;
2059 $rm->{$c} = 1;
2060 }
2061 }
2062 delete $rm->{$self->{svn_path}};
2063 delete $rm->{''}; # we never delete the url we're tracking
2064 return unless %$rm;
2065
61395354
EW
2066 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2067 $self->{tree_b});
a5e0cedc
EW
2068 local $/ = "\0";
2069 while (<$fh>) {
2070 chomp;
747fa12c 2071 my @dn = split m#/#, $_;
c07eee1f
EW
2072 while (pop @dn) {
2073 delete $rm->{join '/', @dn};
2074 }
2075 unless (%$rm) {
22600a25 2076 close $fh;
c07eee1f
EW
2077 return;
2078 }
a5e0cedc 2079 }
aef4e921 2080 command_close_pipe($fh, $ctx);
c07eee1f 2081
a5e0cedc
EW
2082 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2083 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2084 $self->close_directory($bat->{$d}, $p);
2085 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 2086 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
2087 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2088 delete $bat->{$d};
2089 }
2090}
2091
2092sub open_or_add_dir {
2093 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
2094 my $t = $self->{types}->{$full_path};
2095 if (!defined $t) {
2096 die "$full_path not known in r$self->{r} or we have a bug!\n";
2097 }
a5e0cedc
EW
2098 if ($t == $SVN::Node::none) {
2099 return $self->add_directory($full_path, $baton,
2100 undef, -1, $self->{pool});
2101 } elsif ($t == $SVN::Node::dir) {
2102 return $self->open_directory($full_path, $baton,
2103 $self->{r}, $self->{pool});
2104 }
2105 print STDERR "$full_path already exists in repository at ",
2106 "r$self->{r} and it is not a directory (",
2107 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2108 exit 1;
2109}
2110
2111sub ensure_path {
2112 my ($self, $path) = @_;
2113 my $bat = $self->{bat};
6e8548cc
EW
2114 my $repo_path = $self->repo_path($path);
2115 return $bat->{''} unless (length $repo_path);
2116 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
2117 my $c = shift @p;
2118 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2119 while (@p) {
2120 my $c0 = $c;
2121 $c .= '/' . shift @p;
2122 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2123 }
2124 return $bat->{$c};
2125}
2126
2127sub A {
44320b9e 2128 my ($self, $m) = @_;
a5e0cedc
EW
2129 my ($dir, $file) = split_path($m->{file_b});
2130 my $pbat = $self->ensure_path($dir);
2131 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2132 undef, -1);
44320b9e 2133 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2134 $self->chg_file($fbat, $m);
2135 $self->close_file($fbat,undef,$self->{pool});
2136}
2137
2138sub C {
44320b9e 2139 my ($self, $m) = @_;
a5e0cedc
EW
2140 my ($dir, $file) = split_path($m->{file_b});
2141 my $pbat = $self->ensure_path($dir);
2142 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2143 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2144 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2145 $self->chg_file($fbat, $m);
2146 $self->close_file($fbat,undef,$self->{pool});
2147}
2148
2149sub delete_entry {
2150 my ($self, $path, $pbat) = @_;
2151 my $rpath = $self->repo_path($path);
2152 my ($dir, $file) = split_path($rpath);
2153 $self->{rm}->{$dir} = 1;
2154 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2155}
2156
2157sub R {
44320b9e 2158 my ($self, $m) = @_;
a5e0cedc
EW
2159 my ($dir, $file) = split_path($m->{file_b});
2160 my $pbat = $self->ensure_path($dir);
2161 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2162 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2163 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2164 $self->chg_file($fbat, $m);
2165 $self->close_file($fbat,undef,$self->{pool});
2166
2167 ($dir, $file) = split_path($m->{file_a});
2168 $pbat = $self->ensure_path($dir);
2169 $self->delete_entry($m->{file_a}, $pbat);
2170}
2171
2172sub M {
44320b9e 2173 my ($self, $m) = @_;
a5e0cedc
EW
2174 my ($dir, $file) = split_path($m->{file_b});
2175 my $pbat = $self->ensure_path($dir);
2176 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2177 $pbat,$self->{r},$self->{pool});
44320b9e 2178 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2179 $self->chg_file($fbat, $m);
2180 $self->close_file($fbat,undef,$self->{pool});
2181}
2182
2183sub T { shift->M(@_) }
2184
2185sub change_file_prop {
2186 my ($self, $fbat, $pname, $pval) = @_;
2187 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2188}
2189
2190sub chg_file {
2191 my ($self, $fbat, $m) = @_;
2192 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2193 $self->change_file_prop($fbat,'svn:executable','*');
2194 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2195 $self->change_file_prop($fbat,'svn:executable',undef);
2196 }
2197 my $fh = IO::File->new_tmpfile or croak $!;
2198 if ($m->{mode_b} =~ /^120/) {
2199 print $fh 'link ' or croak $!;
2200 $self->change_file_prop($fbat,'svn:special','*');
2201 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2202 $self->change_file_prop($fbat,'svn:special',undef);
2203 }
2204 defined(my $pid = fork) or croak $!;
2205 if (!$pid) {
2206 open STDOUT, '>&', $fh or croak $!;
2207 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2208 }
2209 waitpid $pid, 0;
2210 croak $? if $?;
2211 $fh->flush == 0 or croak $!;
2212 seek $fh, 0, 0 or croak $!;
2213
2214 my $md5 = Digest::MD5->new;
2215 $md5->addfile($fh) or croak $!;
2216 seek $fh, 0, 0 or croak $!;
2217
2218 my $exp = $md5->hexdigest;
f7197dff
EW
2219 my $pool = SVN::Pool->new;
2220 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2221 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2222 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2223 $pool->clear;
a5e0cedc
EW
2224
2225 close $fh or croak $!;
2226}
2227
2228sub D {
44320b9e 2229 my ($self, $m) = @_;
a5e0cedc
EW
2230 my ($dir, $file) = split_path($m->{file_b});
2231 my $pbat = $self->ensure_path($dir);
44320b9e 2232 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2233 $self->delete_entry($m->{file_b}, $pbat);
2234}
2235
2236sub close_edit {
2237 my ($self) = @_;
2238 my ($p,$bat) = ($self->{pool}, $self->{bat});
2239 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2240 $self->close_directory($bat->{$_}, $p);
2241 }
2242 $self->SUPER::close_edit($p);
2243 $p->clear;
2244}
2245
2246sub abort_edit {
2247 my ($self) = @_;
2248 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2249}
2250
2251sub DESTROY {
2252 my $self = shift;
2253 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2254 $self->{pool}->clear;
2255}
2256
44320b9e
EW
2257# this drives the editor
2258sub apply_diff {
61395354
EW
2259 my ($self) = @_;
2260 my $mods = $self->{mods};
44320b9e 2261 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2262 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2263 my $f = $m->{chg};
2264 if (defined $o{$f}) {
2265 $self->$f($m);
2266 } else {
2267 fatal("Invalid change type: $f\n");
2268 }
2269 }
24e22aa8 2270 $self->rmdirs if $_rmdir;
6e8548cc 2271 if (@$mods == 0) {
44320b9e
EW
2272 $self->abort_edit;
2273 } else {
2274 $self->close_edit;
2275 }
6e8548cc 2276 return scalar @$mods;
44320b9e
EW
2277}
2278
d81bf827
EW
2279package Git::SVN::Ra;
2280use vars qw/@ISA $config_dir/;
2281use strict;
2282use warnings;
2283my ($can_do_switch);
5d3b7cd5 2284my $RA;
d81bf827
EW
2285
2286BEGIN {
2287 # enforce temporary pool usage for some simple functions
2288 my $e;
2289 foreach (qw/get_latest_revnum rev_proplist get_file
2290 check_path get_dir get_uuid get_repos_root/) {
2291 $e .= "sub $_ {
2292 my \$self = shift;
2293 my \$pool = SVN::Pool->new;
2294 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2295 \$pool->clear;
2296 wantarray ? \@ret : \$ret[0]; }\n";
2297 }
2298 eval $e;
2299}
2300
2301sub new {
2302 my ($class, $url) = @_;
f6f09876 2303 $url =~ s!/+$!!;
5d3b7cd5 2304 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 2305
d81bf827
EW
2306 SVN::_Core::svn_config_ensure($config_dir, undef);
2307 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2308 SVN::Client::get_simple_provider(),
2309 SVN::Client::get_ssl_server_trust_file_provider(),
2310 SVN::Client::get_simple_prompt_provider(
2311 \&Git::SVN::Prompt::simple, 2),
2312 SVN::Client::get_ssl_client_cert_prompt_provider(
2313 \&Git::SVN::Prompt::ssl_client_cert, 2),
2314 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2315 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2316 SVN::Client::get_username_provider(),
2317 SVN::Client::get_ssl_server_trust_prompt_provider(
2318 \&Git::SVN::Prompt::ssl_server_trust),
2319 SVN::Client::get_username_prompt_provider(
2320 \&Git::SVN::Prompt::username, 2),
2321 ]);
2322 my $config = SVN::Core::config_get_config($config_dir);
2323 my $self = SVN::Ra->new(url => $url, auth => $baton,
2324 config => $config,
2325 pool => SVN::Pool->new,
2326 auth_provider_callbacks => $callbacks);
2327 $self->{svn_path} = $url;
2328 $self->{repos_root} = $self->get_repos_root;
2329 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E/*##;
5d3b7cd5 2330 $RA = bless $self, $class;
d81bf827
EW
2331}
2332
2333sub DESTROY {
5d3b7cd5 2334 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2335}
2336
d81bf827
EW
2337sub get_log {
2338 my ($self, @args) = @_;
2339 my $pool = SVN::Pool->new;
d81bf827
EW
2340 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2341 my $ret = $self->SUPER::get_log(@args, $pool);
2342 $pool->clear;
2343 $ret;
2344}
2345
2346sub get_commit_editor {
44320b9e 2347 my ($self, $log, $cb, $pool) = @_;
d81bf827 2348 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2349 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2350}
2351
2352sub uuid {
2353 my ($self) = @_;
2354 $self->{uuid} ||= $self->get_uuid;
2355}
2356
2357sub gs_do_update {
8a603774
EW
2358 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2359 my $new = ($rev_a == $rev_b);
2360 my $path = $gs->{path};
2361
2362 my $ta = $self->check_path($path, $rev_a);
2363 my $tb = $new ? $ta : $self->check_path($path, $rev_b);
2364 return 1 if ($tb != $SVN::Node::dir && $ta != $SVN::Node::dir);
2365 if ($ta == $SVN::Node::none) {
2366 $rev_a = $rev_b;
2367 $new = 1;
2368 }
2369
d81bf827 2370 my $pool = SVN::Pool->new;
8b8fc068 2371 $editor->set_path_strip($path);
2b27f6c8
EW
2372 my (@pc) = split m#/#, $path;
2373 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 2374 1, $editor, $pool);
d81bf827 2375 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
2376
2377 # Since we can't rely on svn_ra_reparent being available, we'll
2378 # just have to do some magic with set_path to make it so
2379 # we only want a partial path.
2380 my $sp = '';
2381 my $final = join('/', @pc);
2382 while (@pc) {
2383 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2384 $sp .= '/' if length $sp;
2385 $sp .= shift @pc;
2386 }
2387 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2388
2b27f6c8
EW
2389 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2390
d81bf827
EW
2391 $reporter->finish_report($pool);
2392 $pool->clear;
2393 $editor->{git_commit_ok};
2394}
2395
2b27f6c8
EW
2396# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2397# svn_ra_reparent didn't work before 1.4)
d81bf827 2398sub gs_do_switch {
8a603774
EW
2399 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2400 my $path = $gs->{path};
d81bf827 2401 my $pool = SVN::Pool->new;
2b27f6c8
EW
2402
2403 my $full_url = $self->{url};
2404 my $old_url = $full_url;
2405 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
2406 my ($ra, $reparented);
2407 if ($old_url ne $full_url) {
2408 if ($old_url !~ m#^svn(\+ssh)?://#) {
2409 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2410 $pool);
2411 $self->{url} = $full_url;
2412 $reparented = 1;
2413 } else {
2414 $ra = Git::SVN::Ra->new($full_url);
2415 }
2416 }
2417 $ra ||= $self;
8a603774 2418 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 2419 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 2420 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 2421 $reporter->finish_report($pool);
2b27f6c8 2422
5d3b7cd5
EW
2423 if ($reparented) {
2424 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2425 $self->{url} = $old_url;
2426 }
2b27f6c8 2427
d81bf827
EW
2428 $pool->clear;
2429 $editor->{git_commit_ok};
2430}
2431
0af9c9f9
EW
2432sub gs_fetch_loop_common {
2433 my ($self, $base, $head, @gs) = @_;
2434 my $inc = 1000;
2435 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
0af9c9f9
EW
2436 foreach my $gs (@gs) {
2437 if (my $last_commit = $gs->last_commit) {
2438 $gs->assert_index_clean($last_commit);
2439 }
0af9c9f9
EW
2440 }
2441 while (1) {
d4eff2bd 2442 my %revs;
f7c3fc4a 2443 my $err_handler = $SVN::Error::handler;
fbcc1737
EW
2444 $SVN::Error::handler = \&skip_unknown_revs;
2445 $self->get_log([''], $min, $max, 0, 1, 1, sub {
2446 my ($paths, $r, $author, $date, $log) = @_;
2447 $revs{$r} = [ dup_changed_paths($paths),
2448 { author => $author,
2449 date => $date,
2450 log => $log } ] });
d4eff2bd 2451 $SVN::Error::handler = $err_handler;
fbcc1737 2452
d4eff2bd 2453 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737
EW
2454 my ($paths, $logged) = @{$revs{$r}};
2455 foreach my $gs (@gs) {
2456 if ($gs->rev_db_max >= $r) {
2457 next;
2458 }
2459 next unless $gs->match_paths($paths, $r);
2460 $gs->{logged_rev_props} = $logged;
2461 my $log_entry = $gs->do_fetch($paths, $r);
2462 if ($log_entry) {
0af9c9f9
EW
2463 $gs->do_git_commit($log_entry);
2464 }
2465 }
2466 }
9c93fee5
EW
2467 # pre-fill the .rev_db since it'll eventually get filled in
2468 # with '0' x40 if something new gets committed
2469 foreach my $gs (@gs) {
2470 next if defined $gs->rev_db_get($max);
2471 $gs->rev_db_set($max, 0 x40);
2472 }
0af9c9f9
EW
2473 last if $max >= $head;
2474 $min = $max + 1;
2475 $max += $inc;
2476 $max = $head if ($max > $head);
2477 }
0af9c9f9
EW
2478}
2479
e6434f87
EW
2480sub minimize_url {
2481 my ($self) = @_;
2482 return $self->{url} if ($self->{url} eq $self->{repos_root});
2483 my $url = $self->{repos_root};
2484 my @components = split(m!/!, $self->{svn_path});
2485 my $c = '';
2486 do {
2487 $url .= "/$c" if length $c;
2488 eval { (ref $self)->new($url)->get_latest_revnum };
2489 } while ($@ && ($c = shift @components));
2490 $url;
2491}
2492
d81bf827
EW
2493sub can_do_switch {
2494 my $self = shift;
2495 unless (defined $can_do_switch) {
2496 my $pool = SVN::Pool->new;
2497 my $rep = eval {
2498 $self->do_switch(1, '', 0, $self->{url},
2499 SVN::Delta::Editor->new, $pool);
2500 };
2501 if ($@) {
2502 $can_do_switch = 0;
2503 } else {
2504 $rep->abort_report($pool);
2505 $can_do_switch = 1;
2506 }
2507 $pool->clear;
2508 }
2509 $can_do_switch;
2510}
2511
0af9c9f9
EW
2512sub skip_unknown_revs {
2513 my ($err) = @_;
2514 my $errno = $err->apr_err();
2515 # Maybe the branch we're tracking didn't
2516 # exist when the repo started, so it's
2517 # not an error if it doesn't, just continue
2518 #
2519 # Wonderfully consistent library, eh?
2520 # 160013 - svn:// and file://
2521 # 175002 - http(s)://
2522 # 175007 - http(s):// (this repo required authorization, too...)
2523 # More codes may be discovered later...
2524 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2525 return;
2526 }
2527 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2528}
2529
2530# svn_log_changed_path_t objects passed to get_log are likely to be
2531# overwritten even if only the refs are copied to an external variable,
2532# so we should dup the structures in their entirety. Using an externally
2533# passed pool (instead of our temporary and quickly cleared pool in
2534# Git::SVN::Ra) does not help matters at all...
2535sub dup_changed_paths {
2536 my ($paths) = @_;
2537 return undef unless $paths;
2538 my %ret;
2539 foreach my $p (keys %$paths) {
2540 my $i = $paths->{$p};
2541 my %s = map { $_ => $i->$_ }
2542 qw/copyfrom_path copyfrom_rev action/;
2543 $ret{$p} = \%s;
2544 }
2545 \%ret;
2546}
2547
f8c9d1d2
EW
2548package Git::SVN::Log;
2549use strict;
2550use warnings;
2551use POSIX qw/strftime/;
2552use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2553 %rusers $show_commit $incremental/;
2554my $l_fmt;
2555
2556sub cmt_showable {
2557 my ($c) = @_;
2558 return 1 if defined $c->{r};
2559 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2560 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
44320b9e
EW
2561 my @log = command(qw/cat-file commit/, $c->{c});
2562 shift @log while ($log[0] ne "\n");
2563 shift @log;
2564 @{$c->{l}} = grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
2565
2566 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 2567 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
2568 }
2569 return defined $c->{r};
2570}
2571
2572sub log_use_color {
2573 return 1 if $color;
2574 my ($dc, $dcvar);
2575 $dcvar = 'color.diff';
2576 $dc = `git-config --get $dcvar`;
2577 if ($dc eq '') {
2578 # nothing at all; fallback to "diff.color"
2579 $dcvar = 'diff.color';
2580 $dc = `git-config --get $dcvar`;
2581 }
2582 chomp($dc);
2583 if ($dc eq 'auto') {
2584 my $pc;
2585 $pc = `git-config --get color.pager`;
2586 if ($pc eq '') {
2587 # does not have it -- fallback to pager.color
2588 $pc = `git-config --bool --get pager.color`;
2589 }
2590 else {
2591 $pc = `git-config --bool --get color.pager`;
2592 if ($?) {
2593 $pc = 'false';
2594 }
2595 }
2596 chomp($pc);
2597 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2598 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2599 }
2600 return 0;
2601 }
2602 return 0 if $dc eq 'never';
2603 return 1 if $dc eq 'always';
2604 chomp($dc = `git-config --bool --get $dcvar`);
2605 return ($dc eq 'true');
2606}
2607
2608sub git_svn_log_cmd {
2609 my ($r_min, $r_max) = @_;
2610 my $gs = Git::SVN->_new;
2611 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2612 $gs->refname);
2613 push @cmd, '-r' unless $non_recursive;
2614 push @cmd, qw/--raw --name-status/ if $verbose;
2615 push @cmd, '--color' if log_use_color();
2616 return @cmd unless defined $r_max;
2617 if ($r_max == $r_min) {
2618 push @cmd, '--max-count=1';
2619 if (my $c = $gs->rev_db_get($r_max)) {
2620 push @cmd, $c;
2621 }
2622 } else {
2623 my ($c_min, $c_max);
2624 $c_max = $gs->rev_db_get($r_max);
2625 $c_min = $gs->rev_db_get($r_min);
2626 if (defined $c_min && defined $c_max) {
2627 if ($r_max > $r_max) {
2628 push @cmd, "$c_min..$c_max";
2629 } else {
2630 push @cmd, "$c_max..$c_min";
2631 }
2632 } elsif ($r_max > $r_min) {
2633 push @cmd, $c_max;
2634 } else {
2635 push @cmd, $c_min;
2636 }
2637 }
2638 return @cmd;
2639}
2640
2641# adapted from pager.c
2642sub config_pager {
2643 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2644 if (!defined $pager) {
2645 $pager = 'less';
2646 } elsif (length $pager == 0 || $pager eq 'cat') {
2647 $pager = undef;
2648 }
2649}
2650
2651sub run_pager {
2652 return unless -t *STDOUT;
2653 pipe my $rfd, my $wfd or return;
2654 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2655 if (!$pid) {
2656 open STDOUT, '>&', $wfd or
2657 ::fatal "Can't redirect to stdout: $!\n";
2658 return;
2659 }
2660 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2661 $ENV{LESS} ||= 'FRSX';
2662 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2663}
2664
21819a37
EW
2665sub tz_to_s_offset {
2666 my ($tz) = @_;
2667 $tz =~ s/(\d\d)$//;
2668 return ($1 * 60) + ($tz * 3600);
2669}
2670
f8c9d1d2
EW
2671sub get_author_info {
2672 my ($dest, $author, $t, $tz) = @_;
2673 $author =~ s/(?:^\s*|\s*$)//g;
2674 $dest->{a_raw} = $author;
2675 my $au;
1c8443b0 2676 if ($::_authors) {
f8c9d1d2
EW
2677 $au = $rusers{$author} || undef;
2678 }
2679 if (!$au) {
2680 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2681 }
2682 $dest->{t} = $t;
2683 $dest->{tz} = $tz;
2684 $dest->{a} = $au;
2685 # Date::Parse isn't in the standard Perl distro :(
2686 if ($tz =~ s/^\+//) {
21819a37 2687 $t += tz_to_s_offset($tz);
f8c9d1d2 2688 } elsif ($tz =~ s/^\-//) {
21819a37 2689 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
2690 }
2691 $dest->{t_utc} = $t;
2692}
2693
2694sub process_commit {
2695 my ($c, $r_min, $r_max, $defer) = @_;
2696 if (defined $r_min && defined $r_max) {
2697 if ($r_min == $c->{r} && $r_min == $r_max) {
2698 show_commit($c);
2699 return 0;
2700 }
2701 return 1 if $r_min == $r_max;
2702 if ($r_min < $r_max) {
2703 # we need to reverse the print order
2704 return 0 if (defined $limit && --$limit < 0);
2705 push @$defer, $c;
2706 return 1;
2707 }
2708 if ($r_min != $r_max) {
2709 return 1 if ($r_min < $c->{r});
2710 return 1 if ($r_max > $c->{r});
2711 }
2712 }
2713 return 0 if (defined $limit && --$limit < 0);
2714 show_commit($c);
2715 return 1;
2716}
2717
2718sub show_commit {
2719 my $c = shift;
2720 if ($oneline) {
2721 my $x = "\n";
2722 if (my $l = $c->{l}) {
2723 while ($l->[0] =~ /^\s*$/) { shift @$l }
2724 $x = $l->[0];
2725 }
2726 $l_fmt ||= 'A' . length($c->{r});
2727 print 'r',pack($l_fmt, $c->{r}),' | ';
2728 print "$c->{c} | " if $show_commit;
2729 print $x;
2730 } else {
2731 show_commit_normal($c);
2732 }
2733}
2734
2735sub show_commit_changed_paths {
2736 my ($c) = @_;
2737 return unless $c->{changed};
2738 print "Changed paths:\n", @{$c->{changed}};
2739}
2740
2741sub show_commit_normal {
2742 my ($c) = @_;
2743 print '-' x72, "\nr$c->{r} | ";
2744 print "$c->{c} | " if $show_commit;
2745 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2746 localtime($c->{t_utc})), ' | ';
2747 my $nr_line = 0;
2748
2749 if (my $l = $c->{l}) {
2750 while ($l->[$#$l] eq "\n" && $#$l > 0
2751 && $l->[($#$l - 1)] eq "\n") {
2752 pop @$l;
2753 }
2754 $nr_line = scalar @$l;
2755 if (!$nr_line) {
2756 print "1 line\n\n\n";
2757 } else {
2758 if ($nr_line == 1) {
2759 $nr_line = '1 line';
2760 } else {
2761 $nr_line .= ' lines';
2762 }
2763 print $nr_line, "\n";
2764 show_commit_changed_paths($c);
2765 print "\n";
2766 print $_ foreach @$l;
2767 }
2768 } else {
2769 print "1 line\n";
2770 show_commit_changed_paths($c);
2771 print "\n";
2772
2773 }
2774 foreach my $x (qw/raw diff/) {
2775 if ($c->{$x}) {
2776 print "\n";
2777 print $_ foreach @{$c->{$x}}
2778 }
2779 }
2780}
2781
2782sub cmd_show_log {
2783 my (@args) = @_;
2784 my ($r_min, $r_max);
2785 my $r_last = -1; # prevent dupes
2786 if (defined $TZ) {
2787 $ENV{TZ} = $TZ;
2788 } else {
2789 delete $ENV{TZ};
2790 }
2791 if (defined $::_revision) {
2792 if ($::_revision =~ /^(\d+):(\d+)$/) {
2793 ($r_min, $r_max) = ($1, $2);
2794 } elsif ($::_revision =~ /^\d+$/) {
2795 $r_min = $r_max = $::_revision;
2796 } else {
2797 ::fatal "-r$::_revision is not supported, use ",
2798 "standard \'git log\' arguments instead\n";
2799 }
2800 }
2801
2802 config_pager();
2803 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2804 my $log = command_output_pipe(@args);
2805 run_pager();
2806 my (@k, $c, $d);
2807 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2808 while (<$log>) {
2809 if (/^${esc_color}commit ($::sha1_short)/o) {
2810 my $cmt = $1;
2811 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2812 $r_last = $c->{r};
2813 process_commit($c, $r_min, $r_max, \@k) or
2814 goto out;
2815 }
2816 $d = undef;
2817 $c = { c => $cmt };
2818 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2819 get_author_info($c, $1, $2, $3);
2820 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2821 # ignore
2822 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2823 push @{$c->{raw}}, $_;
2824 } elsif (/^${esc_color}[ACRMDT]\t/) {
2825 # we could add $SVN->{svn_path} here, but that requires
2826 # remote access at the moment (repo_path_split)...
2827 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2828 push @{$c->{changed}}, $_;
2829 } elsif (/^${esc_color}diff /o) {
2830 $d = 1;
2831 push @{$c->{diff}}, $_;
2832 } elsif ($d) {
2833 push @{$c->{diff}}, $_;
2834 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2835 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2836 } elsif (s/^${esc_color} //o) {
2837 push @{$c->{l}}, $_;
2838 }
2839 }
2840 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2841 $r_last = $c->{r};
2842 process_commit($c, $r_min, $r_max, \@k);
2843 }
2844 if (@k) {
2845 my $swap = $r_max;
2846 $r_max = $r_min;
2847 $r_min = $swap;
2848 process_commit($_, $r_min, $r_max) foreach reverse @k;
2849 }
2850out:
c843c464 2851 close $log;
f8c9d1d2
EW
2852 print '-' x72,"\n" unless $incremental || $oneline;
2853}
2854
706587fc
EW
2855package Git::SVN::Migration;
2856# these version numbers do NOT correspond to actual version numbers
2857# of git nor git-svn. They are just relative.
2858#
2859# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
2860#
2861# v1 layout: .git/$id/info/url, refs/remotes/$id
2862#
2863# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
2864#
2865# v3 layout: .git/svn/$id, refs/remotes/$id
2866# - info/url may remain for backwards compatibility
2867# - this is what we migrate up to this layout automatically,
2868# - this will be used by git svn init on single branches
2869#
2870# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
2871# - this is only created for newly multi-init-ed
2872# repositories. Similar in spirit to the
2873# --use-separate-remotes option in git-clone (now default)
2874# - we do not automatically migrate to this (following
2875# the example set by core git)
2876use strict;
2877use warnings;
2878use Carp qw/croak/;
2879use File::Path qw/mkpath/;
47e39c55
EW
2880use File::Basename qw/dirname basename/;
2881use vars qw/$_minimize/;
706587fc
EW
2882
2883sub migrate_from_v0 {
2884 my $git_dir = $ENV{GIT_DIR};
2885 return undef unless -d $git_dir;
2886 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2887 my $migrated = 0;
2888 while (<$fh>) {
2889 chomp;
2890 my ($id, $orig_ref) = ($_, $_);
2891 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
2892 next unless -f "$git_dir/$id/info/url";
2893 my $new_ref = "refs/remotes/$id";
2894 if (::verify_ref("$new_ref^0")) {
2895 print STDERR "W: $orig_ref is probably an old ",
2896 "branch used by an ancient version of ",
2897 "git-svn.\n",
2898 "However, $new_ref also exists.\n",
2899 "We will not be able ",
2900 "to use this branch until this ",
2901 "ambiguity is resolved.\n";
2902 next;
2903 }
2904 print STDERR "Migrating from v0 layout...\n" if !$migrated;
2905 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
2906 command_noisy('update-ref', $new_ref, $orig_ref);
2907 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
2908 $migrated++;
2909 }
2910 command_close_pipe($fh, $ctx);
2911 print STDERR "Done migrating from v0 layout...\n" if $migrated;
2912 $migrated;
2913}
2914
2915sub migrate_from_v1 {
2916 my $git_dir = $ENV{GIT_DIR};
2917 my $migrated = 0;
2918 return $migrated unless -d $git_dir;
2919 my $svn_dir = "$git_dir/svn";
2920
2921 # just in case somebody used 'svn' as their $id at some point...
2922 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
2923
2924 print STDERR "Migrating from a git-svn v1 layout...\n";
2925 mkpath([$svn_dir]);
2926 print STDERR "Data from a previous version of git-svn exists, but\n\t",
2927 "$svn_dir\n\t(required for this version ",
2928 "($::VERSION) of git-svn) does not. exist\n";
2929 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
2930 while (<$fh>) {
2931 my $x = $_;
2932 next unless $x =~ s#^refs/remotes/##;
2933 chomp $x;
2934 next unless -f "$git_dir/$x/info/url";
2935 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
2936 next unless $u;
2937 my $dn = dirname("$git_dir/svn/$x");
2938 mkpath([$dn]) unless -d $dn;
2939 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
2940 mkpath(["$git_dir/svn/svn"]);
2941 print STDERR " - $git_dir/$x/info => ",
2942 "$git_dir/svn/$x/info\n";
2943 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
2944 croak "$!: $x";
2945 # don't worry too much about these, they probably
2946 # don't exist with repos this old (save for index,
2947 # and we can easily regenerate that)
2948 foreach my $f (qw/unhandled.log index .rev_db/) {
2949 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
2950 }
2951 } else {
2952 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
2953 rename "$git_dir/$x", "$git_dir/svn/$x" or
2954 croak "$!: $x";
2955 }
2956 $migrated++;
2957 }
2958 command_close_pipe($fh, $ctx);
2959 print STDERR "Done migrating from a git-svn v1 layout\n";
2960 $migrated;
2961}
2962
2963sub read_old_urls {
2964 my ($l_map, $pfx, $path) = @_;
2965 my @dir;
2966 foreach (<$path/*>) {
2967 if (-r "$_/info/url") {
2968 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
2969 my $ref_id = $pfx . basename $_;
2970 my $url = ::file_to_s("$_/info/url");
2971 $l_map->{$ref_id} = $url;
2972 } elsif (-d $_) {
2973 push @dir, $_;
2974 }
2975 }
2976 foreach (@dir) {
2977 my $x = $_;
2978 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
2979 read_old_urls($l_map, $x, $_);
2980 }
2981}
2982
2983sub migrate_from_v2 {
2984 my @cfg = command(qw/config -l/);
2985 return if grep /^svn-remote\..+\.url=/, @cfg;
2986 my %l_map;
2987 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
2988 my $migrated = 0;
2989
2990 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
2991 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
2992 if ($@) {
2993 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
2994 }
706587fc
EW
2995 $migrated++;
2996 }
2997 $migrated;
2998}
2999
47e39c55
EW
3000sub minimize_connections {
3001 my $r = Git::SVN::read_all_remotes();
3002 my $new_urls = {};
3003 my $root_repos = {};
3004 foreach my $repo_id (keys %$r) {
3005 my $url = $r->{$repo_id}->{url} or next;
3006 my $fetch = $r->{$repo_id}->{fetch} or next;
3007 my $ra = Git::SVN::Ra->new($url);
3008
3009 # skip existing cases where we already connect to the root
3010 if (($ra->{url} eq $ra->{repos_root}) ||
3011 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3012 $repo_id)) {
3013 $root_repos->{$ra->{url}} = $repo_id;
3014 next;
3015 }
3016
3017 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3018 my $root_path = $ra->{url};
3019 $root_path =~ s#^\Q$ra->{repos_root}\E/*##;
3020 foreach my $path (keys %$fetch) {
3021 my $ref_id = $fetch->{$path};
3022 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3023
3024 # make sure we can read when connecting to
3025 # a higher level of a repository
3026 my ($last_rev, undef) = $gs->last_rev_commit;
3027 if (!defined $last_rev) {
3028 $last_rev = eval {
3029 $root_ra->get_latest_revnum;
3030 };
3031 next if $@;
3032 }
3033 my $new = $root_path;
3034 $new .= length $path ? "/$path" : '';
3035 eval {
3036 $root_ra->get_log([$new], $last_rev, $last_rev,
3037 0, 0, 1, sub { });
3038 };
3039 next if $@;
3040 $new_urls->{$ra->{repos_root}}->{$new} =
3041 { ref_id => $ref_id,
3042 old_repo_id => $repo_id,
3043 old_path => $path };
3044 }
3045 }
3046
3047 my @emptied;
3048 foreach my $url (keys %$new_urls) {
3049 # see if we can re-use an existing [svn-remote "repo_id"]
3050 # instead of creating a(n ugly) new section:
3051 my $repo_id = $root_repos->{$url} ||
3052 Git::SVN::sanitize_remote_name($url);
3053
3054 my $fetch = $new_urls->{$url};
3055 foreach my $path (keys %$fetch) {
3056 my $x = $fetch->{$path};
3057 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3058 my $pfx = "svn-remote.$x->{old_repo_id}";
3059
3060 my $old_fetch = quotemeta("$x->{old_path}:".
3061 "refs/remotes/$x->{ref_id}");
8b8fc068 3062 command_noisy(qw/config --unset/,
47e39c55
EW
3063 "$pfx.fetch", '^'. $old_fetch . '$');
3064 delete $r->{$x->{old_repo_id}}->
3065 {fetch}->{$x->{old_path}};
3066 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 3067 command_noisy(qw/config --unset/,
47e39c55
EW
3068 "$pfx.url");
3069 push @emptied, $x->{old_repo_id}
3070 }
3071 }
3072 }
3073 if (@emptied) {
3074 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3075 "$ENV{GIT_DIR}/config";
3076 print STDERR <<EOF;
3077The following [svn-remote] sections in your config file ($file) are empty
3078and can be safely removed:
3079EOF
3080 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3081 }
3082}
3083
706587fc
EW
3084sub migration_check {
3085 migrate_from_v0();
3086 migrate_from_v1();
3087 migrate_from_v2();
47e39c55 3088 minimize_connections() if $_minimize;
706587fc
EW
3089}
3090
ef3cfaad
EW
3091package Git::IndexInfo;
3092use strict;
3093use warnings;
3094use Git qw/command_input_pipe command_close_pipe/;
3095
3096sub new {
3097 my ($class) = @_;
3098 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3099 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3100}
3101
3102sub remove {
3103 my ($self, $path) = @_;
3104 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3105 return ++$self->{nr};
3106 }
3107 undef;
3108}
3109
3110sub update {
3111 my ($self, $mode, $hash, $path) = @_;
3112 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3113 return ++$self->{nr};
3114 }
3115 undef;
3116}
3117
3118sub DESTROY {
3119 my ($self) = @_;
3120 command_close_pipe($self->{gui}, $self->{ctx});
3121}
3122
4bb9ed04
EW
3123package Git::SVN::GlobSpec;
3124use strict;
3125use warnings;
3126
3127sub new {
3128 my ($class, $glob) = @_;
3129 warn "glob: $glob\n";
3130 my $re = $glob;
3131 $re =~ s!/+$!!g; # no need for trailing slashes
3132 my $nr = ($re =~ s!^(.*/?)\*(/?.*)$!\(\[^/\]+\)!g);
3133 my ($left, $right) = ($1, $2);
3134 if ($nr > 1) {
3135 warn "Only one '*' wildcard expansion ",
3136 "is supported (got $nr): '$glob'\n";
3137 } elsif ($nr == 0) {
3138 warn "One '*' is needed for glob: '$glob'\n";
3139 }
3140 $re = quotemeta($left) . $re . quotemeta($right);
3141 $left =~ s!/+$!!g;
3142 $right =~ s!^/+!!g;
3143 bless { left => $left, right => $right,
3144 regex => qr/$re/, glob => $glob }, $class;
3145}
3146
3147sub full_path {
3148 my ($self, $path) = @_;
3149 return (length $self->{left} ? "$self->{left}/" : '') .
3150 $path . (length $self->{right} ? "/$self->{right}" : '');
3151}
3152
3397f9df
EW
3153__END__
3154
3155Data structures:
3156
4bb9ed04
EW
3157
3158$remotes = { # returned by read_all_remotes()
3159 'svn' => {
3160 # svn-remote.svn.url=https://svn.musicpd.org
3161 url => 'https://svn.musicpd.org',
3162 # svn-remote.svn.fetch=mpd/trunk:trunk
3163 fetch => {
3164 'mpd/trunk' => 'trunk',
3165 },
3166 # svn-remote.svn.tags=mpd/tags/*:tags/*
3167 tags => {
3168 path => {
3169 left => 'mpd/tags',
3170 right => '',
3171 regex => qr!mpd/tags/([^/]+)$!,
3172 glob => 'tags/*',
3173 },
3174 ref => {
3175 left => 'tags',
3176 right => '',
3177 regex => qr!tags/([^/]+)$!,
3178 glob => 'tags/*',
3179 },
3180 }
3181 }
3182};
3183
44320b9e 3184$log_entry hashref as returned by libsvn_log_entry()
3397f9df 3185{
44320b9e 3186 log => 'whitespace-formatted log entry
3397f9df
EW
3187', # trailing newline is preserved
3188 revision => '8', # integer
3189 date => '2004-02-24T17:01:44.108345Z', # commit date
3190 author => 'committer name'
3191};
3192
6e8548cc
EW
3193
3194# this is generated by generate_diff();
3397f9df
EW
3195@mods = array of diff-index line hashes, each element represents one line
3196 of diff-index output
3197
3198diff-index line ($m hash)
3199{
3200 mode_a => first column of diff-index output, no leading ':',
3201 mode_b => second column of diff-index output,
3202 sha1_b => sha1sum of the final blob,
ac8e0b91 3203 chg => change type [MCRADT],
3397f9df
EW
3204 file_a => original file name of a file (iff chg is 'C' or 'R')
3205 file_b => new/current file name of a file (any chg)
3206}
3207;
a5e0cedc 3208
a00439ac
EW
3209# retval of read_url_paths{,_all}();
3210$l_map = {
3211 # repository root url
3212 'https://svn.musicpd.org' => {
3213 # repository path # GIT_SVN_ID
3214 'mpd/trunk' => 'trunk',
3215 'mpd/tags/0.11.5' => 'tags/0.11.5',
3216 },
3217}
3218
a5e0cedc
EW
3219Notes:
3220 I don't trust the each() function on unless I created %hash myself
3221 because the internal iterator may not have started at base.