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