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