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