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