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