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