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