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