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