]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
git-fast-import: rename cmd_*() functions to parse_*()
[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
15153451
BS
12# From which subdir have we been invoked?
13my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15} || '';
16
5253dc33 17my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 18$ENV{GIT_DIR} ||= '.git';
9fa00b65 19$Git::SVN::default_repo_id = 'svn';
8b8fc068 20$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 21$Git::SVN::Ra::_log_window_size = 100;
13ccd6d4 22
f8c9d1d2 23$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 24$ENV{TZ} = 'UTC';
a00439ac 25$| = 1; # unbuffer STDOUT
3397f9df 26
207f1a75 27sub fatal (@) { print STDERR "@_\n"; exit 1 }
b9c85187
EW
28require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29require SVN::Ra;
30require SVN::Delta;
31if ($SVN::Core::VERSION lt '1.1.0') {
207f1a75 32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
b9c85187 33}
d81bf827 34push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
35push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df 37use Carp qw/croak/;
8d7c4fad 38use Digest::MD5;
3397f9df
EW
39use IO::File qw//;
40use File::Basename qw/dirname basename/;
41use File::Path qw/mkpath/;
512b620b 42use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
968bdf1f 43use IPC::Open3;
336f1714 44use Git;
a5e0cedc 45
336f1714 46BEGIN {
c5f71ad0
SV
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
336f1714
EW
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
c5f71ad0 51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
8d7c4fad 52 Git::SVN::Migration Git::SVN::Log Git::SVN),
c5f71ad0
SV
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
55 }
336f1714 56 }
336f1714
EW
57}
58
b9c85187 59my ($SVN);
83e9940a 60
f8c9d1d2
EW
61$sha1 = qr/[a-f\d]{40}/;
62$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 63my ($_stdin, $_help, $_edit,
9760adcc 64 $_message, $_file,
d05d72e0 65 $_template, $_shared,
171af110 66 $_version, $_fetch_all, $_no_rebase,
dee41f3e 67 $_merge, $_strategy, $_dry_run, $_local,
4be40381
SG
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format);
0bed5eaa 70$Git::SVN::_follow_parent = 1;
706587fc
EW
71my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
0bed5eaa 74my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 75 'authors-file|A=s' => \$_authors,
ecc712dd 76 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 81 'no-checkout' => \$_no_checkout,
80f50749 82 'quiet|q' => \$_q,
ecc712dd
EW
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
70ae04e4 85 'use-log-author' => \$Git::SVN::_use_log_author,
706587fc 86 %remote_opts );
36f5b1f0 87
8f728fb9 88my ($_trunk, $_tags, $_branches, $_stdlayout);
0dfaf0a4 89my %icv;
dadc6d2a
EW
90my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
91 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
92 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
8f728fb9 93 'stdlayout|s' => \$_stdlayout,
4a1bb4c3 94 'minimize-url|m' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
95 'no-metadata' => sub { $icv{noMetadata} = 1 },
96 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
97 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
98 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
dadc6d2a 99 %remote_opts );
27e9fb8d 100my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
101 'rmdir' => \$SVN::Git::Editor::_rmdir,
102 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
103 'l=i' => \$SVN::Git::Editor::_rename_limit,
104 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 105);
9d55b41a 106
3397f9df 107my %cmd = (
2a3240be 108 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 109 { 'revision|r=s' => \$_revision,
905f8b7d 110 'fetch-all|all' => \$_fetch_all,
e98671e5 111 %fc_opts } ],
0425ea90
EW
112 clone => [ \&cmd_clone, "Initialize and fetch revisions",
113 { 'revision|r=s' => \$_revision,
114 %fc_opts, %init_opts } ],
d2866f9e 115 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 116 " (requires URL argument)",
9d55b41a 117 \%init_opts ],
dadc6d2a
EW
118 'multi-init' => [ \&cmd_multi_init,
119 "Deprecated alias for ".
120 "'$0 init -T<trunk> -b<branches> -t<tags>'",
121 \%init_opts ],
d7ad3bed
EW
122 dcommit => [ \&cmd_dcommit,
123 'Commit several diffs to merge with upstream',
3289e86e
EW
124 { 'merge|m|M' => \$_merge,
125 'strategy|s=s' => \$_strategy,
905f8b7d 126 'verbose|v' => \$_verbose,
3289e86e 127 'dry-run|n' => \$_dry_run,
905f8b7d 128 'fetch-all|all' => \$_fetch_all,
171af110 129 'no-rebase' => \$_no_rebase,
4b155223 130 %cmt_opts, %fc_opts } ],
1ce255dc
EW
131 'set-tree' => [ \&cmd_set_tree,
132 "Set an SVN repository to a git tree-ish",
133 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
134 'create-ignore' => [ \&cmd_create_ignore,
135 'Create a .gitignore per svn:ignore',
136 { 'revision|r=i' => \$_revision
137 } ],
15153451
BS
138 'propget' => [ \&cmd_propget,
139 'Print the value of a property on a file or directory',
140 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
141 'proplist' => [ \&cmd_proplist,
142 'List all properties of a file or directory',
143 { 'revision|r=i' => \$_revision } ],
5969cbe1 144 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 145 { 'revision|r=i' => \$_revision
05b4df31 146 } ],
2d879792
VK
147 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
148 { 'revision|r=i' => \$_revision
149 } ],
1c8443b0 150 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
151 "Deprecated alias for $0 fetch --all",
152 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
153 'migrate' => [ sub { },
154 # no-op, we automatically run this anyways,
706587fc
EW
155 'Migrate configuration/metadata/layout from
156 previous versions of git-svn',
a836a0e1
EW
157 { 'minimize' => \$Git::SVN::Migration::_minimize,
158 %remote_opts } ],
f8c9d1d2
EW
159 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
160 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 161 'revision|r=s' => \$_revision,
f8c9d1d2
EW
162 'verbose|v' => \$Git::SVN::Log::verbose,
163 'incremental' => \$Git::SVN::Log::incremental,
164 'oneline' => \$Git::SVN::Log::oneline,
165 'show-commit' => \$Git::SVN::Log::show_commit,
166 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 167 'authors-file|A=s' => \$_authors,
f8c9d1d2 168 'color' => \$Git::SVN::Log::color,
4dbfe2e9 169 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 170 } ],
26e60160 171 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 172 {} ],
905f8b7d
EW
173 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
174 { 'merge|m|M' => \$_merge,
175 'verbose|v' => \$_verbose,
176 'strategy|s=s' => \$_strategy,
dee41f3e 177 'local|l' => \$_local,
905f8b7d
EW
178 'fetch-all|all' => \$_fetch_all,
179 %fc_opts } ],
44320b9e
EW
180 'commit-diff' => [ \&cmd_commit_diff,
181 'Commit a diff between two trees',
27e9fb8d
EW
182 { 'message|m=s' => \$_message,
183 'file|F=s' => \$_file,
45bf473a 184 'revision|r=s' => \$_revision,
27e9fb8d 185 %cmt_opts } ],
e6fefa92
DK
186 'info' => [ \&cmd_info,
187 "Show info about the latest SVN revision
188 on the current branch",
8b014d71 189 { 'url' => \$_url, } ],
6fb5375e
TS
190 'blame' => [ \&Git::SVN::Log::cmd_blame,
191 "Show what revision and author last modified each line of a file",
4be40381 192 { 'git-format' => \$_git_format } ],
3397f9df 193);
9d55b41a 194
3397f9df
EW
195my $cmd;
196for (my $i = 0; $i < @ARGV; $i++) {
197 if (defined $cmd{$ARGV[$i]}) {
198 $cmd = $ARGV[$i];
199 splice @ARGV, $i, 1;
200 last;
201 }
202};
203
540424b2
EW
204# make sure we're always running at the top-level working directory
205unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
206 unless (-d $ENV{GIT_DIR}) {
207 if ($git_dir_user_set) {
208 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
209 "but it is not a directory\n";
210 }
211 my $git_dir = delete $ENV{GIT_DIR};
212 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
213 unless (length $cdup) {
214 die "Already at toplevel, but $git_dir ",
215 "not found '$cdup'\n";
216 }
217 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
218 unless (-d $git_dir) {
219 die "$git_dir still not found after going to ",
220 "'$cdup'\n";
221 }
222 $ENV{GIT_DIR} = $git_dir;
223 }
224}
f4dd334b
GH
225
226my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
227
228read_repo_config(\%opts);
4be40381 229Getopt::Long::Configure('pass_through') if ($cmd && ($cmd eq 'log' || $cmd eq 'blame'));
f4dd334b
GH
230my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
231 'minimize-connections' => \$Git::SVN::Migration::_minimize,
232 'id|i=s' => \$Git::SVN::default_ref_id,
233 'svn-remote|remote|R=s' => sub {
234 $Git::SVN::no_reuse_existing = 1;
235 $Git::SVN::default_repo_id = $_[1] });
236exit 1 if (!$rv && $cmd && $cmd ne 'log');
237
238usage(0) if $_help;
239version() if $_version;
240usage(1) unless defined $cmd;
241load_authors() if $_authors;
242
0425ea90 243unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
244 Git::SVN::Migration::migration_check();
245}
ecc712dd 246Git::SVN::init_vars();
b805b44a
EW
247eval {
248 Git::SVN::verify_remotes_sanity();
249 $cmd{$cmd}->[0]->(@ARGV);
250};
251fatal $@ if $@;
1e889ef3 252post_fetch_checkout();
3397f9df
EW
253exit 0;
254
255####################### primary functions ######################
256sub usage {
257 my $exit = shift || 0;
258 my $fd = $exit ? \*STDERR : \*STDOUT;
259 print $fd <<"";
260git-svn - bidirectional operations between a single Subversion tree and git
261Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
262
263 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
264
265 foreach (sort keys %cmd) {
448c81b4 266 next if $cmd && $cmd ne $_;
a836a0e1 267 next if /^multi-/; # don't show deprecated commands
b203b769 268 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 269 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
270 # mixed-case options are for .git/config only
271 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 272 # prints out arguments as they should be passed:
b8c92cad 273 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 274 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
275 "--$_" : "-$_" }
276 split /\|/,$_)," $x\n";
277 }
3397f9df
EW
278 }
279 print $fd <<"";
448c81b4
EW
280\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
281arbitrary identifier if you're tracking multiple SVN branches/repositories in
282one git repository and want to keep them separate. See git-svn(1) for more
283information.
3397f9df
EW
284
285 exit $exit;
286}
287
551ce28f 288sub version {
7d60ab2c 289 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
290 exit 0;
291}
292
8164b652
EW
293sub do_git_init_db {
294 unless (-d $ENV{GIT_DIR}) {
295 my @init_db = ('init');
296 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
297 if (defined $_shared) {
298 if ($_shared =~ /[a-z]/) {
299 push @init_db, "--shared=$_shared";
300 } else {
301 push @init_db, "--shared";
302 }
303 }
8164b652
EW
304 command_noisy(@init_db);
305 }
0dfaf0a4
EW
306 my $set;
307 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
308 foreach my $i (keys %icv) {
309 die "'$set' and '$i' cannot both be set\n" if $set;
310 next unless defined $icv{$i};
311 command_noisy('config', "$pfx.$i", $icv{$i});
312 $set = $i;
313 }
8164b652
EW
314}
315
dadc6d2a
EW
316sub init_subdir {
317 my $repo_path = shift or return;
318 mkpath([$repo_path]) unless -d $repo_path;
319 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 320 $ENV{GIT_DIR} = '.git';
dadc6d2a
EW
321}
322
0425ea90
EW
323sub cmd_clone {
324 my ($url, $path) = @_;
325 if (!defined $path &&
8f728fb9 326 (defined $_trunk || defined $_branches || defined $_tags ||
327 defined $_stdlayout) &&
0425ea90
EW
328 $url !~ m#^[a-z\+]+://#) {
329 $path = $url;
330 }
0425ea90 331 $path = basename($url) if !defined $path || !length $path;
f30603fc 332 cmd_init($url, $path);
0425ea90
EW
333 Git::SVN::fetch_all($Git::SVN::default_repo_id);
334}
335
d2866f9e 336sub cmd_init {
8f728fb9 337 if (defined $_stdlayout) {
338 $_trunk = 'trunk' if (!defined $_trunk);
339 $_tags = 'tags' if (!defined $_tags);
340 $_branches = 'branches' if (!defined $_branches);
341 }
dadc6d2a
EW
342 if (defined $_trunk || defined $_branches || defined $_tags) {
343 return cmd_multi_init(@_);
03e0ea87 344 }
dadc6d2a
EW
345 my $url = shift or die "SVN repository location required ",
346 "as a command-line argument\n";
347 init_subdir(@_);
8164b652 348 do_git_init_db();
03e0ea87 349
706587fc 350 Git::SVN->init($url);
3397f9df
EW
351}
352
2a3240be 353sub cmd_fetch {
e98671e5
EW
354 if (grep /^\d+=./, @_) {
355 die "'<rev>=<commit>' fetch arguments are ",
356 "no longer supported.\n";
07a1c950 357 }
e98671e5
EW
358 my ($remote) = @_;
359 if (@_ > 1) {
905f8b7d 360 die "Usage: $0 fetch [--all] [svn-remote]\n";
e98671e5
EW
361 }
362 $remote ||= $Git::SVN::default_repo_id;
363 if ($_fetch_all) {
364 cmd_multi_fetch();
365 } else {
366 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 367 }
2a3240be
EW
368}
369
1ce255dc 370sub cmd_set_tree {
3397f9df
EW
371 my (@commits) = @_;
372 if ($_stdin || !@commits) {
373 print "Reading from stdin...\n";
374 @commits = ();
375 while (<STDIN>) {
1ca72aef 376 if (/\b($sha1_short)\b/o) {
3397f9df
EW
377 unshift @commits, $1;
378 }
379 }
380 }
381 my @revs;
8de010ad 382 foreach my $c (@commits) {
aef4e921 383 my @tmp = command('rev-parse',$c);
8de010ad
EW
384 if (scalar @tmp == 1) {
385 push @revs, $tmp[0];
386 } elsif (scalar @tmp > 1) {
aef4e921 387 push @revs, reverse(command('rev-list',@tmp));
8de010ad 388 } else {
207f1a75 389 fatal "Failed to rev-parse $c";
8de010ad 390 }
3397f9df 391 }
1ce255dc
EW
392 my $gs = Git::SVN->new;
393 my ($r_last, $cmt_last) = $gs->last_rev_commit;
394 $gs->fetch;
97f6987a 395 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
396 fatal "There are new revisions that were fetched ",
397 "and need to be merged (or acknowledged) ",
398 "before committing.\nlast rev: $r_last\n",
207f1a75 399 " current: $gs->{last_rev}";
a5e0cedc 400 }
1ce255dc
EW
401 $gs->set_tree($_) foreach @revs;
402 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 403 unlink $gs->{index};
a5e0cedc 404}
8f22562c 405
d7ad3bed
EW
406sub cmd_dcommit {
407 my $head = shift;
c8cfa3e4 408 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 409 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 410 . "or stash them with `git stash'.\n";
d7ad3bed 411 $head ||= 'HEAD';
a8ae2623 412 my @refs;
13c823fb 413 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
59b0c24d
MM
414 if ($url) {
415 print "Committing to $url ...\n";
416 }
13c823fb 417 unless ($gs) {
a8ae2623 418 die "Unable to determine upstream SVN information from ",
59b0c24d 419 "$head history.\nPerhaps the repository is empty.";
a8ae2623 420 }
45bf473a 421 my $last_rev;
733a65aa 422 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
423 if ($_no_rebase && scalar(@$linear_refs) > 1) {
424 warn "Attempting to commit more than one change while ",
425 "--no-rebase is enabled.\n",
426 "If these changes depend on each other, re-running ",
7dfa16b9 427 "without --no-rebase may be required."
751eb395 428 }
c74d9acf
EW
429 while (1) {
430 my $d = shift @$linear_refs or last;
45bf473a
EW
431 unless (defined $last_rev) {
432 (undef, $last_rev, undef) = cmt_metadata("$d~1");
433 unless (defined $last_rev) {
d7ad3bed 434 fatal "Unable to extract revision information ",
207f1a75 435 "from commit $d~1";
45bf473a
EW
436 }
437 }
b22d4497
EW
438 if ($_dry_run) {
439 print "diff-tree $d~1 $d\n";
440 } else {
751eb395 441 my $cmt_rev;
d7ad3bed 442 my %ed_opts = ( r => $last_rev,
61395354 443 log => get_commit_entry($d)->{log},
645833b5 444 ra => Git::SVN::Ra->new($gs->full_url),
3caf320b
KA
445 config => SVN::Core::config_get_config(
446 $Git::SVN::Ra::config_dir
447 ),
61395354
EW
448 tree_a => "$d~1",
449 tree_b => $d,
450 editor_cb => sub {
451 print "Committed r$_[0]\n";
751eb395
EW
452 $cmt_rev = $_[0];
453 },
a8ae2623 454 svn_path => '');
61395354 455 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 456 print "No changes\n$d~1 == $d\n";
733a65aa 457 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 458 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 459 $parents->{$d};
d7ad3bed 460 }
751eb395 461 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 462 $last_rev = $cmt_rev;
751eb395
EW
463 next if $_no_rebase;
464
465 # we always want to rebase against the current HEAD,
466 # not any head that was passed to us
c74d9acf 467 my @diff = command('diff-tree', $d,
751eb395
EW
468 $gs->refname, '--');
469 my @finish;
470 if (@diff) {
471 @finish = rebase_cmd();
c74d9acf 472 print STDERR "W: $d and ", $gs->refname,
751eb395 473 " differ, using @finish:\n",
c74d9acf 474 join("\n", @diff), "\n";
751eb395
EW
475 } else {
476 print "No changes between current HEAD and ",
477 $gs->refname,
478 "\nResetting to the latest ",
479 $gs->refname, "\n";
480 @finish = qw/reset --mixed/;
481 }
482 command_noisy(@finish, $gs->refname);
c74d9acf
EW
483 if (@diff) {
484 @refs = ();
485 my ($url_, $rev_, $uuid_, $gs_) =
486 working_head_info($head, \@refs);
487 my ($linear_refs_, $parents_) =
488 linearize_history($gs_, \@refs);
489 if (scalar(@$linear_refs) !=
490 scalar(@$linear_refs_)) {
491 fatal "# of revisions changed ",
492 "\nbefore:\n",
493 join("\n", @$linear_refs),
494 "\n\nafter:\n",
495 join("\n", @$linear_refs_), "\n",
496 'If you are attempting to commit ',
497 "merges, try running:\n\t",
498 'git rebase --interactive',
499 '--preserve-merges ',
500 $gs->refname,
501 "\nBefore dcommitting";
502 }
503 if ($url_ ne $url) {
504 fatal "URL mismatch after rebase: ",
505 "$url_ != $url";
506 }
507 if ($uuid_ ne $uuid) {
508 fatal "uuid mismatch after rebase: ",
509 "$uuid_ != $uuid";
510 }
511 # remap parents
512 my (%p, @l, $i);
513 for ($i = 0; $i < scalar @$linear_refs; $i++) {
514 my $new = $linear_refs_->[$i] or next;
515 $p{$new} =
516 $parents->{$linear_refs->[$i]};
517 push @l, $new;
518 }
519 $parents = \%p;
520 $linear_refs = \@l;
521 }
b22d4497
EW
522 }
523 }
3157dd9e 524 unlink $gs->{index};
b22d4497
EW
525}
526
26e60160 527sub cmd_find_rev {
ea14e6c5
MAL
528 my $revision_or_hash = shift or die "SVN or git revision required ",
529 "as a command-line argument\n";
26e60160
AR
530 my $result;
531 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
532 my $head = shift;
533 $head ||= 'HEAD';
534 my @refs;
535 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
536 unless ($gs) {
537 die "Unable to determine upstream SVN information from ",
538 "$head history\n";
26e60160 539 }
b3cb7e45 540 my $desired_revision = substr($revision_or_hash, 1);
060610c5 541 $result = $gs->rev_map_get($desired_revision);
26e60160
AR
542 } else {
543 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
544 $result = $rev;
545 }
546 print "$result\n" if $result;
547}
548
905f8b7d
EW
549sub cmd_rebase {
550 command_noisy(qw/update-index --refresh/);
13c823fb
EW
551 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
552 unless ($gs) {
905f8b7d
EW
553 die "Unable to determine upstream SVN information from ",
554 "working tree history\n";
555 }
905f8b7d
EW
556 if (command(qw/diff-index HEAD --/)) {
557 print STDERR "Cannot rebase with uncommited changes:\n";
558 command_noisy('status');
559 exit 1;
560 }
dee41f3e 561 unless ($_local) {
cec0d5a3
SG
562 # rebase will checkout for us, so no need to do it explicitly
563 $_no_checkout = 'true';
dee41f3e
EW
564 $_fetch_all ? $gs->fetch_all : $gs->fetch;
565 }
905f8b7d
EW
566 command_noisy(rebase_cmd(), $gs->refname);
567}
568
5969cbe1 569sub cmd_show_ignore {
13c823fb
EW
570 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
571 $gs ||= Git::SVN->new;
5969cbe1 572 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
01bdab84
BS
573 $gs->prop_walk($gs->{path}, $r, sub {
574 my ($gs, $path, $props) = @_;
575 print STDOUT "\n# $path\n";
576 my $s = $props->{'svn:ignore'} or return;
577 $s =~ s/[\r\n]+/\n/g;
578 chomp $s;
579 $s =~ s#^#$path#gm;
580 print STDOUT "$s\n";
581 });
a5e0cedc
EW
582}
583
2d879792
VK
584sub cmd_show_externals {
585 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
586 $gs ||= Git::SVN->new;
587 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
588 $gs->prop_walk($gs->{path}, $r, sub {
589 my ($gs, $path, $props) = @_;
590 print STDOUT "\n# $path\n";
591 my $s = $props->{'svn:externals'} or return;
592 $s =~ s/[\r\n]+/\n/g;
593 chomp $s;
594 $s =~ s#^#$path#gm;
595 print STDOUT "$s\n";
596 });
597}
598
d05ddec5
BS
599sub cmd_create_ignore {
600 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
601 $gs ||= Git::SVN->new;
602 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
603 $gs->prop_walk($gs->{path}, $r, sub {
604 my ($gs, $path, $props) = @_;
605 # $path is of the form /path/to/dir/
606 my $ignore = '.' . $path . '.gitignore';
607 my $s = $props->{'svn:ignore'} or return;
608 open(GITIGNORE, '>', $ignore)
207f1a75 609 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5
BS
610 $s =~ s/[\r\n]+/\n/g;
611 chomp $s;
612 # Prefix all patterns so that the ignore doesn't apply
613 # to sub-directories.
614 $s =~ s#^#/#gm;
615 print GITIGNORE "$s\n";
616 close(GITIGNORE)
207f1a75 617 or fatal("Failed to close `$ignore': $!");
c4c66b26 618 command_noisy('add', '-f', $ignore);
d05ddec5
BS
619 });
620}
621
b2b3ada7
DK
622sub canonicalize_path {
623 my ($path) = @_;
e6fefa92
DK
624 my $dot_slash_added = 0;
625 if (substr($path, 0, 1) ne "/") {
626 $path = "./" . $path;
627 $dot_slash_added = 1;
628 }
b2b3ada7
DK
629 # File::Spec->canonpath doesn't collapse x/../y into y (for a
630 # good reason), so let's do this manually.
631 $path =~ s#/+#/#g;
632 $path =~ s#/\.(?:/|$)#/#g;
633 $path =~ s#/[^/]+/\.\.##g;
634 $path =~ s#/$##g;
e6fefa92 635 $path =~ s#^\./## if $dot_slash_added;
b2b3ada7
DK
636 return $path;
637}
638
15153451
BS
639# get_svnprops(PATH)
640# ------------------
51e057cf 641# Helper for cmd_propget and cmd_proplist below.
15153451
BS
642sub get_svnprops {
643 my $path = shift;
644 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
645 $gs ||= Git::SVN->new;
646
647 # prefix THE PATH by the sub-directory from which the user
648 # invoked us.
649 $path = $cmd_dir_prefix . $path;
207f1a75 650 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
651 my $is_dir = -d $path ? 1 : 0;
652 $path = $gs->{path} . '/' . $path;
653
654 # canonicalize the path (otherwise libsvn will abort or fail to
655 # find the file)
b2b3ada7 656 $path = canonicalize_path($path);
15153451
BS
657
658 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
659 my $props;
660 if ($is_dir) {
661 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
662 }
663 else {
664 (undef, $props) = $gs->ra->get_file($path, $r, undef);
665 }
666 return $props;
667}
668
669# cmd_propget (PROP, PATH)
670# ------------------------
671# Print the SVN property PROP for PATH.
672sub cmd_propget {
673 my ($prop, $path) = @_;
674 $path = '.' if not defined $path;
675 usage(1) if not defined $prop;
676 my $props = get_svnprops($path);
677 if (not defined $props->{$prop}) {
207f1a75 678 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
679 }
680 print $props->{$prop} . "\n";
681}
682
51e057cf
BS
683# cmd_proplist (PATH)
684# -------------------
685# Print the list of SVN properties for PATH.
686sub cmd_proplist {
687 my $path = shift;
688 $path = '.' if not defined $path;
689 my $props = get_svnprops($path);
690 print "Properties on '$path':\n";
691 foreach (sort keys %{$props}) {
692 print " $_\n";
693 }
694}
695
8164b652 696sub cmd_multi_init {
9d55b41a 697 my $url = shift;
98327e58
EW
698 unless (defined $_trunk || defined $_branches || defined $_tags) {
699 usage(1);
9d55b41a 700 }
dc431666
EW
701
702 # there are currently some bugs that prevent multi-init/multi-fetch
703 # setups from working well without this.
704 $Git::SVN::_minimize_url = 1;
705
8164b652 706 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
707 if (defined $url) {
708 $url =~ s#/+$##;
709 init_subdir(@_);
710 }
f30603fc 711 do_git_init_db();
98327e58 712 if (defined $_trunk) {
706587fc
EW
713 my $trunk_ref = $_prefix . 'trunk';
714 # try both old-style and new-style lookups:
715 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 716 unless ($gs_trunk) {
706587fc
EW
717 my ($trunk_url, $trunk_path) =
718 complete_svn_url($url, $_trunk);
719 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
720 undef, $trunk_ref);
98327e58 721 }
c35b96e7 722 }
706587fc 723 return unless defined $_branches || defined $_tags;
e7db67e6
EW
724 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
725 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
726 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
727}
728
1c8443b0 729sub cmd_multi_fetch {
0af9c9f9
EW
730 my $remotes = Git::SVN::read_all_remotes();
731 foreach my $repo_id (sort keys %$remotes) {
db03cd24 732 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
733 Git::SVN::fetch_all($repo_id, $remotes);
734 }
9d55b41a 735 }
9d55b41a
EW
736}
737
44320b9e
EW
738# this command is special because it requires no metadata
739sub cmd_commit_diff {
740 my ($ta, $tb, $url) = @_;
741 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 742 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 743 fatal($usage) if (!defined $ta || !defined $tb);
d3a840dc 744 my $svn_path;
44320b9e
EW
745 if (!defined $url) {
746 my $gs = eval { Git::SVN->new };
747 if (!$gs) {
748 fatal("Needed URL or usable git-svn --id in ",
749 "the command-line\n", $usage);
750 }
751 $url = $gs->{url};
d3a840dc 752 $svn_path = $gs->{path};
44320b9e
EW
753 }
754 unless (defined $_revision) {
755 fatal("-r|--revision is a required argument\n", $usage);
756 }
757 if (defined $_message && defined $_file) {
758 fatal("Both --message/-m and --file/-F specified ",
759 "for the commit message.\n",
207f1a75 760 "I have no idea what you mean");
44320b9e
EW
761 }
762 if (defined $_file) {
763 $_message = file_to_s($_file);
764 } else {
765 $_message ||= get_commit_entry($tb)->{log};
766 }
767 my $ra ||= Git::SVN::Ra->new($url);
d3a840dc 768 $svn_path ||= $ra->{svn_path};
44320b9e
EW
769 my $r = $_revision;
770 if ($r eq 'HEAD') {
771 $r = $ra->get_latest_revnum;
772 } elsif ($r !~ /^\d+$/) {
773 die "revision argument: $r not understood by git-svn\n";
774 }
61395354
EW
775 my %ed_opts = ( r => $r,
776 log => $_message,
777 ra => $ra,
778 tree_a => $ta,
779 tree_b => $tb,
780 editor_cb => sub { print "Committed r$_[0]\n" },
781 svn_path => $svn_path );
782 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
783 print "No changes\n$ta == $tb\n";
784 }
44320b9e
EW
785}
786
e6fefa92
DK
787sub cmd_info {
788 my $path = canonicalize_path(shift or ".");
789 unless (scalar(@_) == 0) {
790 die "Too many arguments specified\n";
791 }
792
793 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
794
795 if (!$file_type && !$diff_status) {
796 print STDERR "$path: (Not a versioned resource)\n\n";
797 return;
798 }
799
800 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
801 unless ($gs) {
802 die "Unable to determine upstream SVN information from ",
803 "working tree history\n";
804 }
805 my $full_url = $url . ($path eq "." ? "" : "/$path");
806
8b014d71
DK
807 if ($_url) {
808 print $full_url, "\n";
809 return;
810 }
811
e6fefa92
DK
812 my $result = "Path: $path\n";
813 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
814 $result .= "URL: " . $full_url . "\n";
815
a5460eb7
EW
816 eval {
817 my $repos_root = $gs->repos_root;
818 Git::SVN::remove_username($repos_root);
819 $result .= "Repository Root: $repos_root\n";
820 };
821 if ($@) {
822 $result .= "Repository Root: (offline)\n";
823 }
e6fefa92
DK
824 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
825 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
826
827 $result .= "Node Kind: " .
828 ($file_type eq "dir" ? "directory" : "file") . "\n";
829
830 my $schedule = $diff_status eq "A"
831 ? "add"
832 : ($diff_status eq "D" ? "delete" : "normal");
833 $result .= "Schedule: $schedule\n";
834
835 if ($diff_status eq "A") {
836 print $result, "\n";
837 return;
838 }
839
840 my ($lc_author, $lc_rev, $lc_date_utc);
841 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
842 my $log = command_output_pipe(@args);
843 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
844 while (<$log>) {
845 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
846 $lc_author = $1;
847 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
848 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
849 (undef, $lc_rev, undef) = ::extract_metadata($1);
850 }
851 }
852 close $log;
853
854 Git::SVN::Log::set_local_timezone();
855
856 $result .= "Last Changed Author: $lc_author\n";
857 $result .= "Last Changed Rev: $lc_rev\n";
858 $result .= "Last Changed Date: " .
859 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
860
861 if ($file_type ne "dir") {
862 my $text_last_updated_date =
863 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
864 $result .=
865 "Text Last Updated: " .
866 Git::SVN::Log::format_svn_date($text_last_updated_date) .
867 "\n";
868 my $checksum;
869 if ($diff_status eq "D") {
870 my ($fh, $ctx) =
871 command_output_pipe(qw(cat-file blob), "HEAD:$path");
872 if ($file_type eq "link") {
873 my $file_name = <$fh>;
8d7c4fad 874 $checksum = md5sum("link $file_name");
e6fefa92 875 } else {
8d7c4fad 876 $checksum = md5sum($fh);
e6fefa92
DK
877 }
878 command_close_pipe($fh, $ctx);
879 } elsif ($file_type eq "link") {
880 my $file_name =
881 command(qw(cat-file blob), "HEAD:$path");
882 $checksum =
8d7c4fad 883 md5sum("link " . $file_name);
e6fefa92
DK
884 } else {
885 open FILE, "<", $path or die $!;
8d7c4fad 886 $checksum = md5sum(\*FILE);
e6fefa92
DK
887 close FILE or die $!;
888 }
889 $result .= "Checksum: " . $checksum . "\n";
890 }
891
892 print $result, "\n";
893}
894
3397f9df
EW
895########################### utility functions #########################
896
905f8b7d
EW
897sub rebase_cmd {
898 my @cmd = qw/rebase/;
899 push @cmd, '-v' if $_verbose;
900 push @cmd, qw/--merge/ if $_merge;
901 push @cmd, "--strategy=$_strategy" if $_strategy;
902 @cmd;
903}
904
1e889ef3
EW
905sub post_fetch_checkout {
906 return if $_no_checkout;
907 my $gs = $Git::SVN::_head or return;
908 return if verify_ref('refs/heads/master^0');
909
910 my $valid_head = verify_ref('HEAD^0');
911 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
912 return if ($valid_head || !verify_ref('HEAD^0'));
913
914 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
915 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
916 return if -f $index;
917
7ae3df8c 918 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
919 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
920 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
921 print STDERR "Checked out HEAD:\n ",
922 $gs->full_url, " r", $gs->last_rev, "\n";
923}
924
98327e58
EW
925sub complete_svn_url {
926 my ($url, $path) = @_;
927 $path =~ s#/+$##;
98327e58 928 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
929 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
930 fatal("E: '$path' is not a complete URL ",
207f1a75 931 "and a separate URL is not specified");
98327e58 932 }
706587fc 933 return ($url, $path);
98327e58 934 }
706587fc 935 return ($path, '');
98327e58
EW
936}
937
9d55b41a 938sub complete_url_ls_init {
706587fc
EW
939 my ($ra, $repo_path, $switch, $pfx) = @_;
940 unless ($repo_path) {
9d55b41a
EW
941 print STDERR "W: $switch not specified\n";
942 return;
943 }
706587fc
EW
944 $repo_path =~ s#/+$##;
945 if ($repo_path =~ m#^[a-z\+]+://#) {
946 $ra = Git::SVN::Ra->new($repo_path);
947 $repo_path = '';
e7db67e6 948 } else {
706587fc 949 $repo_path =~ s#^/+##;
e7db67e6 950 unless ($ra) {
706587fc 951 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 952 "and a separate URL is not specified");
8164b652 953 }
e7db67e6 954 }
706587fc 955 my $url = $ra->{url};
b4d57e5e
EW
956 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
957 my $k = "svn-remote.$gs->{repo_id}.url";
958 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
959 if ($orig_url && ($orig_url ne $gs->{url})) {
960 die "$k already set: $orig_url\n",
961 "wanted to set to: $gs->{url}\n";
88cf4107 962 }
b4d57e5e 963 command_oneline('config', $k, $gs->{url}) unless $orig_url;
ed0b9d43 964 my $remote_path = "$ra->{svn_path}/$repo_path";
b4d57e5e
EW
965 $remote_path =~ s#/+#/#g;
966 $remote_path =~ s#^/##g;
ed0b9d43 967 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
968 my ($n) = ($switch =~ /^--(\w+)/);
969 if (length $pfx && $pfx !~ m#/$#) {
970 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 971 }
b4d57e5e
EW
972 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
973 "$remote_path:refs/remotes/$pfx*");
9d55b41a
EW
974}
975
aef4e921
EW
976sub verify_ref {
977 my ($ref) = @_;
2c5c1d53
EW
978 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
979 { STDERR => 0 }); };
aef4e921
EW
980}
981
a5e0cedc 982sub get_tree_from_treeish {
cf52b8f0 983 my ($treeish) = @_;
44320b9e 984 # $treeish can be a symbolic ref, too:
aef4e921 985 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
986 my $expected;
987 while ($type eq 'tag') {
aef4e921 988 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
989 }
990 if ($type eq 'commit') {
aef4e921
EW
991 $expected = (grep /^tree /, command(qw/cat-file commit/,
992 $treeish))[0];
44320b9e 993 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
994 die "Unable to get tree from $treeish\n" unless $expected;
995 } elsif ($type eq 'tree') {
996 $expected = $treeish;
997 } else {
998 die "$treeish is a $type, expected tree, tag or commit\n";
999 }
a5e0cedc
EW
1000 return $expected;
1001}
1002
44320b9e
EW
1003sub get_commit_entry {
1004 my ($treeish) = shift;
1005 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1006 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1007 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1008 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1009
44320b9e 1010 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1011 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1012 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1013 $type, $treeish);
3397f9df
EW
1014 my $in_msg = 0;
1015 while (<$msg_fh>) {
1016 if (!$in_msg) {
1017 $in_msg = 1 if (/^\s*$/);
df746c5a 1018 } elsif (/^git-svn-id: /) {
44320b9e
EW
1019 # skip this for now, we regenerate the
1020 # correct one on re-fetch anyways
1021 # TODO: set *:merge properties or like...
3397f9df 1022 } else {
44320b9e 1023 print $log_fh $_ or croak $!;
3397f9df
EW
1024 }
1025 }
aef4e921 1026 command_close_pipe($msg_fh, $ctx);
3397f9df 1027 }
44320b9e 1028 close $log_fh or croak $!;
3397f9df
EW
1029
1030 if ($_edit || ($type eq 'tree')) {
1031 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
1032 # TODO: strip out spaces, comments, like git-commit.sh
1033 system($editor, $commit_editmsg);
3397f9df 1034 }
44320b9e
EW
1035 rename $commit_editmsg, $commit_msg or croak $!;
1036 open $log_fh, '<', $commit_msg or croak $!;
1037 { local $/; chomp($log_entry{log} = <$log_fh>); }
1038 close $log_fh or croak $!;
1039 unlink $commit_msg;
1040 \%log_entry;
a5e0cedc
EW
1041}
1042
3397f9df
EW
1043sub s_to_file {
1044 my ($str, $file, $mode) = @_;
1045 open my $fd,'>',$file or croak $!;
1046 print $fd $str,"\n" or croak $!;
1047 close $fd or croak $!;
1048 chmod ($mode &~ umask, $file) if (defined $mode);
1049}
1050
1051sub file_to_s {
1052 my $file = shift;
1053 open my $fd,'<',$file or croak "$!: file: $file\n";
1054 local $/;
1055 my $ret = <$fd>;
1056 close $fd or croak $!;
1057 $ret =~ s/\s*$//s;
1058 return $ret;
1059}
1060
eeb0abe0
EW
1061# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1062sub load_authors {
1063 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1064 my $log = $cmd eq 'log';
eeb0abe0
EW
1065 while (<$authors>) {
1066 chomp;
575d025c 1067 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1068 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1069 if ($log) {
1070 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1071 } else {
1072 $users{$user} = [$name, $email];
1073 }
79bb8d88
EW
1074 }
1075 close $authors or croak $!;
1076}
1077
e0d10e1c 1078# convert GetOpt::Long specs for use by git-config
b8c92cad 1079sub read_repo_config {
706587fc 1080 return unless -d $ENV{GIT_DIR};
b8c92cad 1081 my $opts = shift;
97ae0911 1082 my @config_only;
b8c92cad 1083 foreach my $o (keys %$opts) {
97ae0911
EW
1084 # if we have mixedCase and a long option-only, then
1085 # it's a config-only variable that we don't need for
1086 # the command-line.
1087 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1088 my $v = $opts->{$o};
97ae0911 1089 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1090 $key =~ s/-//g;
e0d10e1c 1091 my $arg = 'git-config';
b8c92cad
EW
1092 $arg .= ' --int' if ($o =~ /[:=]i$/);
1093 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1094 if (ref $v eq 'ARRAY') {
1095 chomp(my @tmp = `$arg --get-all svn.$key`);
1096 @$v = @tmp if @tmp;
1097 } else {
1098 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1099 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1100 $$v = $tmp;
1101 }
1102 }
1103 }
97ae0911 1104 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1105}
1106
79bb8d88 1107sub extract_metadata {
c1927a85 1108 my $id = shift or return (undef, undef, undef);
3dfab993 1109 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
79bb8d88 1110 \s([a-f\d\-]+)$/x);
e70dc780 1111 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1112 # some of the original repositories I made had
82e5a82f 1113 # identifiers like this:
3dfab993 1114 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
79bb8d88
EW
1115 }
1116 return ($url, $rev, $uuid);
1117}
1118
c1927a85
EW
1119sub cmt_metadata {
1120 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1121 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1122}
1123
905f8b7d
EW
1124sub working_head_info {
1125 my ($head, $refs) = @_;
b6309ac2 1126 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
05b4df31 1127 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1128 my $hash;
40cb8f8f 1129 my %max;
3dfab993
SV
1130 while (<$fh>) {
1131 if ( m{^commit ($::sha1)$} ) {
1132 unshift @$refs, $hash if $hash and $refs;
1133 $hash = $1;
1134 next;
1135 }
1136 next unless s{^\s*(git-svn-id:)}{$1};
1137 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1138 if (defined $url && defined $rev) {
40cb8f8f 1139 next if $max{$url} and $max{$url} < $rev;
13c823fb 1140 if (my $gs = Git::SVN->find_by_url($url)) {
060610c5 1141 my $c = $gs->rev_map_get($rev);
b03c7a63 1142 if ($c && $c eq $hash) {
13c823fb
EW
1143 close $fh; # break the pipe
1144 return ($url, $rev, $uuid, $gs);
40cb8f8f 1145 } else {
060610c5 1146 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1147 }
1148 }
1149 }
905f8b7d 1150 }
13c823fb
EW
1151 command_close_pipe($fh, $ctx);
1152 (undef, undef, undef, undef);
905f8b7d
EW
1153}
1154
733a65aa
EW
1155sub read_commit_parents {
1156 my ($parents, $c) = @_;
7b02b85a
EW
1157 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1158 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1159 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1160}
1161
1162sub linearize_history {
1163 my ($gs, $refs) = @_;
1164 my %parents;
1165 foreach my $c (@$refs) {
1166 read_commit_parents(\%parents, $c);
1167 }
1168
1169 my @linear_refs;
1170 my %skip = ();
1171 my $last_svn_commit = $gs->last_commit;
1172 foreach my $c (reverse @$refs) {
1173 next if $c eq $last_svn_commit;
1174 last if $skip{$c};
1175
1176 unshift @linear_refs, $c;
1177 $skip{$c} = 1;
1178
1179 # we only want the first parent to diff against for linear
1180 # history, we save the rest to inject when we finalize the
1181 # svn commit
1182 my $fp_a = verify_ref("$c~1");
1183 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1184 if (!$fp_a || !$fp_b) {
1185 die "Commit $c\n",
1186 "has no parent commit, and therefore ",
1187 "nothing to diff against.\n",
1188 "You should be working from a repository ",
1189 "originally created by git-svn\n";
1190 }
1191 if ($fp_a ne $fp_b) {
1192 die "$c~1 = $fp_a, however parsing commit $c ",
1193 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1194 }
1195
1196 foreach my $p (@{$parents{$c}}) {
1197 $skip{$p} = 1;
1198 }
1199 }
1200 (\@linear_refs, \%parents);
1201}
1202
e6fefa92
DK
1203sub find_file_type_and_diff_status {
1204 my ($path) = @_;
1205 return ('dir', '') if $path eq '.';
1206
1207 my $diff_output =
1208 command_oneline(qw(diff --cached --name-status --), $path) || "";
1209 my $diff_status = (split(' ', $diff_output))[0] || "";
1210
1211 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1212
1213 return (undef, undef) if !$diff_status && !$ls_tree;
1214
1215 if ($diff_status eq "A") {
1216 return ("link", $diff_status) if -l $path;
1217 return ("dir", $diff_status) if -d $path;
1218 return ("file", $diff_status);
1219 }
1220
1221 my $mode = (split(' ', $ls_tree))[0] || "";
1222
1223 return ("link", $diff_status) if $mode eq "120000";
1224 return ("dir", $diff_status) if $mode eq "040000";
1225 return ("file", $diff_status);
1226}
1227
b2b3ada7
DK
1228sub md5sum {
1229 my $arg = shift;
1230 my $ref = ref $arg;
1231 my $md5 = Digest::MD5->new();
1232 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1233 $md5->addfile($arg) or croak $!;
1234 } elsif ($ref eq 'SCALAR') {
1235 $md5->add($$arg) or croak $!;
1236 } elsif (!$ref) {
1237 $md5->add($arg) or croak $!;
1238 } else {
1239 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1240 }
1241 return $md5->hexdigest();
1242}
1243
9b981fc6
EW
1244package Git::SVN;
1245use strict;
1246use warnings;
060610c5
EW
1247use Fcntl qw/:DEFAULT :seek/;
1248use constant rev_map_fmt => 'NH40';
ecc712dd 1249use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 1250 $_repack $_repack_flags $_use_svm_props $_head
70ae04e4
AW
1251 $_use_svnsync_props $no_reuse_existing $_minimize_url
1252 $_use_log_author/;
9b981fc6
EW
1253use Carp qw/croak/;
1254use File::Path qw/mkpath/;
373274f9 1255use File::Copy qw/copy/;
9b981fc6
EW
1256use IPC::Open3;
1257
94bc914c
KW
1258my ($_gc_nr, $_gc_period);
1259
9b981fc6
EW
1260# properties that we do not log:
1261my %SKIP_PROP;
1262BEGIN {
1263 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1264 svn:special svn:executable
1265 svn:entry:committed-rev
1266 svn:entry:last-author
1267 svn:entry:uuid
1268 svn:entry:committed-date/;
91b03282
EW
1269
1270 # some options are read globally, but can be overridden locally
1271 # per [svn-remote "..."] section. Command-line options will *NOT*
1272 # override options set in an [svn-remote "..."] section
c5f71ad0
SV
1273 no strict 'refs';
1274 for my $option (qw/follow_parent no_metadata use_svm_props
1275 use_svnsync_props/) {
1276 my $key = $option;
91b03282 1277 $key =~ tr/_//d;
c5f71ad0
SV
1278 my $prop = "-$option";
1279 *$option = sub {
1280 my ($self) = @_;
1281 return $self->{$prop} if exists $self->{$prop};
1282 my $k = "svn-remote.$self->{repo_id}.$key";
1283 eval { command_oneline(qw/config --get/, $k) };
1284 if ($@) {
1285 $self->{$prop} = ${"Git::SVN::_$option"};
91b03282 1286 } else {
c5f71ad0
SV
1287 my $v = command_oneline(qw/config --bool/,$k);
1288 $self->{$prop} = $v eq 'false' ? 0 : 1;
91b03282 1289 }
c5f71ad0
SV
1290 return $self->{$prop};
1291 }
91b03282 1292 }
9b981fc6
EW
1293}
1294
321b1842
EW
1295my (%LOCKFILES, %INDEX_FILES);
1296END {
1297 unlink keys %LOCKFILES if %LOCKFILES;
1298 unlink keys %INDEX_FILES if %INDEX_FILES;
1299}
373274f9 1300
4bb9ed04
EW
1301sub resolve_local_globs {
1302 my ($url, $fetch, $glob_spec) = @_;
1303 return unless defined $glob_spec;
1304 my $ref = $glob_spec->{ref};
1305 my $path = $glob_spec->{path};
1306 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1307 next unless m#^refs/remotes/$ref->{regex}$#;
1308 my $p = $1;
bf655fd7
RE
1309 my $pathname = desanitize_refname($path->full_path($p));
1310 my $refname = desanitize_refname($ref->full_path($p));
4bb9ed04
EW
1311 if (my $existing = $fetch->{$pathname}) {
1312 if ($existing ne $refname) {
1313 die "Refspec conflict:\n",
1314 "existing: refs/remotes/$existing\n",
1315 " globbed: refs/remotes/$refname\n";
1316 }
1317 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 1318 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
1319 "refs/remotes/$refname: '$url' not found in '$u'\n";
1320 if ($pathname ne $u) {
1321 warn "W: Refspec glob conflict ",
1322 "(ref: refs/remotes/$refname):\n",
1323 "expected path: $pathname\n",
1324 " real path: $u\n",
1325 "Continuing ahead with $u\n";
1326 next;
1327 }
1328 } else {
4bb9ed04
EW
1329 $fetch->{$pathname} = $refname;
1330 }
1331 }
1332}
1333
e98671e5
EW
1334sub parse_revision_argument {
1335 my ($base, $head) = @_;
1336 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1337 return ($base, $head);
1338 }
1339 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1340 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1341 return ($head, $head) if ($::_revision eq 'HEAD');
1342 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1343 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1344 die "revision argument: $::_revision not understood by git-svn\n";
1345}
1346
0af9c9f9 1347sub fetch_all {
4bb9ed04 1348 my ($repo_id, $remotes) = @_;
905f8b7d
EW
1349 if (ref $repo_id) {
1350 my $gs = $repo_id;
1351 $repo_id = undef;
1352 $repo_id = $gs->{repo_id};
1353 }
1354 $remotes ||= read_all_remotes();
7447b4bc
EW
1355 my $remote = $remotes->{$repo_id} or
1356 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 1357 my $fetch = $remote->{fetch};
7447b4bc 1358 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 1359 my (@gs, @globs);
0af9c9f9 1360 my $ra = Git::SVN::Ra->new($url);
26a62d57 1361 my $uuid = $ra->get_uuid;
0af9c9f9 1362 my $head = $ra->get_latest_revnum;
28710f74 1363 my $base = defined $fetch ? $head : 0;
e518192f
EW
1364
1365 # read the max revs for wildcard expansion (branches/*, tags/*)
1366 foreach my $t (qw/branches tags/) {
1367 defined $remote->{$t} or next;
1368 push @globs, $remote->{$t};
93f2689c
EW
1369 my $max_rev = eval { tmp_config(qw/--int --get/,
1370 "svn-remote.$repo_id.${t}-maxRev") };
1371 if (defined $max_rev && ($max_rev < $base)) {
1372 $base = $max_rev;
d6d3346b
EW
1373 } elsif (!defined $max_rev) {
1374 $base = 0;
e518192f
EW
1375 }
1376 }
1377
db03cd24
EW
1378 if ($fetch) {
1379 foreach my $p (sort keys %$fetch) {
1380 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
060610c5 1381 my $lr = $gs->rev_map_max;
db03cd24
EW
1382 if (defined $lr) {
1383 $base = $lr if ($lr < $base);
1384 }
1385 push @gs, $gs;
0af9c9f9 1386 }
0af9c9f9 1387 }
e98671e5
EW
1388
1389 ($base, $head) = parse_revision_argument($base, $head);
e518192f 1390 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
1391}
1392
47e39c55
EW
1393sub read_all_remotes {
1394 my $r = {};
8b8fc068 1395 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
47e39c55 1396 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
46cf98ba
EW
1397 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1398 $local_ref =~ s{^/}{};
1399 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
47e39c55
EW
1400 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1401 $r->{$1}->{url} = $2;
4bb9ed04
EW
1402 } elsif (m!^(.+)\.(branches|tags)=
1403 (.*):refs/remotes/(.+)\s*$/!x) {
1404 my ($p, $g) = ($3, $4);
1405 my $rs = $r->{$1}->{$2} = {
e518192f 1406 t => $2,
93f2689c 1407 remote => $1,
4bb9ed04
EW
1408 path => Git::SVN::GlobSpec->new($p),
1409 ref => Git::SVN::GlobSpec->new($g) };
1410 if (length($rs->{ref}->{right}) != 0) {
1411 die "The '*' glob character must be the last ",
1412 "character of '$g'\n";
1413 }
47e39c55
EW
1414 }
1415 }
1416 $r;
1417}
1418
ecc712dd 1419sub init_vars {
94bc914c 1420 $_gc_nr = $_gc_period = 1000;
af788a6e
KW
1421 if (defined $_repack || defined $_repack_flags) {
1422 warn "Repack options are obsolete; they have no effect.\n";
1423 }
ecc712dd
EW
1424}
1425
b805b44a 1426sub verify_remotes_sanity {
536c4b09 1427 return unless -d $ENV{GIT_DIR};
b805b44a
EW
1428 my %seen;
1429 foreach (command(qw/config -l/)) {
1430 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1431 if ($seen{$1}) {
1432 die "Remote ref refs/remote/$1 is tracked by",
1433 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1434 "Please resolve this ambiguity in ",
1435 "your git configuration file before ",
1436 "continuing\n";
1437 }
1438 $seen{$1} = $_;
1439 }
1440 }
1441}
1442
47e39c55 1443# we allow more chars than remotes2config.sh...
706587fc
EW
1444sub sanitize_remote_name {
1445 my ($name) = @_;
47e39c55 1446 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
706587fc
EW
1447 $name;
1448}
1449
e6434f87
EW
1450sub find_existing_remote {
1451 my ($url, $remotes) = @_;
befc9adc 1452 return undef if $no_reuse_existing;
e6434f87
EW
1453 my $existing;
1454 foreach my $repo_id (keys %$remotes) {
1455 my $u = $remotes->{$repo_id}->{url} or next;
1456 next if $u ne $url;
1457 $existing = $repo_id;
1458 last;
1459 }
1460 $existing;
1461}
b805b44a 1462
e6434f87 1463sub init_remote_config {
d8115c51 1464 my ($self, $url, $no_write) = @_;
e6434f87
EW
1465 $url =~ s!/+$!!; # strip trailing slash
1466 my $r = read_all_remotes();
1467 my $existing = find_existing_remote($url, $r);
1468 if ($existing) {
e518192f
EW
1469 unless ($no_write) {
1470 print STDERR "Using existing ",
1471 "[svn-remote \"$existing\"]\n";
1472 }
e6434f87 1473 $self->{repo_id} = $existing;
4a1bb4c3 1474 } elsif ($_minimize_url) {
e6434f87
EW
1475 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1476 $existing = find_existing_remote($min_url, $r);
1477 if ($existing) {
e518192f
EW
1478 unless ($no_write) {
1479 print STDERR "Using existing ",
1480 "[svn-remote \"$existing\"]\n";
1481 }
e6434f87
EW
1482 $self->{repo_id} = $existing;
1483 }
1484 if ($min_url ne $url) {
e518192f
EW
1485 unless ($no_write) {
1486 print STDERR "Using higher level of URL: ",
1487 "$url => $min_url\n";
1488 }
e6434f87
EW
1489 my $old_path = $self->{path};
1490 $self->{path} = $url;
4e9f6cc7 1491 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1492 if (length $old_path) {
1493 $self->{path} .= "/$old_path";
1494 }
1495 $url = $min_url;
1496 }
1497 }
1498 my $orig_url;
1499 if (!$existing) {
b805b44a 1500 # verify that we aren't overwriting anything:
e6434f87 1501 $orig_url = eval {
706587fc 1502 command_oneline('config', '--get',
e6434f87 1503 "svn-remote.$self->{repo_id}.url")
706587fc 1504 };
b805b44a 1505 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1506 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1507 "$orig_url\nwanted to set to: $url\n";
1508 }
9b981fc6 1509 }
e6434f87
EW
1510 my ($xrepo_id, $xpath) = find_ref($self->refname);
1511 if (defined $xpath) {
1512 die "svn-remote.$xrepo_id.fetch already set to track ",
1513 "$xpath:refs/remotes/", $self->refname, "\n";
1514 }
d8115c51
EW
1515 unless ($no_write) {
1516 command_noisy('config',
1517 "svn-remote.$self->{repo_id}.url", $url);
46cf98ba 1518 $self->{path} =~ s{^/}{};
d8115c51
EW
1519 command_noisy('config', '--add',
1520 "svn-remote.$self->{repo_id}.fetch",
1521 "$self->{path}:".$self->refname);
1522 }
9b981fc6 1523 $self->{url} = $url;
e6434f87
EW
1524}
1525
a8ae2623
EW
1526sub find_by_url { # repos_root and, path are optional
1527 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1528
1a97a506 1529 return undef unless defined $full_url;
56973d20
AR
1530 remove_username($full_url);
1531 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1532 my $remotes = read_all_remotes();
1533 if (defined $full_url && defined $repos_root && !defined $path) {
1534 $path = $full_url;
1535 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1536 }
1537 foreach my $repo_id (keys %$remotes) {
1538 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1539 remove_username($u);
a8ae2623
EW
1540 next if defined $repos_root && $repos_root ne $u;
1541
1542 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1543 foreach (qw/branches tags/) {
1544 resolve_local_globs($u, $fetch,
1545 $remotes->{$repo_id}->{$_});
1546 }
1547 my $p = $path;
0bb91d9a 1548 my $rwr = rewrite_root({repo_id => $repo_id});
a8ae2623
EW
1549 unless (defined $p) {
1550 $p = $full_url;
0bb91d9a
JG
1551 my $z = $u;
1552 if ($rwr) {
1553 $z = $rwr;
1554 }
1555 $p =~ s#^\Q$z\E(?:/|$)## or next;
a8ae2623
EW
1556 }
1557 foreach my $f (keys %$fetch) {
1558 next if $f ne $p;
1559 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1560 }
1561 }
1562 undef;
1563}
1564
e6434f87 1565sub init {
d8115c51 1566 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1567 my $self = _new($class, $repo_id, $ref_id, $path);
1568 if (defined $url) {
d8115c51 1569 $self->init_remote_config($url, $no_write);
e6434f87 1570 }
9b981fc6
EW
1571 $self;
1572}
1573
706587fc
EW
1574sub find_ref {
1575 my ($ref_id) = @_;
1576 foreach (command(qw/config -l/)) {
1577 next unless m!^svn-remote\.(.+)\.fetch=
1578 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1579 my ($repo_id, $path, $ref) = ($1, $2, $3);
1580 if ($ref eq $ref_id) {
1581 $path = '' if ($path =~ m#^\./?#);
1582 return ($repo_id, $path);
1583 }
1584 }
1585 (undef, undef, undef);
1586}
1587
9b981fc6 1588sub new {
706587fc
EW
1589 my ($class, $ref_id, $repo_id, $path) = @_;
1590 if (defined $ref_id && !defined $repo_id && !defined $path) {
1591 ($repo_id, $path) = find_ref($ref_id);
1592 if (!defined $repo_id) {
1593 die "Could not find a \"svn-remote.*.fetch\" key ",
1594 "in the repository configuration matching: ",
1595 "refs/remotes/$ref_id\n";
1596 }
1597 }
1598 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1599 if (!defined $self->{path} || !length $self->{path}) {
1600 my $fetch = command_oneline('config', '--get',
1601 "svn-remote.$repo_id.fetch",
1602 ":refs/remotes/$ref_id\$") or
1603 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1604 "\":refs/remotes/$ref_id\$\" in config\n";
1605 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1606 }
706587fc
EW
1607 $self->{url} = command_oneline('config', '--get',
1608 "svn-remote.$repo_id.url") or
1609 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1610 $self->rebuild;
9b981fc6
EW
1611 $self;
1612}
1613
bf655fd7
RE
1614sub refname {
1615 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1616
1617 # It cannot end with a slash /, we'll throw up on this because
1618 # SVN can't have directories with a slash in their name, either:
1619 if ($refname =~ m{/$}) {
1620 die "ref: '$refname' ends with a trailing slash, this is ",
1621 "not permitted by git nor Subversion\n";
1622 }
1623
1624 # It cannot have ASCII control character space, tilde ~, caret ^,
1625 # colon :, question-mark ?, asterisk *, space, or open bracket [
1626 # anywhere.
1627 #
1628 # Additionally, % must be escaped because it is used for escaping
1629 # and we want our escaped refname to be reversible
1630 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1631
1632 # no slash-separated component can begin with a dot .
1633 # /.* becomes /%2E*
1634 $refname =~ s{/\.}{/%2E}g;
1635
1636 # It cannot have two consecutive dots .. anywhere
1637 # .. becomes %2E%2E
1638 $refname =~ s{\.\.}{%2E%2E}g;
1639
1640 return $refname;
1641}
1642
1643sub desanitize_refname {
1644 my ($refname) = @_;
1645 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1646 return $refname;
1647}
9b981fc6 1648
26a62d57
EW
1649sub svm_uuid {
1650 my ($self) = @_;
1651 return $self->{svm}->{uuid} if $self->svm;
1652 $self->ra;
1653 unless ($self->{svm}) {
1654 die "SVM UUID not cached, and reading remotely failed\n";
1655 }
1656 $self->{svm}->{uuid};
1657}
8a49ee97 1658
26a62d57
EW
1659sub svm {
1660 my ($self) = @_;
1661 return $self->{svm} if $self->{svm};
1662 my $svm;
8a49ee97
EW
1663 # see if we have it in our config, first:
1664 eval {
26a62d57
EW
1665 my $section = "svn-remote.$self->{repo_id}";
1666 $svm = {
93f2689c
EW
1667 source => tmp_config('--get', "$section.svm-source"),
1668 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1669 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1670 }
1671 };
befc9adc
EW
1672 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1673 $self->{svm} = $svm;
1674 }
26a62d57
EW
1675 $self->{svm};
1676}
1677
1678sub _set_svm_vars {
1679 my ($self, $ra) = @_;
db03cd24
EW
1680 return $ra if $self->svm;
1681
1682 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1683 "(svm:source, svm:uuid) ",
db03cd24
EW
1684 "from the following URLs:\n" );
1685 sub read_svm_props {
befc9adc
EW
1686 my ($self, $ra, $path, $r) = @_;
1687 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1688 my $src = $props->{'svm:source'};
db03cd24 1689 my $uuid = $props->{'svm:uuid'};
befc9adc 1690 return undef if (!$src || !$uuid);
26a62d57 1691
befc9adc 1692 chomp($src, $uuid);
26a62d57 1693
db03cd24
EW
1694 $uuid =~ m{^[0-9a-f\-]{30,}$}
1695 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1696
1697 # the '!' is used to mark the repos_root!/relative/path
1698 $src =~ s{/?!/?}{/};
db03cd24 1699 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1700 # username is of no interest
8a49ee97 1701 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1702
befc9adc
EW
1703 my $replace = $ra->{url};
1704 $replace .= "/$path" if length $path;
1705
db03cd24 1706 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1707 tmp_config("$section.svm-source", $src);
1708 tmp_config("$section.svm-replace", $replace);
1709 tmp_config("$section.svm-uuid", $uuid);
1710 $self->{svm} = {
1711 source => $src,
1712 uuid => $uuid,
1713 replace => $replace
1714 };
db03cd24
EW
1715 }
1716
1717 my $r = $ra->get_latest_revnum;
1718 my $path = $self->{path};
befc9adc 1719 my %tried;
db03cd24 1720 while (length $path) {
befc9adc
EW
1721 unless ($tried{"$self->{url}/$path"}) {
1722 return $ra if $self->read_svm_props($ra, $path, $r);
1723 $tried{"$self->{url}/$path"} = 1;
db03cd24 1724 }
befc9adc 1725 $path =~ s#/?[^/]+$##;
8a49ee97 1726 }
befc9adc
EW
1727 die "Path: '$path' should be ''\n" if $path ne '';
1728 return $ra if $self->read_svm_props($ra, $path, $r);
1729 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
1730
1731 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 1732 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1733 }
1734
1735 # nope, make sure we're connected to the repository root:
1736 my $ok;
1737 my @tried_b;
1738 $path = $ra->{svn_path};
db03cd24
EW
1739 $ra = Git::SVN::Ra->new($ra->{repos_root});
1740 while (length $path) {
befc9adc
EW
1741 unless ($tried{"$ra->{url}/$path"}) {
1742 $ok = $self->read_svm_props($ra, $path, $r);
1743 last if $ok;
1744 $tried{"$ra->{url}/$path"} = 1;
1745 }
1746 $path =~ s#/?[^/]+$##;
db03cd24 1747 }
befc9adc
EW
1748 die "Path: '$path' should be ''\n" if $path ne '';
1749 $ok ||= $self->read_svm_props($ra, $path, $r);
1750 $tried{"$ra->{url}/$path"} = 1;
db03cd24 1751 if (!$ok) {
befc9adc 1752 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1753 }
1754 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1755}
1756
62e349d2
EW
1757sub svnsync {
1758 my ($self) = @_;
1759 return $self->{svnsync} if $self->{svnsync};
1760
1761 if ($self->no_metadata) {
1762 die "Can't have both 'noMetadata' and ",
1763 "'useSvnsyncProps' options set!\n";
1764 }
1765 if ($self->rewrite_root) {
1766 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1767 "options set!\n";
1768 }
1769
1770 my $svnsync;
1771 # see if we have it in our config, first:
1772 eval {
1773 my $section = "svn-remote.$self->{repo_id}";
98fa5b68
EW
1774
1775 my $url = tmp_config('--get', "$section.svnsync-url");
1776 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1777 die "doesn't look right - svn:sync-from-url is '$url'\n";
1778
1779 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1780 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1781 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1782
1783 $svnsync = { url => $url, uuid => $uuid }
62e349d2
EW
1784 };
1785 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1786 return $self->{svnsync} = $svnsync;
1787 }
1788
1789 my $err = "useSvnsyncProps set, but failed to read " .
1790 "svnsync property: svn:sync-from-";
1791 my $rp = $self->ra->rev_proplist(0);
1792
1793 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
98fa5b68 1794 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
62e349d2
EW
1795 die "doesn't look right - svn:sync-from-url is '$url'\n";
1796
1797 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
98fa5b68 1798 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
62e349d2
EW
1799 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1800
1801 my $section = "svn-remote.$self->{repo_id}";
1802 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1803 tmp_config('--add', "$section.svnsync-url", $url);
1804 return $self->{svnsync} = { url => $url, uuid => $uuid };
1805}
1806
26a62d57
EW
1807# this allows us to memoize our SVN::Ra UUID locally and avoid a
1808# remote lookup (useful for 'git svn log').
1809sub ra_uuid {
1810 my ($self) = @_;
1811 unless ($self->{ra_uuid}) {
1812 my $key = "svn-remote.$self->{repo_id}.uuid";
1813 my $uuid = eval { tmp_config('--get', $key) };
1814 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1815 $self->{ra_uuid} = $uuid;
1816 } else {
1817 die "ra_uuid called without URL\n" unless $self->{url};
1818 $self->{ra_uuid} = $self->ra->get_uuid;
1819 tmp_config('--add', $key, $self->{ra_uuid});
1820 }
1821 }
1822 $self->{ra_uuid};
1823}
1824
a5460eb7
EW
1825sub _set_repos_root {
1826 my ($self, $repos_root) = @_;
1827 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1828 $repos_root ||= $self->ra->{repos_root};
1829 tmp_config($k, $repos_root);
1830 $repos_root;
1831}
1832
1833sub repos_root {
1834 my ($self) = @_;
1835 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1836 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1837}
1838
9b981fc6
EW
1839sub ra {
1840 my ($self) = shift;
8a49ee97 1841 my $ra = Git::SVN::Ra->new($self->{url});
a5460eb7 1842 $self->_set_repos_root($ra->{repos_root});
91b03282
EW
1843 if ($self->use_svm_props && !$self->{svm}) {
1844 if ($self->no_metadata) {
97ae0911
EW
1845 die "Can't have both 'noMetadata' and ",
1846 "'useSvmProps' options set!\n";
62e349d2
EW
1847 } elsif ($self->use_svnsync_props) {
1848 die "Can't have both 'useSvnsyncProps' and ",
1849 "'useSvmProps' options set!\n";
91b03282 1850 }
26a62d57 1851 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
1852 $self->{-want_revprops} = 1;
1853 }
1854 $ra;
9b981fc6
EW
1855}
1856
15710b6f
EW
1857sub rel_path {
1858 my ($self) = @_;
1859 my $repos_root = $self->ra->{repos_root};
1860 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
1861 my $url = $self->{url} .
1862 (length $self->{path} ? "/$self->{path}" : $self->{path});
1863 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1864 $url;
15710b6f
EW
1865}
1866
01bdab84
BS
1867# prop_walk(PATH, REV, SUB)
1868# -------------------------
1869# Recursively traverse PATH at revision REV and invoke SUB for each
1870# directory that contains a SVN property. SUB will be invoked as
1871# follows: &SUB(gs, path, props); where `gs' is this instance of
1872# Git::SVN, `path' the path to the directory where the properties
1873# `props' were found. The `path' will be relative to point of checkout,
1874# that is, if url://repo/trunk is the current Git branch, and that
1875# directory contains a sub-directory `d', SUB will be invoked with `/d/'
1876# as `path' (note the trailing `/').
1877sub prop_walk {
1878 my ($self, $path, $rev, $sub) = @_;
1879
35cda061 1880 $path =~ s#^/##;
01bdab84
BS
1881 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1882 $path =~ s#^/*#/#g;
9b981fc6 1883 my $p = $path;
01bdab84
BS
1884 # Strip the irrelevant part of the path.
1885 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1886 # Ensure the path is terminated by a `/'.
1887 $p =~ s#/*$#/#;
1888
1889 # The properties contain all the internal SVN stuff nobody
1890 # (usually) cares about.
1891 my $interesting_props = 0;
1892 foreach (keys %{$props}) {
1893 # If it doesn't start with `svn:', it must be a
1894 # user-defined property.
1895 ++$interesting_props and next if $_ !~ /^svn:/;
1896 # FIXME: Fragile, if SVN adds new public properties,
1897 # this needs to be updated.
1898 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1899 |eol-style|mime-type
1900 |externals|needs-lock)$/x;
1901 }
1902 &$sub($self, $p, $props) if $interesting_props;
1903
9b981fc6 1904 foreach (sort keys %$dirent) {
0dc03d6a 1905 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
67dac28b 1906 $self->prop_walk($p . $_, $rev, $sub);
9b981fc6
EW
1907 }
1908}
1909
3ebe8df7
EW
1910sub last_rev { ($_[0]->last_rev_commit)[0] }
1911sub last_commit { ($_[0]->last_rev_commit)[1] }
1912
9b981fc6
EW
1913# returns the newest SVN revision number and newest commit SHA1
1914sub last_rev_commit {
1915 my ($self) = @_;
1916 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1917 return ($self->{last_rev}, $self->{last_commit});
1918 }
d2866f9e 1919 my $c = ::verify_ref($self->refname.'^0');
91b03282 1920 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 1921 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
1922 if (defined $rev) {
1923 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1924 return ($rev, $c);
1925 }
1926 }
060610c5
EW
1927 my $map_path = $self->map_path;
1928 unless (-e $map_path) {
26a62d57
EW
1929 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1930 return (undef, undef);
1931 }
66ab84b9 1932 my ($rev, $commit) = $self->rev_map_max(1);
060610c5
EW
1933 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1934 return ($rev, $commit);
9b981fc6
EW
1935}
1936
3ebe8df7
EW
1937sub get_fetch_range {
1938 my ($self, $min, $max) = @_;
1939 $max ||= $self->ra->get_latest_revnum;
060610c5 1940 $min ||= $self->rev_map_max;
3ebe8df7 1941 (++$min, $max);
9b981fc6
EW
1942}
1943
8a49ee97 1944sub tmp_config {
93f2689c 1945 my (@args) = @_;
b7e5348c
EW
1946 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1947 my $config = "$ENV{GIT_DIR}/svn/.metadata";
38570a47 1948 if (! -f $config && -f $old_def_config) {
b7e5348c
EW
1949 rename $old_def_config, $config or
1950 die "Failed rename $old_def_config => $config: $!\n";
1951 }
8a49ee97 1952 my $old_config = $ENV{GIT_CONFIG};
93f2689c 1953 $ENV{GIT_CONFIG} = $config;
8a49ee97 1954 $@ = undef;
b4d57e5e
EW
1955 my @ret = eval {
1956 unless (-f $config) {
1957 mkfile($config);
1958 open my $fh, '>', $config or
1959 die "Can't open $config: $!\n";
1960 print $fh "; This file is used internally by ",
1961 "git-svn\n" or die
1962 "Couldn't write to $config: $!\n";
1963 print $fh "; You should not have to edit it\n" or
1964 die "Couldn't write to $config: $!\n";
1965 close $fh or die "Couldn't close $config: $!\n";
1966 }
1967 command('config', @args);
1968 };
8a49ee97
EW
1969 my $err = $@;
1970 if (defined $old_config) {
1971 $ENV{GIT_CONFIG} = $old_config;
1972 } else {
1973 delete $ENV{GIT_CONFIG};
1974 }
1975 die $err if $err;
1976 wantarray ? @ret : $ret[0];
1977}
1978
9b981fc6
EW
1979sub tmp_index_do {
1980 my ($self, $sub) = @_;
1981 my $old_index = $ENV{GIT_INDEX_FILE};
1982 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 1983 $@ = undef;
b4d57e5e
EW
1984 my @ret = eval {
1985 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1986 mkpath([$dir]) unless -d $dir;
1987 &$sub;
1988 };
8a49ee97
EW
1989 my $err = $@;
1990 if (defined $old_index) {
9b981fc6
EW
1991 $ENV{GIT_INDEX_FILE} = $old_index;
1992 } else {
1993 delete $ENV{GIT_INDEX_FILE};
1994 }
8a49ee97 1995 die $err if $err;
9b981fc6
EW
1996 wantarray ? @ret : $ret[0];
1997}
1998
1999sub assert_index_clean {
2000 my ($self, $treeish) = @_;
2001
2002 $self->tmp_index_do(sub {
2003 command_noisy('read-tree', $treeish) unless -e $self->{index};
2004 my $x = command_oneline('write-tree');
2005 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2006 /^tree ($::sha1)/mo);
e8d120bd
EW
2007 return if $y eq $x;
2008
2009 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2010 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2011 command_noisy('read-tree', $treeish);
9b981fc6
EW
2012 $x = command_oneline('write-tree');
2013 if ($y ne $x) {
2014 ::fatal "trees ($treeish) $y != $x\n",
207f1a75 2015 "Something is seriously wrong...";
9b981fc6
EW
2016 }
2017 });
2018}
2019
2020sub get_commit_parents {
0af9c9f9 2021 my ($self, $log_entry) = @_;
9b981fc6 2022 my (%seen, @ret, @tmp);
0af9c9f9
EW
2023 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2024 if (my $ip = $self->{inject_parents}) {
2025 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2026 push @tmp, $commit;
9b981fc6
EW
2027 }
2028 }
d2866f9e 2029 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
2030 push @tmp, $cur;
2031 }
733a65aa
EW
2032 if (my $ipd = $self->{inject_parents_dcommit}) {
2033 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2034 push @tmp, @$commit;
2035 }
2036 }
44320b9e 2037 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
2038 while (my $p = shift @tmp) {
2039 next if $seen{$p};
2040 $seen{$p} = 1;
2041 push @ret, $p;
2042 # MAXPARENT is defined to 16 in commit-tree.c:
2043 last if @ret >= 16;
2044 }
2045 if (@tmp) {
44320b9e 2046 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
2047 join("\n\t", @tmp), "\n";
2048 }
2049 @ret;
2050}
2051
aea736cc
EW
2052sub rewrite_root {
2053 my ($self) = @_;
2054 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2055 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2056 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2057 if ($rwr) {
2058 $rwr =~ s#/+$##;
2059 if ($rwr !~ m#^[a-z\+]+://#) {
2060 die "$rwr is not a valid URL (key: $k)\n";
2061 }
2062 }
2063 $self->{-rewrite_root} = $rwr;
2064}
2065
2066sub metadata_url {
2067 my ($self) = @_;
2068 ($self->rewrite_root || $self->{url}) .
2069 (length $self->{path} ? '/' . $self->{path} : '');
2070}
2071
706587fc 2072sub full_url {
9b981fc6 2073 my ($self) = @_;
5d3b7cd5 2074 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
2075}
2076
ad94802a
EW
2077
2078sub set_commit_header_env {
2079 my ($log_entry) = @_;
2080 my %env;
2081 foreach my $ned (qw/NAME EMAIL DATE/) {
2082 foreach my $ac (qw/AUTHOR COMMITTER/) {
2083 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2084 }
9b981fc6 2085 }
ad94802a 2086
70ae04e4
AW
2087 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2088 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
44320b9e 2089 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 2090
70ae04e4
AW
2091 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2092 ? $log_entry->{commit_name}
2093 : $log_entry->{name};
2094 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2095 ? $log_entry->{commit_email}
2096 : $log_entry->{email};
ad94802a
EW
2097 \%env;
2098}
70ae04e4 2099
ad94802a
EW
2100sub restore_commit_header_env {
2101 my ($env) = @_;
2102 foreach my $ned (qw/NAME EMAIL DATE/) {
2103 foreach my $ac (qw/AUTHOR COMMITTER/) {
2104 my $k = "GIT_${ac}_${ned}";
2105 if (defined $env->{$k}) {
2106 $ENV{$k} = $env->{$k};
2107 } else {
2108 delete $ENV{$k};
2109 }
2110 }
2111 }
2112}
2113
94bc914c
KW
2114sub gc {
2115 command_noisy('gc', '--auto');
2116};
2117
ad94802a
EW
2118sub do_git_commit {
2119 my ($self, $log_entry) = @_;
2120 my $lr = $self->last_rev;
2121 if (defined $lr && $lr >= $log_entry->{revision}) {
2122 die "Last fetched revision of ", $self->refname,
2123 " was r$lr, but we are about to fetch: ",
2124 "r$log_entry->{revision}!\n";
2125 }
2126 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2127 croak "$log_entry->{revision} = $c already exists! ",
2128 "Why are we refetching it?\n";
2129 }
2130 my $old_env = set_commit_header_env($log_entry);
44320b9e 2131 my $tree = $log_entry->{tree};
9b981fc6
EW
2132 if (!defined $tree) {
2133 $tree = $self->tmp_index_do(sub {
2134 command_oneline('write-tree') });
2135 }
2136 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2137
2138 my @exec = ('git-commit-tree', $tree);
0af9c9f9 2139 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
2140 push @exec, '-p', $_;
2141 }
2142 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2143 or croak $!;
44320b9e 2144 print $msg_fh $log_entry->{log} or croak $!;
ad94802a 2145 restore_commit_header_env($old_env);
91b03282 2146 unless ($self->no_metadata) {
8a49ee97
EW
2147 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2148 or croak $!;
9760adcc 2149 }
9b981fc6
EW
2150 $msg_fh->flush == 0 or croak $!;
2151 close $msg_fh or croak $!;
2152 chomp(my $commit = do { local $/; <$out_fh> });
2153 close $out_fh or croak $!;
2154 waitpid $pid, 0;
2155 croak $? if $?;
2156 if ($commit !~ /^$::sha1$/o) {
2157 die "Failed to commit, invalid sha1: $commit\n";
2158 }
2159
060610c5 2160 $self->rev_map_set($log_entry->{revision}, $commit, 1);
9b981fc6 2161
44320b9e 2162 $self->{last_rev} = $log_entry->{revision};
9b981fc6 2163 $self->{last_commit} = $commit;
8a49ee97
EW
2164 print "r$log_entry->{revision}";
2165 if (defined $log_entry->{svm_revision}) {
2166 print " (\@$log_entry->{svm_revision})";
060610c5 2167 $self->rev_map_set($log_entry->{svm_revision}, $commit,
26a62d57 2168 0, $self->svm_uuid);
8a49ee97
EW
2169 }
2170 print " = $commit ($self->{ref_id})\n";
94bc914c
KW
2171 if (--$_gc_nr == 0) {
2172 $_gc_nr = $_gc_period;
2173 gc();
2174 }
9b981fc6
EW
2175 return $commit;
2176}
2177
fbcc1737
EW
2178sub match_paths {
2179 my ($self, $paths, $r) = @_;
4e9f6cc7 2180 return 1 if $self->{path} eq '';
d542aedb
EW
2181 if (my $path = $paths->{"/$self->{path}"}) {
2182 return ($path->{action} eq 'D') ? 0 : 1;
2183 }
4e9f6cc7 2184 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
2185 if (grep /$self->{path_regex}/, keys %$paths) {
2186 return 1;
2187 }
2188 my $c = '';
2189 foreach (split m#/#, $self->{path}) {
2190 $c .= "/$_";
74a81227
EW
2191 next unless ($paths->{$c} &&
2192 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
2193 if ($self->ra->check_path($self->{path}, $r) ==
2194 $SVN::Node::dir) {
fbcc1737
EW
2195 return 1;
2196 }
2197 }
2198 return 0;
2199}
2200
15710b6f
EW
2201sub find_parent_branch {
2202 my ($self, $paths, $rev) = @_;
91b03282 2203 return undef unless $self->follow_parent;
e5a0b240 2204 unless (defined $paths) {
c7eba716
EW
2205 my $err_handler = $SVN::Error::handler;
2206 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
2207 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2208 $paths =
2209 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 2210 $SVN::Error::handler = $err_handler;
e5a0b240
EW
2211 }
2212 return undef unless defined $paths;
15710b6f
EW
2213
2214 # look for a parent from another branch:
7f578c55
EW
2215 my @b_path_components = split m#/#, $self->rel_path;
2216 my @a_path_components;
2217 my $i;
2218 while (@b_path_components) {
2219 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 2220 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
2221 unshift(@a_path_components, pop(@b_path_components));
2222 }
74a81227
EW
2223 return undef unless defined $i && defined $i->{copyfrom_path};
2224 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
2225 if (@a_path_components) {
2226 print STDERR "branch_from: $branch_from => ";
2227 $branch_from .= '/'.join('/', @a_path_components);
2228 print STDERR $branch_from, "\n";
2229 }
3ebe8df7 2230 my $r = $i->{copyfrom_rev};
15710b6f
EW
2231 my $repos_root = $self->ra->{repos_root};
2232 my $url = $self->ra->{url};
2233 my $new_url = $repos_root . $branch_from;
2234 print STDERR "Found possible branch point: ",
2235 "$new_url => ", $self->full_url, ", $r\n";
2236 $branch_from =~ s#^/##;
a8ae2623 2237 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
15710b6f 2238 unless ($gs) {
ce2a0f2f
EW
2239 my $ref_id = $self->{ref_id};
2240 $ref_id =~ s/\@\d+$//;
2241 $ref_id .= "\@$r";
15710b6f
EW
2242 # just grow a tail if we're not unique enough :x
2243 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 2244 print STDERR "Initializing parent: $ref_id\n";
f61cc48d 2245 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
c586879c
EW
2246 if ($u =~ s#^\Q$url\E(/|$)##) {
2247 $p = $u;
2248 $u = $url;
f61cc48d 2249 $repo_id = $self->{repo_id};
c586879c 2250 }
f61cc48d 2251 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
15710b6f
EW
2252 }
2253 my ($r0, $parent) = $gs->find_rev_before($r, 1);
91b03282 2254 if (!defined $r0 || !defined $parent) {
d627de6b
EW
2255 my ($base, $head) = parse_revision_argument(0, $r);
2256 if ($base <= $r) {
2257 $gs->fetch($base, $r);
2258 }
15710b6f
EW
2259 ($r0, $parent) = $gs->last_rev_commit;
2260 }
ef70de96 2261 if (defined $r0 && defined $parent) {
15710b6f 2262 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
2263 my $ed;
2264 if ($self->ra->can_do_switch) {
2e5e2480 2265 $self->assert_index_clean($parent);
8b8fc068 2266 print STDERR "Following parent with do_switch\n";
15710b6f 2267 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 2268 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
2269 # at the moment), so we can't rely on it
2270 $self->{last_commit} = $parent;
2271 $ed = SVN::Git::Fetcher->new($self);
8a603774 2272 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
2273 $self->full_url, $ed)
2274 or die "SVN connection failed somewhere...\n";
9ff74e95
SW
2275 } elsif ($self->ra->trees_match($new_url, $r0,
2276 $self->full_url, $rev)) {
2277 print STDERR "Trees match:\n",
2278 " $new_url\@$r0\n",
2279 " ${\$self->full_url}\@$rev\n",
2280 "Following parent with no changes\n";
2281 $self->tmp_index_do(sub {
2282 command_noisy('read-tree', $parent);
2283 });
2284 $self->{last_commit} = $parent;
15710b6f 2285 } else {
8b8fc068 2286 print STDERR "Following parent with do_update\n";
15710b6f 2287 $ed = SVN::Git::Fetcher->new($self);
8a603774 2288 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
2289 or die "SVN connection failed somewhere...\n";
2290 }
f7c3fc4a 2291 print STDERR "Successfully followed parent\n";
15710b6f
EW
2292 return $self->make_log_entry($rev, [$parent], $ed);
2293 }
15710b6f
EW
2294 return undef;
2295}
2296
9b981fc6 2297sub do_fetch {
706587fc 2298 my ($self, $paths, $rev) = @_;
15710b6f 2299 my $ed;
9b981fc6 2300 my ($last_rev, @parents);
b9dffd8c
EW
2301 if (my $lc = $self->last_commit) {
2302 # we can have a branch that was deleted, then re-added
2303 # under the same name but copied from another path, in
2304 # which case we'll have multiple parents (we don't
2305 # want to break the original ref, nor lose copypath info):
2306 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2307 push @{$log_entry->{parents}}, $lc;
2308 return $log_entry;
2309 }
15710b6f 2310 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2311 $last_rev = $self->{last_rev};
b9dffd8c
EW
2312 $ed->{c} = $lc;
2313 @parents = ($lc);
9b981fc6
EW
2314 } else {
2315 $last_rev = $rev;
15710b6f
EW
2316 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2317 return $log_entry;
2318 }
2319 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2320 }
8a603774 2321 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
2322 die "SVN connection failed somewhere...\n";
2323 }
2324 $self->make_log_entry($rev, \@parents, $ed);
2325}
2326
97f6987a
EW
2327sub get_untracked {
2328 my ($self, $ed) = @_;
2329 my @out;
2330 my $h = $ed->{empty};
9b981fc6
EW
2331 foreach (sort keys %$h) {
2332 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 2333 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
2334 warn "W: $act: $_\n";
2335 }
2336 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 2337 $h = $ed->{$t} or next;
9b981fc6
EW
2338 foreach my $path (sort keys %$h) {
2339 my $ppath = $path eq '' ? '.' : $path;
2340 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 2341 next if $SKIP_PROP{$prop};
9b981fc6 2342 my $v = $h->{$path}->{$prop};
97f6987a
EW
2343 my $t_ppath_prop = "$t: " .
2344 uri_encode($ppath) . ' ' .
2345 uri_encode($prop);
9b981fc6 2346 if (defined $v) {
97f6987a
EW
2347 push @out, " +$t_ppath_prop " .
2348 uri_encode($v);
9b981fc6 2349 } else {
97f6987a 2350 push @out, " -$t_ppath_prop";
9b981fc6
EW
2351 }
2352 }
2353 }
2354 }
2355 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 2356 $h = $ed->{$t} or next;
9b981fc6
EW
2357 foreach my $parent (sort keys %$h) {
2358 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
2359 push @out, " $t: " .
2360 uri_encode("$parent/$path");
9b981fc6
EW
2361 warn "W: $t: $parent/$path ",
2362 "Insufficient permissions?\n";
2363 }
2364 }
2365 }
97f6987a 2366 \@out;
9b981fc6
EW
2367}
2368
1c8443b0
EW
2369sub parse_svn_date {
2370 my $date = shift || return '+0000 1970-01-01 00:00:00';
2371 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2372 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2373 croak "Unable to parse date: $date\n";
2374 "+0000 $Y-$m-$d $H:$M:$S";
2375}
2376
2377sub check_author {
2378 my ($author) = @_;
2379 if (!defined $author || length $author == 0) {
2380 $author = '(no author)';
9231f500 2381 } elsif (defined $::_authors && ! defined $::users{$author}) {
1c8443b0
EW
2382 die "Author: $author not defined in $::_authors file\n";
2383 }
2384 $author;
2385}
2386
9b981fc6 2387sub make_log_entry {
97f6987a
EW
2388 my ($self, $rev, $parents, $ed) = @_;
2389 my $untracked = $self->get_untracked($ed);
2390
9b981fc6 2391 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
2392 print $un "r$rev\n" or croak $!;
2393 print $un $_, "\n" foreach @$untracked;
2394 my %log_entry = ( parents => $parents || [], revision => $rev,
2395 log => '');
fbcc1737 2396
8a49ee97 2397 my $headrev;
fbcc1737 2398 my $logged = delete $self->{logged_rev_props};
8a49ee97 2399 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
2400 my $rp = $self->ra->rev_proplist($rev);
2401 foreach (sort keys %$rp) {
2402 my $v = $rp->{$_};
2403 if (/^svn:(author|date|log)$/) {
2404 $log_entry{$1} = $v;
8a49ee97
EW
2405 } elsif ($_ eq 'svm:headrev') {
2406 $headrev = $v;
fbcc1737
EW
2407 } else {
2408 print $un " rev_prop: ", uri_encode($_), ' ',
2409 uri_encode($v), "\n";
2410 }
9b981fc6 2411 }
fbcc1737
EW
2412 } else {
2413 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
2414 }
2415 close $un or croak $!;
97f6987a 2416
9b981fc6 2417 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 2418 $log_entry{log} .= "\n";
db03cd24
EW
2419 my $author = $log_entry{author} = check_author($log_entry{author});
2420 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
70ae04e4
AW
2421 : ($author, undef);
2422
2423 my ($commit_name, $commit_email) = ($name, $email);
2424 if ($_use_log_author) {
5ff6aae8
AW
2425 my $name_field;
2426 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2427 $name_field = $1;
2428 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2429 $name_field = $1;
2430 }
2431 if (!defined $name_field) {
abfa533d
SB
2432 if (!defined $email) {
2433 $email = $name;
2434 }
5ff6aae8 2435 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
70ae04e4 2436 ($name, $email) = ($1, $2);
5ff6aae8
AW
2437 } elsif ($name_field =~ /(.*)@/) {
2438 ($name, $email) = ($1, $name_field);
2439 } else {
abfa533d 2440 ($name, $email) = ($name_field, $name_field);
70ae04e4
AW
2441 }
2442 }
91b03282 2443 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
2444 if ($self->rewrite_root) {
2445 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2446 "options set!\n";
2447 }
8a49ee97 2448 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
2449 # we don't want "SVM: initializing mirror for junk" ...
2450 return undef if $r == 0;
2451 my $svm = $self->svm;
2452 if ($uuid ne $svm->{uuid}) {
8a49ee97 2453 die "UUID mismatch on SVM path:\n",
befc9adc 2454 "expected: $svm->{uuid}\n",
8a49ee97
EW
2455 " got: $uuid\n";
2456 }
befc9adc
EW
2457 my $full_url = $self->full_url;
2458 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2459 die "Failed to replace '$svm->{replace}' with ",
2460 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
2461 # throw away username for storing in records
2462 remove_username($full_url);
8a49ee97
EW
2463 $log_entry{metadata} = "$full_url\@$r $uuid";
2464 $log_entry{svm_revision} = $r;
70ae04e4
AW
2465 $email ||= "$author\@$uuid";
2466 $commit_email ||= "$author\@$uuid";
62e349d2
EW
2467 } elsif ($self->use_svnsync_props) {
2468 my $full_url = $self->svnsync->{url};
2469 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 2470 remove_username($full_url);
62e349d2
EW
2471 my $uuid = $self->svnsync->{uuid};
2472 $log_entry{metadata} = "$full_url\@$rev $uuid";
70ae04e4
AW
2473 $email ||= "$author\@$uuid";
2474 $commit_email ||= "$author\@$uuid";
8a49ee97 2475 } else {
ce118739
AR
2476 my $url = $self->metadata_url;
2477 remove_username($url);
2478 $log_entry{metadata} = "$url\@$rev " .
26a62d57 2479 $self->ra->get_uuid;
db03cd24 2480 $email ||= "$author\@" . $self->ra->get_uuid;
70ae04e4 2481 $commit_email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 2482 }
db03cd24
EW
2483 $log_entry{name} = $name;
2484 $log_entry{email} = $email;
70ae04e4
AW
2485 $log_entry{commit_name} = $commit_name;
2486 $log_entry{commit_email} = $commit_email;
9b981fc6
EW
2487 \%log_entry;
2488}
2489
2490sub fetch {
3ebe8df7 2491 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 2492 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 2493 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 2494 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
2495}
2496
2497sub set_tree_cb {
2498 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
2499 $self->{inject_parents} = { $rev => $tree };
2500 $self->fetch(undef, undef);
9b981fc6
EW
2501}
2502
2503sub set_tree {
2504 my ($self, $tree) = (shift, shift);
1ce255dc 2505 my $log_entry = ::get_commit_entry($tree);
9b981fc6 2506 unless ($self->{last_rev}) {
207f1a75 2507 fatal("Must have an existing revision to commit");
9b981fc6 2508 }
61395354
EW
2509 my %ed_opts = ( r => $self->{last_rev},
2510 log => $log_entry->{log},
2511 ra => $self->ra,
2512 tree_a => $self->{last_commit},
2513 tree_b => $tree,
2514 editor_cb => sub {
2515 $self->set_tree_cb($log_entry, $tree, @_) },
2516 svn_path => $self->{path} );
2517 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
2518 print "No changes\nr$self->{last_rev} = $tree\n";
2519 }
9b981fc6
EW
2520}
2521
060610c5
EW
2522sub rebuild_from_rev_db {
2523 my ($self, $path) = @_;
2524 my $r = -1;
2525 open my $fh, '<', $path or croak "open: $!";
4f7ec797 2526 binmode $fh or croak "binmode: $!";
060610c5
EW
2527 while (<$fh>) {
2528 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2529 chomp($_);
2530 ++$r;
2531 next if $_ eq ('0' x 40);
2532 $self->rev_map_set($r, $_);
2533 print "r$r = $_\n";
2534 }
2535 close $fh or croak "close: $!";
2536 unlink $path or croak "unlink: $!";
2537}
2538
f0ecca10
EW
2539sub rebuild {
2540 my ($self) = @_;
060610c5
EW
2541 my $map_path = $self->map_path;
2542 return if (-e $map_path && ! -z $map_path);
d6d3346b 2543 return unless ::verify_ref($self->refname.'^0');
060610c5
EW
2544 if ($self->use_svm_props || $self->no_metadata) {
2545 my $rev_db = $self->rev_db_path;
2546 $self->rebuild_from_rev_db($rev_db);
2547 if ($self->use_svm_props) {
2548 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2549 $self->rebuild_from_rev_db($svm_rev_db);
2550 }
2551 $self->unlink_rev_db_symlink;
26a62d57
EW
2552 return;
2553 }
060610c5
EW
2554 print "Rebuilding $map_path ...\n";
2555 my ($log, $ctx) =
2556 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2557 $self->refname, '--');
f0ecca10 2558 my $full_url = $self->full_url;
18ea92bd 2559 remove_username($full_url);
060610c5 2560 my $svn_uuid = $self->ra_uuid;
3dfab993
SV
2561 my $c;
2562 while (<$log>) {
2563 if ( m{^commit ($::sha1)$} ) {
2564 $c = $1;
2565 next;
2566 }
2567 next unless s{^\s*(git-svn-id:)}{$1};
2568 my ($url, $rev, $uuid) = ::extract_metadata($_);
18ea92bd 2569 remove_username($url);
f0ecca10
EW
2570
2571 # ignore merges (from set-tree)
2572 next if (!defined $rev || !$uuid);
2573
2574 # if we merged or otherwise started elsewhere, this is
2575 # how we break out of it
060610c5 2576 if (($uuid ne $svn_uuid) ||
f0ecca10
EW
2577 ($full_url && $url && ($url ne $full_url))) {
2578 next;
2579 }
f0ecca10 2580
060610c5 2581 $self->rev_map_set($rev, $c);
f0ecca10
EW
2582 print "r$rev = $c\n";
2583 }
3dfab993 2584 command_close_pipe($log, $ctx);
060610c5
EW
2585 print "Done rebuilding $map_path\n";
2586 my $rev_db_path = $self->rev_db_path;
2587 if (-f $self->rev_db_path) {
2588 unlink $self->rev_db_path or croak "unlink: $!";
2589 }
2590 $self->unlink_rev_db_symlink;
f0ecca10
EW
2591}
2592
060610c5 2593# rev_map:
9b981fc6
EW
2594# Tie::File seems to be prone to offset errors if revisions get sparse,
2595# it's not that fast, either. Tie::File is also not in Perl 5.6. So
2596# one of my favorite modules is out :< Next up would be one of the DBM
060610c5
EW
2597# modules, but I'm not sure which is most portable...
2598#
2599# This is the replacement for the rev_db format, which was too big
2600# and inefficient for large repositories with a lot of sparse history
2601# (mainly tags)
2602#
2603# The format is this:
2604# - 24 bytes for every record,
2605# * 4 bytes for the integer representing an SVN revision number
2606# * 20 bytes representing the sha1 of a git commit
2607# - No empty padding records like the old format
66ab84b9 2608# (except the last record, which can be overwritten)
060610c5
EW
2609# - new records are written append-only since SVN revision numbers
2610# increase monotonically
2611# - lookups on SVN revision number are done via a binary search
66ab84b9
EW
2612# - Piping the file to xxd -c24 is a good way of dumping it for
2613# viewing or editing (piped back through xxd -r), should the need
2614# ever arise.
2615# - The last record can be padding revision with an all-zero sha1
2616# This is used to optimize fetch performance when using multiple
2617# "fetch" directives in .git/config
060610c5 2618#
97ae0911 2619# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 2620
060610c5 2621sub _rev_map_set {
26a62d57 2622 my ($fh, $rev, $commit) = @_;
060610c5 2623
4f7ec797 2624 binmode $fh or croak "binmode: $!";
060610c5
EW
2625 my $size = (stat($fh))[7];
2626 ($size % 24) == 0 or croak "inconsistent size: $size";
2627
66ab84b9 2628 my $wr_offset = 0;
060610c5
EW
2629 if ($size > 0) {
2630 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2631 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2632 $read == 24 or croak "read only $read bytes (!= 24)";
2633 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
2634 if ($last_commit eq ('0' x40)) {
2635 if ($size >= 48) {
2636 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2637 $read = sysread($fh, $buf, 24) or
2638 croak "read: $!";
2639 $read == 24 or
2640 croak "read only $read bytes (!= 24)";
2641 ($last_rev, $last_commit) =
2642 unpack(rev_map_fmt, $buf);
2643 if ($last_commit eq ('0' x40)) {
2644 croak "inconsistent .rev_map\n";
2645 }
2646 }
2647 if ($last_rev >= $rev) {
2648 croak "last_rev is higher!: $last_rev >= $rev";
2649 }
2650 $wr_offset = -24;
26a62d57
EW
2651 }
2652 }
66ab84b9 2653 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
060610c5
EW
2654 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2655 croak "write: $!";
26a62d57
EW
2656}
2657
2658sub mkfile {
2659 my ($path) = @_;
2660 unless (-e $path) {
2661 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2662 mkpath([$dir]) unless -d $dir;
2663 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2664 close $fh or die "Couldn't close (create) $path: $!\n";
2665 }
2666}
2667
060610c5 2668sub rev_map_set {
26a62d57
EW
2669 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2670 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
060610c5 2671 my $db = $self->map_path($uuid);
26a62d57 2672 my $db_lock = "$db.lock";
373274f9
EW
2673 my $sig;
2674 if ($update_ref) {
2675 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2676 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2677 }
26a62d57
EW
2678 mkfile($db);
2679
373274f9 2680 $LOCKFILES{$db_lock} = 1;
97ae0911 2681 my $sync;
97ae0911
EW
2682 # both of these options make our .rev_db file very, very important
2683 # and we can't afford to lose it because rebuild() won't work
2684 if ($self->use_svm_props || $self->no_metadata) {
2685 $sync = 1;
060610c5 2686 copy($db, $db_lock) or die "rev_map_set(@_): ",
26a62d57 2687 "Failed to copy: ",
373274f9
EW
2688 "$db => $db_lock ($!)\n";
2689 } else {
060610c5 2690 rename $db, $db_lock or die "rev_map_set(@_): ",
26a62d57 2691 "Failed to rename: ",
373274f9
EW
2692 "$db => $db_lock ($!)\n";
2693 }
060610c5 2694
66ab84b9 2695 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
060610c5
EW
2696 or croak "Couldn't open $db_lock: $!\n";
2697 _rev_map_set($fh, $rev, $commit);
97ae0911
EW
2698 if ($sync) {
2699 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2700 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2701 }
9b981fc6 2702 close $fh or croak $!;
373274f9 2703 if ($update_ref) {
1e889ef3 2704 $_head = $self;
373274f9
EW
2705 command_noisy('update-ref', '-m', "r$rev",
2706 $self->refname, $commit);
2707 }
060610c5 2708 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
373274f9
EW
2709 "$db_lock => $db ($!)\n";
2710 delete $LOCKFILES{$db_lock};
2711 if ($update_ref) {
2712 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2713 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2714 kill $sig, $$ if defined $sig;
2715 }
9b981fc6
EW
2716}
2717
66ab84b9
EW
2718# If want_commit, this will return an array of (rev, commit) where
2719# commit _must_ be a valid commit in the archive.
2720# Otherwise, it'll return the max revision (whether or not the
2721# commit is valid or just a 0x40 placeholder).
060610c5 2722sub rev_map_max {
66ab84b9 2723 my ($self, $want_commit) = @_;
d6d3346b 2724 $self->rebuild;
060610c5 2725 my $map_path = $self->map_path;
66ab84b9 2726 stat $map_path or return $want_commit ? (0, undef) : 0;
060610c5 2727 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 2728 binmode $fh or croak "binmode: $!";
060610c5
EW
2729 my $size = (stat($fh))[7];
2730 ($size % 24) == 0 or croak "inconsistent size: $size";
2731
2732 if ($size == 0) {
2733 close $fh or croak "close: $!";
66ab84b9 2734 return $want_commit ? (0, undef) : 0;
060610c5
EW
2735 }
2736
66ab84b9 2737 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
060610c5 2738 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
060610c5 2739 my ($r, $c) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
2740 if ($want_commit && $c eq ('0' x40)) {
2741 if ($size < 48) {
2742 return $want_commit ? (0, undef) : 0;
2743 }
2744 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2745 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2746 ($r, $c) = unpack(rev_map_fmt, $buf);
2747 if ($c eq ('0'x40)) {
2748 croak "Penultimate record is all-zeroes in $map_path";
2749 }
2750 }
2751 close $fh or croak "close: $!";
2752 $want_commit ? ($r, $c) : $r;
9c93fee5
EW
2753}
2754
060610c5 2755sub rev_map_get {
26a62d57 2756 my ($self, $rev, $uuid) = @_;
060610c5
EW
2757 my $map_path = $self->map_path($uuid);
2758 return undef unless -e $map_path;
2759
2760 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 2761 binmode $fh or croak "binmode: $!";
060610c5
EW
2762 my $size = (stat($fh))[7];
2763 ($size % 24) == 0 or croak "inconsistent size: $size";
2764
2765 if ($size == 0) {
2766 close $fh or croak "close: $fh";
2767 return undef;
2768 }
2769
2770 my ($l, $u) = (0, $size - 24);
2771 my ($r, $c, $buf);
2772
2773 while ($l <= $u) {
2774 my $i = int(($l/24 + $u/24) / 2) * 24;
2775 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2776 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2777 my ($r, $c) = unpack('NH40', $buf);
2778
2779 if ($r < $rev) {
2780 $l = $i + 24;
2781 } elsif ($r > $rev) {
2782 $u = $i - 24;
2783 } else { # $r == $rev
2784 close($fh) or croak "close: $!";
66ab84b9 2785 return $c eq ('0' x 40) ? undef : $c;
060610c5 2786 }
9b981fc6 2787 }
060610c5
EW
2788 close($fh) or croak "close: $!";
2789 undef;
9b981fc6
EW
2790}
2791
111947ef
DK
2792# Finds the first svn revision that exists on (if $eq_ok is true) or
2793# before $rev for the current branch. It will not search any lower
2794# than $min_rev. Returns the git commit hash and svn revision number
2795# if found, else (undef, undef).
15710b6f 2796sub find_rev_before {
111947ef 2797 my ($self, $rev, $eq_ok, $min_rev) = @_;
15710b6f 2798 --$rev unless $eq_ok;
111947ef
DK
2799 $min_rev ||= 1;
2800 while ($rev >= $min_rev) {
060610c5 2801 if (my $c = $self->rev_map_get($rev)) {
15710b6f
EW
2802 return ($rev, $c);
2803 }
2804 --$rev;
2805 }
2806 return (undef, undef);
2807}
2808
111947ef
DK
2809# Finds the first svn revision that exists on (if $eq_ok is true) or
2810# after $rev for the current branch. It will not search any higher
2811# than $max_rev. Returns the git commit hash and svn revision number
2812# if found, else (undef, undef).
2813sub find_rev_after {
2814 my ($self, $rev, $eq_ok, $max_rev) = @_;
2815 ++$rev unless $eq_ok;
060610c5 2816 $max_rev ||= $self->rev_map_max;
111947ef 2817 while ($rev <= $max_rev) {
060610c5 2818 if (my $c = $self->rev_map_get($rev)) {
111947ef
DK
2819 return ($rev, $c);
2820 }
2821 ++$rev;
2822 }
2823 return (undef, undef);
2824}
2825
9b981fc6 2826sub _new {
706587fc
EW
2827 my ($class, $repo_id, $ref_id, $path) = @_;
2828 unless (defined $repo_id && length $repo_id) {
2829 $repo_id = $Git::SVN::default_repo_id;
2830 }
2831 unless (defined $ref_id && length $ref_id) {
8b8fc068 2832 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
2833 }
2834 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2835 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2836 $_[3] = $path = '' unless (defined $path);
b4d57e5e 2837 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
2838 bless {
2839 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 2840 path => $path, config => "$ENV{GIT_DIR}/svn/config",
060610c5 2841 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
26a62d57
EW
2842}
2843
060610c5
EW
2844# for read-only access of old .rev_db formats
2845sub unlink_rev_db_symlink {
2846 my ($self) = @_;
2847 my $link = $self->rev_db_path;
2848 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2849 if (-l $link) {
2850 unlink $link or croak "unlink: $link failed!";
2851 }
2852}
2853
2854sub rev_db_path {
2855 my ($self, $uuid) = @_;
2856 my $db_path = $self->map_path($uuid);
2857 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2858 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2859 $db_path;
2860}
2861
2862# the new replacement for .rev_db
2863sub map_path {
26a62d57
EW
2864 my ($self, $uuid) = @_;
2865 $uuid ||= $self->ra_uuid;
060610c5 2866 "$self->{map_root}.$uuid";
9b981fc6
EW
2867}
2868
1c8443b0
EW
2869sub uri_encode {
2870 my ($f) = @_;
2871 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2872 $f
2873}
9b981fc6 2874
18ea92bd
SV
2875sub remove_username {
2876 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2877}
2878
d976acfd
EW
2879package Git::SVN::Prompt;
2880use strict;
2881use warnings;
2882require SVN::Core;
2883use vars qw/$_no_auth_cache $_username/;
2884
2885sub simple {
30d055aa
EW
2886 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2887 $may_save = undef if $_no_auth_cache;
2888 $default_username = $_username if defined $_username;
2889 if (defined $default_username && length $default_username) {
2890 if (defined $realm && length $realm) {
6f729591
EW
2891 print STDERR "Authentication realm: $realm\n";
2892 STDERR->flush;
30d055aa
EW
2893 }
2894 $cred->username($default_username);
2895 } else {
d976acfd 2896 username($cred, $realm, $may_save, $pool);
30d055aa
EW
2897 }
2898 $cred->password(_read_password("Password for '" .
2899 $cred->username . "': ", $realm));
2900 $cred->may_save($may_save);
2901 $SVN::_Core::SVN_NO_ERROR;
2902}
2903
d976acfd 2904sub ssl_server_trust {
30d055aa
EW
2905 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2906 $may_save = undef if $_no_auth_cache;
6f729591 2907 print STDERR "Error validating server certificate for '$realm':\n";
fd499bcc
ER
2908 {
2909 no warnings 'once';
2910 # All variables SVN::Auth::SSL::* are used only once,
2911 # so we're shutting up Perl warnings about this.
2912 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2913 print STDERR " - The certificate is not issued ",
2914 "by a trusted authority. Use the\n",
2915 " fingerprint to validate ",
2916 "the certificate manually!\n";
2917 }
2918 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2919 print STDERR " - The certificate hostname ",
2920 "does not match.\n";
2921 }
2922 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2923 print STDERR " - The certificate is not yet valid.\n";
2924 }
2925 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2926 print STDERR " - The certificate has expired.\n";
2927 }
2928 if ($failures & $SVN::Auth::SSL::OTHER) {
2929 print STDERR " - The certificate has ",
2930 "an unknown error.\n";
2931 }
2932 } # no warnings 'once'
6f729591
EW
2933 printf STDERR
2934 "Certificate information:\n".
30d055aa
EW
2935 " - Hostname: %s\n".
2936 " - Valid: from %s until %s\n".
2937 " - Issuer: %s\n".
2938 " - Fingerprint: %s\n",
2939 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 2940 issuer_dname fingerprint);
30d055aa
EW
2941 my $choice;
2942prompt:
6f729591 2943 print STDERR $may_save ?
30d055aa
EW
2944 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2945 "(R)eject or accept (t)emporarily? ";
6f729591 2946 STDERR->flush;
30d055aa
EW
2947 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2948 if ($choice =~ /^t$/i) {
2949 $cred->may_save(undef);
2950 } elsif ($choice =~ /^r$/i) {
2951 return -1;
2952 } elsif ($may_save && $choice =~ /^p$/i) {
2953 $cred->may_save($may_save);
2954 } else {
2955 goto prompt;
2956 }
2957 $cred->accepted_failures($failures);
2958 $SVN::_Core::SVN_NO_ERROR;
2959}
2960
d976acfd 2961sub ssl_client_cert {
30d055aa
EW
2962 my ($cred, $realm, $may_save, $pool) = @_;
2963 $may_save = undef if $_no_auth_cache;
6f729591
EW
2964 print STDERR "Client certificate filename: ";
2965 STDERR->flush;
30d055aa
EW
2966 chomp(my $filename = <STDIN>);
2967 $cred->cert_file($filename);
2968 $cred->may_save($may_save);
2969 $SVN::_Core::SVN_NO_ERROR;
2970}
2971
d976acfd 2972sub ssl_client_cert_pw {
30d055aa
EW
2973 my ($cred, $realm, $may_save, $pool) = @_;
2974 $may_save = undef if $_no_auth_cache;
2975 $cred->password(_read_password("Password: ", $realm));
2976 $cred->may_save($may_save);
2977 $SVN::_Core::SVN_NO_ERROR;
2978}
2979
d976acfd 2980sub username {
30d055aa
EW
2981 my ($cred, $realm, $may_save, $pool) = @_;
2982 $may_save = undef if $_no_auth_cache;
2983 if (defined $realm && length $realm) {
6f729591 2984 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
2985 }
2986 my $username;
2987 if (defined $_username) {
2988 $username = $_username;
2989 } else {
6f729591
EW
2990 print STDERR "Username: ";
2991 STDERR->flush;
30d055aa
EW
2992 chomp($username = <STDIN>);
2993 }
2994 $cred->username($username);
2995 $cred->may_save($may_save);
2996 $SVN::_Core::SVN_NO_ERROR;
2997}
2998
2999sub _read_password {
3000 my ($prompt, $realm) = @_;
6f729591
EW
3001 print STDERR $prompt;
3002 STDERR->flush;
30d055aa
EW
3003 require Term::ReadKey;
3004 Term::ReadKey::ReadMode('noecho');
3005 my $password = '';
3006 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3007 last if $key =~ /[\012\015]/; # \n\r
3008 $password .= $key;
3009 }
3010 Term::ReadKey::ReadMode('restore');
6f729591
EW
3011 print STDERR "\n";
3012 STDERR->flush;
30d055aa
EW
3013 $password;
3014}
3015
27a1a801
EW
3016package SVN::Git::Fetcher;
3017use vars qw/@ISA/;
3018use strict;
3019use warnings;
3020use Carp qw/croak/;
3021use IO::File qw//;
3022
3023# file baton members: path, mode_a, mode_b, pool, fh, blob, base
3024sub new {
3025 my ($class, $git_svn) = @_;
3026 my $self = SVN::Delta::Editor->new;
3027 bless $self, $class;
1c8443b0 3028 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
3029 $self->{empty} = {};
3030 $self->{dir_prop} = {};
3031 $self->{file_prop} = {};
3032 $self->{absent_dir} = {};
3033 $self->{absent_file} = {};
ef3cfaad 3034 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
3035 $self;
3036}
3037
8b8fc068
EW
3038sub set_path_strip {
3039 my ($self, $path) = @_;
4e9f6cc7 3040 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
3041}
3042
d2a9a87b
EW
3043sub open_root {
3044 { path => '' };
3045}
3046
3047sub open_directory {
3048 my ($self, $path, $pb, $rev) = @_;
3049 { path => $path };
3050}
3051
706587fc
EW
3052sub git_path {
3053 my ($self, $path) = @_;
2b27f6c8
EW
3054 if ($self->{path_strip}) {
3055 $path =~ s!$self->{path_strip}!! or
3056 die "Failed to strip path '$path' ($self->{path_strip})\n";
3057 }
706587fc
EW
3058 $path;
3059}
3060
27a1a801
EW
3061sub delete_entry {
3062 my ($self, $path, $rev, $pb) = @_;
4a87db0e 3063
706587fc 3064 my $gpath = $self->git_path($path);
8a603774
EW
3065 return undef if ($gpath eq '');
3066
4a87db0e 3067 # remove entire directories.
706587fc 3068 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
3069 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3070 -r --name-only -z/,
706587fc 3071 $self->{c}, '--', $gpath);
4a87db0e
EW
3072 local $/ = "\0";
3073 while (<$ls>) {
ef3cfaad
EW
3074 chomp;
3075 $self->{gii}->remove($_);
9e3cdbd4 3076 print "\tD\t$_\n" unless $::_q;
4a87db0e 3077 }
9e3cdbd4 3078 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
3079 command_close_pipe($ls, $ctx);
3080 $self->{empty}->{$path} = 0
3081 } else {
ef3cfaad 3082 $self->{gii}->remove($gpath);
9e3cdbd4 3083 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 3084 }
27a1a801
EW
3085 undef;
3086}
3087
3088sub open_file {
3089 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
3090 my $gpath = $self->git_path($path);
3091 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 3092 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
3093 unless (defined $mode && defined $blob) {
3094 die "$path was not found in commit $self->{c} (r$rev)\n";
3095 }
27a1a801 3096 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 3097 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
3098}
3099
3100sub add_file {
3101 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
3102 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3103 delete $self->{empty}->{$dir};
27a1a801 3104 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 3105 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
3106}
3107
d2a9a87b
EW
3108sub add_directory {
3109 my ($self, $path, $cp_path, $cp_rev) = @_;
12a6d752
EW
3110 my $gpath = $self->git_path($path);
3111 if ($gpath eq '') {
3112 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3113 -r --name-only -z/,
3114 $self->{c});
3115 local $/ = "\0";
3116 while (<$ls>) {
3117 chomp;
3118 $self->{gii}->remove($_);
3119 print "\tD\t$_\n" unless $::_q;
3120 }
3121 command_close_pipe($ls, $ctx);
3122 $self->{empty}->{$path} = 0;
3123 }
d2a9a87b
EW
3124 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3125 delete $self->{empty}->{$dir};
3126 $self->{empty}->{$path} = 1;
3127 { path => $path };
3128}
3129
3130sub change_dir_prop {
3131 my ($self, $db, $prop, $value) = @_;
3132 $self->{dir_prop}->{$db->{path}} ||= {};
3133 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3134 undef;
3135}
3136
3137sub absent_directory {
3138 my ($self, $path, $pb) = @_;
3139 $self->{absent_dir}->{$pb->{path}} ||= [];
3140 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3141 undef;
3142}
3143
3144sub absent_file {
3145 my ($self, $path, $pb) = @_;
3146 $self->{absent_file}->{$pb->{path}} ||= [];
3147 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3148 undef;
3149}
3150
27a1a801
EW
3151sub change_file_prop {
3152 my ($self, $fb, $prop, $value) = @_;
3153 if ($prop eq 'svn:executable') {
3154 if ($fb->{mode_b} != 120000) {
3155 $fb->{mode_b} = defined $value ? 100755 : 100644;
3156 }
3157 } elsif ($prop eq 'svn:special') {
3158 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
3159 } else {
3160 $self->{file_prop}->{$fb->{path}} ||= {};
3161 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
3162 }
3163 undef;
3164}
3165
3166sub apply_textdelta {
3167 my ($self, $fb, $exp) = @_;
3168 my $fh = IO::File->new_tmpfile;
3169 $fh->autoflush(1);
3170 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3171 # (but $base does not,) so dup() it for reading in close_file
3172 open my $dup, '<&', $fh or croak $!;
3173 my $base = IO::File->new_tmpfile;
3174 $base->autoflush(1);
3175 if ($fb->{blob}) {
3176 defined (my $pid = fork) or croak $!;
3177 if (!$pid) {
3178 open STDOUT, '>&', $base or croak $!;
3179 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
3180 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
3181 }
3182 waitpid $pid, 0;
3183 croak $? if $?;
3184
3185 if (defined $exp) {
3186 seek $base, 0, 0 or croak $!;
8d7c4fad 3187 my $got = ::md5sum($base);
27a1a801
EW
3188 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3189 "expected: $exp\n",
3190 " got: $got\n" if ($got ne $exp);
3191 }
3192 }
3193 seek $base, 0, 0 or croak $!;
3194 $fb->{fh} = $dup;
3195 $fb->{base} = $base;
3196 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3197}
3198
3199sub close_file {
3200 my ($self, $fb, $exp) = @_;
3201 my $hash;
706587fc 3202 my $path = $self->git_path($fb->{path});
27a1a801 3203 if (my $fh = $fb->{fh}) {
7faf0686
EW
3204 if (defined $exp) {
3205 seek($fh, 0, 0) or croak $!;
8d7c4fad 3206 my $got = ::md5sum($fh);
7faf0686
EW
3207 if ($got ne $exp) {
3208 die "Checksum mismatch: $path\n",
3209 "expected: $exp\n got: $got\n";
3210 }
3211 }
bcd8ee5b 3212 sysseek($fh, 0, 0) or croak $!;
27a1a801 3213 if ($fb->{mode_b} == 120000) {
7fc35e0e
EW
3214 eval {
3215 sysread($fh, my $buf, 5) == 5 or croak $!;
3216 $buf eq 'link ' or die "$path has mode 120000",
3217 " but is not a link";
3218 };
3219 if ($@) {
3220 warn "$@\n";
3221 sysseek($fh, 0, 0) or croak $!;
3222 }
27a1a801
EW
3223 }
3224 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
3225 if (!$pid) {
3226 open STDIN, '<&', $fh or croak $!;
3227 exec qw/git-hash-object -w --stdin/ or croak $!;
3228 }
3229 chomp($hash = do { local $/; <$out> });
3230 close $out or croak $!;
3231 close $fh or croak $!;
3232 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3233 close $fb->{base} or croak $!;
3234 } else {
3235 $hash = $fb->{blob} or die "no blob information\n";
3236 }
3237 $fb->{pool}->clear;
ef3cfaad 3238 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 3239 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
3240 undef;
3241}
3242
3243sub abort_edit {
3244 my $self = shift;
ef3cfaad
EW
3245 $self->{nr} = $self->{gii}->{nr};
3246 delete $self->{gii};
27a1a801
EW
3247 $self->SUPER::abort_edit(@_);
3248}
3249
3250sub close_edit {
3251 my $self = shift;
dad73c0b 3252 $self->{git_commit_ok} = 1;
ef3cfaad
EW
3253 $self->{nr} = $self->{gii}->{nr};
3254 delete $self->{gii};
27a1a801
EW
3255 $self->SUPER::close_edit(@_);
3256}
1a82e793 3257
a5e0cedc 3258package SVN::Git::Editor;
24e22aa8 3259use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
3260use strict;
3261use warnings;
3262use Carp qw/croak/;
3263use IO::File;
3264
3265sub new {
61395354
EW
3266 my ($class, $opts) = @_;
3267 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3268 die "$_ required!\n" unless (defined $opts->{$_});
3269 }
3270
3271 my $pool = SVN::Pool->new;
3272 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3273 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3274 $opts->{r}, $mods);
3275
3276 # $opts->{ra} functions should not be used after this:
3277 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3278 $opts->{editor_cb}, $pool);
3279 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 3280 bless $self, $class;
61395354
EW
3281 foreach (qw/svn_path r tree_a tree_b/) {
3282 $self->{$_} = $opts->{$_};
a5e0cedc 3283 }
61395354
EW
3284 $self->{url} = $opts->{ra}->{url};
3285 $self->{mods} = $mods;
3286 $self->{types} = $types;
3287 $self->{pool} = $pool;
a5e0cedc
EW
3288 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3289 $self->{rm} = { };
d3a840dc
EW
3290 $self->{path_prefix} = length $self->{svn_path} ?
3291 "$self->{svn_path}/" : '';
a5e0cedc
EW
3292 return $self;
3293}
3294
61395354
EW
3295sub generate_diff {
3296 my ($tree_a, $tree_b) = @_;
3297 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
3298 if ($_cp_similarity) {
3299 push @diff_tree, "-C$_cp_similarity";
61395354
EW
3300 } else {
3301 push @diff_tree, '-C';
3302 }
24e22aa8
EW
3303 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3304 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
3305 push @diff_tree, $tree_a, $tree_b;
3306 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3307 local $/ = "\0";
3308 my $state = 'meta';
3309 my @mods;
3310 while (<$diff_fh>) {
3311 chomp $_; # this gets rid of the trailing "\0"
3312 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3313 $::sha1\s($::sha1)\s
3314 ([MTCRAD])\d*$/xo) {
3315 push @mods, { mode_a => $1, mode_b => $2,
3316 sha1_b => $3, chg => $4 };
3317 if ($4 =~ /^(?:C|R)$/) {
3318 $state = 'file_a';
3319 } else {
3320 $state = 'file_b';
3321 }
3322 } elsif ($state eq 'file_a') {
3323 my $x = $mods[$#mods] or croak "Empty array\n";
3324 if ($x->{chg} !~ /^(?:C|R)$/) {
3325 croak "Error parsing $_, $x->{chg}\n";
3326 }
3327 $x->{file_a} = $_;
3328 $state = 'file_b';
3329 } elsif ($state eq 'file_b') {
3330 my $x = $mods[$#mods] or croak "Empty array\n";
3331 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3332 croak "Error parsing $_, $x->{chg}\n";
3333 }
3334 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3335 croak "Error parsing $_, $x->{chg}\n";
3336 }
3337 $x->{file_b} = $_;
3338 $state = 'meta';
3339 } else {
3340 croak "Error parsing $_\n";
3341 }
3342 }
3343 command_close_pipe($diff_fh, $ctx);
3344 \@mods;
3345}
3346
3347sub check_diff_paths {
3348 my ($ra, $pfx, $rev, $mods) = @_;
3349 my %types;
3350 $pfx .= '/' if length $pfx;
3351
3352 sub type_diff_paths {
3353 my ($ra, $types, $path, $rev) = @_;
3354 my @p = split m#/+#, $path;
3355 my $c = shift @p;
3356 unless (defined $types->{$c}) {
3357 $types->{$c} = $ra->check_path($c, $rev);
3358 }
3359 while (@p) {
3360 $c .= '/' . shift @p;
3361 next if defined $types->{$c};
3362 $types->{$c} = $ra->check_path($c, $rev);
3363 }
3364 }
3365
3366 foreach my $m (@$mods) {
3367 foreach my $f (qw/file_a file_b/) {
3368 next unless defined $m->{$f};
3369 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3370 if (length $pfx.$dir && ! defined $types{$dir}) {
3371 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3372 }
3373 }
3374 }
3375 \%types;
3376}
3377
a5e0cedc
EW
3378sub split_path {
3379 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3380}
3381
3382sub repo_path {
d3a840dc
EW
3383 my ($self, $path) = @_;
3384 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
3385}
3386
3387sub url_path {
3388 my ($self, $path) = @_;
29633bb9
EW
3389 if ($self->{url} =~ m#^https?://#) {
3390 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3391 }
6e8548cc 3392 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
3393}
3394
3395sub rmdirs {
61395354 3396 my ($self) = @_;
a5e0cedc
EW
3397 my $rm = $self->{rm};
3398 delete $rm->{''}; # we never delete the url we're tracking
3399 return unless %$rm;
3400
3401 foreach (keys %$rm) {
3402 my @d = split m#/#, $_;
3403 my $c = shift @d;
3404 $rm->{$c} = 1;
3405 while (@d) {
3406 $c .= '/' . shift @d;
3407 $rm->{$c} = 1;
3408 }
3409 }
3410 delete $rm->{$self->{svn_path}};
3411 delete $rm->{''}; # we never delete the url we're tracking
3412 return unless %$rm;
3413
61395354
EW
3414 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3415 $self->{tree_b});
a5e0cedc
EW
3416 local $/ = "\0";
3417 while (<$fh>) {
3418 chomp;
747fa12c 3419 my @dn = split m#/#, $_;
c07eee1f
EW
3420 while (pop @dn) {
3421 delete $rm->{join '/', @dn};
3422 }
3423 unless (%$rm) {
22600a25 3424 close $fh;
c07eee1f
EW
3425 return;
3426 }
a5e0cedc 3427 }
aef4e921 3428 command_close_pipe($fh, $ctx);
c07eee1f 3429
a5e0cedc
EW
3430 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3431 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3432 $self->close_directory($bat->{$d}, $p);
3433 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 3434 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
3435 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3436 delete $bat->{$d};
3437 }
3438}
3439
3440sub open_or_add_dir {
3441 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
3442 my $t = $self->{types}->{$full_path};
3443 if (!defined $t) {
3444 die "$full_path not known in r$self->{r} or we have a bug!\n";
3445 }
fd499bcc
ER
3446 {
3447 no warnings 'once';
3448 # SVN::Node::none and SVN::Node::file are used only once,
3449 # so we're shutting up Perl's warnings about them.
3450 if ($t == $SVN::Node::none) {
3451 return $self->add_directory($full_path, $baton,
3452 undef, -1, $self->{pool});
3453 } elsif ($t == $SVN::Node::dir) {
3454 return $self->open_directory($full_path, $baton,
3455 $self->{r}, $self->{pool});
3456 } # no warnings 'once'
3457 print STDERR "$full_path already exists in repository at ",
3458 "r$self->{r} and it is not a directory (",
3459 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3460 } # no warnings 'once'
a5e0cedc
EW
3461 exit 1;
3462}
3463
3464sub ensure_path {
3465 my ($self, $path) = @_;
3466 my $bat = $self->{bat};
6e8548cc
EW
3467 my $repo_path = $self->repo_path($path);
3468 return $bat->{''} unless (length $repo_path);
3469 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
3470 my $c = shift @p;
3471 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3472 while (@p) {
3473 my $c0 = $c;
3474 $c .= '/' . shift @p;
3475 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3476 }
3477 return $bat->{$c};
3478}
3479
3480sub A {
44320b9e 3481 my ($self, $m) = @_;
a5e0cedc
EW
3482 my ($dir, $file) = split_path($m->{file_b});
3483 my $pbat = $self->ensure_path($dir);
3484 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3485 undef, -1);
44320b9e 3486 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3487 $self->chg_file($fbat, $m);
3488 $self->close_file($fbat,undef,$self->{pool});
3489}
3490
3491sub C {
44320b9e 3492 my ($self, $m) = @_;
a5e0cedc
EW
3493 my ($dir, $file) = split_path($m->{file_b});
3494 my $pbat = $self->ensure_path($dir);
3495 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3496 $self->url_path($m->{file_a}), $self->{r});
44320b9e 3497 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3498 $self->chg_file($fbat, $m);
3499 $self->close_file($fbat,undef,$self->{pool});
3500}
3501
3502sub delete_entry {
3503 my ($self, $path, $pbat) = @_;
3504 my $rpath = $self->repo_path($path);
3505 my ($dir, $file) = split_path($rpath);
3506 $self->{rm}->{$dir} = 1;
3507 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3508}
3509
3510sub R {
44320b9e 3511 my ($self, $m) = @_;
a5e0cedc
EW
3512 my ($dir, $file) = split_path($m->{file_b});
3513 my $pbat = $self->ensure_path($dir);
3514 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3515 $self->url_path($m->{file_a}), $self->{r});
44320b9e 3516 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3517 $self->chg_file($fbat, $m);
3518 $self->close_file($fbat,undef,$self->{pool});
3519
3520 ($dir, $file) = split_path($m->{file_a});
3521 $pbat = $self->ensure_path($dir);
3522 $self->delete_entry($m->{file_a}, $pbat);
3523}
3524
3525sub M {
44320b9e 3526 my ($self, $m) = @_;
a5e0cedc
EW
3527 my ($dir, $file) = split_path($m->{file_b});
3528 my $pbat = $self->ensure_path($dir);
3529 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3530 $pbat,$self->{r},$self->{pool});
44320b9e 3531 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3532 $self->chg_file($fbat, $m);
3533 $self->close_file($fbat,undef,$self->{pool});
3534}
3535
3536sub T { shift->M(@_) }
3537
3538sub change_file_prop {
3539 my ($self, $fbat, $pname, $pval) = @_;
3540 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3541}
3542
3543sub chg_file {
3544 my ($self, $fbat, $m) = @_;
3545 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3546 $self->change_file_prop($fbat,'svn:executable','*');
3547 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3548 $self->change_file_prop($fbat,'svn:executable',undef);
3549 }
3550 my $fh = IO::File->new_tmpfile or croak $!;
3551 if ($m->{mode_b} =~ /^120/) {
3552 print $fh 'link ' or croak $!;
3553 $self->change_file_prop($fbat,'svn:special','*');
3554 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3555 $self->change_file_prop($fbat,'svn:special',undef);
3556 }
3557 defined(my $pid = fork) or croak $!;
3558 if (!$pid) {
3559 open STDOUT, '>&', $fh or croak $!;
3560 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3561 }
3562 waitpid $pid, 0;
3563 croak $? if $?;
3564 $fh->flush == 0 or croak $!;
3565 seek $fh, 0, 0 or croak $!;
3566
8d7c4fad 3567 my $exp = ::md5sum($fh);
a5e0cedc
EW
3568 seek $fh, 0, 0 or croak $!;
3569
f7197dff
EW
3570 my $pool = SVN::Pool->new;
3571 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3572 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 3573 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 3574 $pool->clear;
a5e0cedc
EW
3575
3576 close $fh or croak $!;
3577}
3578
3579sub D {
44320b9e 3580 my ($self, $m) = @_;
a5e0cedc
EW
3581 my ($dir, $file) = split_path($m->{file_b});
3582 my $pbat = $self->ensure_path($dir);
44320b9e 3583 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
3584 $self->delete_entry($m->{file_b}, $pbat);
3585}
3586
3587sub close_edit {
3588 my ($self) = @_;
3589 my ($p,$bat) = ($self->{pool}, $self->{bat});
3590 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
6442754d 3591 next if $_ eq '';
a5e0cedc
EW
3592 $self->close_directory($bat->{$_}, $p);
3593 }
6442754d 3594 $self->close_directory($bat->{''}, $p);
a5e0cedc
EW
3595 $self->SUPER::close_edit($p);
3596 $p->clear;
3597}
3598
3599sub abort_edit {
3600 my ($self) = @_;
3601 $self->SUPER::abort_edit($self->{pool});
61395354
EW
3602}
3603
3604sub DESTROY {
3605 my $self = shift;
3606 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
3607 $self->{pool}->clear;
3608}
3609
44320b9e
EW
3610# this drives the editor
3611sub apply_diff {
61395354
EW
3612 my ($self) = @_;
3613 my $mods = $self->{mods};
44320b9e 3614 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 3615 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
3616 my $f = $m->{chg};
3617 if (defined $o{$f}) {
3618 $self->$f($m);
3619 } else {
207f1a75 3620 fatal("Invalid change type: $f");
44320b9e
EW
3621 }
3622 }
24e22aa8 3623 $self->rmdirs if $_rmdir;
6e8548cc 3624 if (@$mods == 0) {
44320b9e
EW
3625 $self->abort_edit;
3626 } else {
3627 $self->close_edit;
3628 }
6e8548cc 3629 return scalar @$mods;
44320b9e
EW
3630}
3631
d81bf827 3632package Git::SVN::Ra;
6af1db44 3633use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
3634use strict;
3635use warnings;
a51cdb0c 3636my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
d81bf827
EW
3637
3638BEGIN {
3639 # enforce temporary pool usage for some simple functions
c5f71ad0
SV
3640 no strict 'refs';
3641 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3642 my $SUPER = "SUPER::$f";
3643 *$f = sub {
3644 my $self = shift;
3645 my $pool = SVN::Pool->new;
3646 my @ret = $self->$SUPER(@_,$pool);
3647 $pool->clear;
3648 wantarray ? @ret : $ret[0];
3649 };
d81bf827 3650 }
d81bf827
EW
3651}
3652
9ff74e95
SW
3653sub _auth_providers () {
3654 [
3655 SVN::Client::get_simple_provider(),
3656 SVN::Client::get_ssl_server_trust_file_provider(),
3657 SVN::Client::get_simple_prompt_provider(
3658 \&Git::SVN::Prompt::simple, 2),
3659 SVN::Client::get_ssl_client_cert_file_provider(),
3660 SVN::Client::get_ssl_client_cert_prompt_provider(
3661 \&Git::SVN::Prompt::ssl_client_cert, 2),
77266e96 3662 SVN::Client::get_ssl_client_cert_pw_file_provider(),
9ff74e95
SW
3663 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3664 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3665 SVN::Client::get_username_provider(),
3666 SVN::Client::get_ssl_server_trust_prompt_provider(
3667 \&Git::SVN::Prompt::ssl_server_trust),
3668 SVN::Client::get_username_prompt_provider(
3669 \&Git::SVN::Prompt::username, 2)
3670 ]
3671}
3672
cfbe7ab3
EW
3673sub escape_uri_only {
3674 my ($uri) = @_;
3675 my @tmp;
3676 foreach (split m{/}, $uri) {
d1a8d0ea 3677 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
cfbe7ab3
EW
3678 push @tmp, $_;
3679 }
3680 join('/', @tmp);
3681}
3682
3683sub escape_url {
3684 my ($url) = @_;
3685 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3686 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3687 $url = "$scheme://$domain$uri";
3688 }
3689 $url;
3690}
3691
d81bf827
EW
3692sub new {
3693 my ($class, $url) = @_;
f6f09876 3694 $url =~ s!/+$!!;
5d3b7cd5 3695 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 3696
d81bf827 3697 SVN::_Core::svn_config_ensure($config_dir, undef);
9ff74e95 3698 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
d81bf827 3699 my $config = SVN::Core::config_get_config($config_dir);
7730fbe6 3700 $RA = undef;
602015e0
ER
3701 my $dont_store_passwords = 1;
3702 my $conf_t = ${$config}{'config'};
3703 {
fd499bcc 3704 no warnings 'once';
602015e0
ER
3705 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3706 # produces warnings that variables are used only once.
3707 # I had not found the better way to shut them up, so
fd499bcc 3708 # the warnings of type 'once' are disabled in this block.
602015e0
ER
3709 if (SVN::_Core::svn_config_get_bool($conf_t,
3710 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3711 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3712 1) == 0) {
3713 SVN::_Core::svn_auth_set_parameter($baton,
3714 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3715 bless (\$dont_store_passwords, "_p_void"));
3716 }
3717 if (SVN::_Core::svn_config_get_bool($conf_t,
3718 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3719 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3720 1) == 0) {
3721 $Git::SVN::Prompt::_no_auth_cache = 1;
3722 }
fd499bcc 3723 } # no warnings 'once'
cfbe7ab3 3724 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
d81bf827
EW
3725 config => $config,
3726 pool => SVN::Pool->new,
3727 auth_provider_callbacks => $callbacks);
cfbe7ab3 3728 $self->{url} = $url;
d81bf827
EW
3729 $self->{svn_path} = $url;
3730 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 3731 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
0dc03d6a
EW
3732 $self->{cache} = { check_path => { r => 0, data => {} },
3733 get_dir => { r => 0, data => {} } };
5d3b7cd5 3734 $RA = bless $self, $class;
d81bf827
EW
3735}
3736
0dc03d6a
EW
3737sub check_path {
3738 my ($self, $path, $r) = @_;
3739 my $cache = $self->{cache}->{check_path};
3740 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3741 return $cache->{data}->{$path};
3742 }
3743 my $pool = SVN::Pool->new;
3744 my $t = $self->SUPER::check_path($path, $r, $pool);
3745 $pool->clear;
3746 if ($r != $cache->{r}) {
3747 %{$cache->{data}} = ();
3748 $cache->{r} = $r;
3749 }
3750 $cache->{data}->{$path} = $t;
3751}
3752
3753sub get_dir {
3754 my ($self, $dir, $r) = @_;
3755 my $cache = $self->{cache}->{get_dir};
3756 if ($r == $cache->{r}) {
3757 if (my $x = $cache->{data}->{$dir}) {
3758 return wantarray ? @$x : $x->[0];
3759 }
3760 }
3761 my $pool = SVN::Pool->new;
3762 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3763 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3764 $pool->clear;
3765 if ($r != $cache->{r}) {
3766 %{$cache->{data}} = ();
3767 $cache->{r} = $r;
3768 }
3769 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3770 wantarray ? (\%dirents, $r, $props) : \%dirents;
3771}
3772
d81bf827 3773sub DESTROY {
5d3b7cd5 3774 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
3775}
3776
d81bf827
EW
3777sub get_log {
3778 my ($self, @args) = @_;
3779 my $pool = SVN::Pool->new;
d81bf827
EW
3780 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3781 my $ret = $self->SUPER::get_log(@args, $pool);
3782 $pool->clear;
3783 $ret;
3784}
3785
9ff74e95
SW
3786sub trees_match {
3787 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3788 my $ctx = SVN::Client->new(auth => _auth_providers);
3789 my $out = IO::File->new_tmpfile;
3790
3791 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3792 # $ctx->diff(), so we'll create a default one
3793 my $pool = SVN::Pool->new_default_sub;
3794
3795 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3796 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3797 $out->flush;
3798 my $ret = (($out->stat)[7] == 0);
3799 close $out or croak $!;
3800
3801 $ret;
3802}
3803
d81bf827 3804sub get_commit_editor {
44320b9e 3805 my ($self, $log, $cb, $pool) = @_;
d81bf827 3806 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 3807 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
3808}
3809
d81bf827 3810sub gs_do_update {
8a603774
EW
3811 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3812 my $new = ($rev_a == $rev_b);
3813 my $path = $gs->{path};
3814
2e5e2480
EW
3815 if ($new && -e $gs->{index}) {
3816 unlink $gs->{index} or die
3817 "Couldn't unlink index: $gs->{index}: $!\n";
3818 }
d81bf827 3819 my $pool = SVN::Pool->new;
8b8fc068 3820 $editor->set_path_strip($path);
2b27f6c8
EW
3821 my (@pc) = split m#/#, $path;
3822 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 3823 1, $editor, $pool);
d81bf827 3824 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
3825
3826 # Since we can't rely on svn_ra_reparent being available, we'll
3827 # just have to do some magic with set_path to make it so
3828 # we only want a partial path.
3829 my $sp = '';
3830 my $final = join('/', @pc);
3831 while (@pc) {
3832 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3833 $sp .= '/' if length $sp;
3834 $sp .= shift @pc;
3835 }
3836 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3837
2b27f6c8
EW
3838 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3839
d81bf827
EW
3840 $reporter->finish_report($pool);
3841 $pool->clear;
3842 $editor->{git_commit_ok};
3843}
3844
2b27f6c8
EW
3845# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3846# svn_ra_reparent didn't work before 1.4)
d81bf827 3847sub gs_do_switch {
8a603774
EW
3848 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3849 my $path = $gs->{path};
d81bf827 3850 my $pool = SVN::Pool->new;
2b27f6c8
EW
3851
3852 my $full_url = $self->{url};
3853 my $old_url = $full_url;
cfbe7ab3 3854 $full_url .= '/' . escape_uri_only($path) if length $path;
5d3b7cd5
EW
3855 my ($ra, $reparented);
3856 if ($old_url ne $full_url) {
3857 if ($old_url !~ m#^svn(\+ssh)?://#) {
3858 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3859 $pool);
3860 $self->{url} = $full_url;
3861 $reparented = 1;
3862 } else {
a51cdb0c
EW
3863 $_[0] = undef;
3864 $self = undef;
3865 $RA = undef;
5d3b7cd5 3866 $ra = Git::SVN::Ra->new($full_url);
a51cdb0c 3867 $ra_invalid = 1;
5d3b7cd5
EW
3868 }
3869 }
3870 $ra ||= $self;
8a603774 3871 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 3872 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 3873 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 3874 $reporter->finish_report($pool);
2b27f6c8 3875
5d3b7cd5
EW
3876 if ($reparented) {
3877 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3878 $self->{url} = $old_url;
3879 }
2b27f6c8 3880
d81bf827
EW
3881 $pool->clear;
3882 $editor->{git_commit_ok};
3883}
3884
b54a901e
EW
3885sub longest_common_path {
3886 my ($gsv, $globs) = @_;
d2ae1434 3887 my %common;
e518192f
EW
3888 my $common_max = scalar @$gsv;
3889
3890 foreach my $gs (@$gsv) {
d2ae1434
EW
3891 my @tmp = split m#/#, $gs->{path};
3892 my $p = '';
3893 foreach (@tmp) {
3894 $p .= length($p) ? "/$_" : $_;
3895 $common{$p} ||= 0;
3896 $common{$p}++;
3897 }
3898 }
e518192f
EW
3899 $globs ||= [];
3900 $common_max += scalar @$globs;
3901 foreach my $glob (@$globs) {
3902 my @tmp = split m#/#, $glob->{path}->{left};
3903 my $p = '';
3904 foreach (@tmp) {
3905 $p .= length($p) ? "/$_" : $_;
3906 $common{$p} ||= 0;
3907 $common{$p}++;
3908 }
3909 }
3910
d2ae1434
EW
3911 my $longest_path = '';
3912 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 3913 if ($common{$_} == $common_max) {
d2ae1434
EW
3914 $longest_path = $_;
3915 last;
3916 }
0af9c9f9 3917 }
b54a901e
EW
3918 $longest_path;
3919}
3920
3921sub gs_fetch_loop_common {
3922 my ($self, $base, $head, $gsv, $globs) = @_;
3923 return if ($base > $head);
3924 my $inc = $_log_window_size;
3925 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3926 my $longest_path = longest_common_path($gsv, $globs);
a51cdb0c 3927 my $ra_url = $self->{url};
0af9c9f9 3928 while (1) {
d4eff2bd 3929 my %revs;
d2ae1434 3930 my $err;
f7c3fc4a 3931 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
3932 $SVN::Error::handler = sub {
3933 ($err) = @_;
3934 skip_unknown_revs($err);
3935 };
3936 sub _cb {
3937 my ($paths, $r, $author, $date, $log) = @_;
3938 [ dup_changed_paths($paths),
3939 { author => $author, date => $date, log => $log } ];
3940 }
3941 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3942 sub { $revs{$_[1]} = _cb(@_) });
3943 if ($err && $max >= $head) {
3944 print STDERR "Path '$longest_path' ",
3945 "was probably deleted:\n",
3946 $err->expanded_message,
3947 "\nWill attempt to follow ",
3948 "revisions r$min .. r$max ",
3949 "committed before the deletion\n";
3950 my $hi = $max;
3951 while (--$hi >= $min) {
3952 my $ok;
3953 $self->get_log([$longest_path], $min, $hi,
3954 0, 1, 1, sub {
3955 $ok ||= $_[1];
3956 $revs{$_[1]} = _cb(@_) });
3957 if ($ok) {
3958 print STDERR "r$min .. r$ok OK\n";
3959 last;
3960 }
3961 }
3962 }
d4eff2bd 3963 $SVN::Error::handler = $err_handler;
fbcc1737 3964
e518192f 3965 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 3966 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 3967 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
3968
3969 foreach my $gs ($self->match_globs(\%exists, $paths,
3970 $globs, $r)) {
060610c5 3971 if ($gs->rev_map_max >= $r) {
fbcc1737
EW
3972 next;
3973 }
3974 next unless $gs->match_paths($paths, $r);
3975 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
3976 if (my $last_commit = $gs->last_commit) {
3977 $gs->assert_index_clean($last_commit);
3978 }
fbcc1737
EW
3979 my $log_entry = $gs->do_fetch($paths, $r);
3980 if ($log_entry) {
0af9c9f9
EW
3981 $gs->do_git_commit($log_entry);
3982 }
321b1842 3983 $INDEX_FILES{$gs->{index}} = 1;
0af9c9f9 3984 }
e518192f 3985 foreach my $g (@$globs) {
93f2689c
EW
3986 my $k = "svn-remote.$g->{remote}." .
3987 "$g->{t}-maxRev";
3988 Git::SVN::tmp_config($k, $r);
e518192f 3989 }
a51cdb0c
EW
3990 if ($ra_invalid) {
3991 $_[0] = undef;
3992 $self = undef;
3993 $RA = undef;
3994 $self = Git::SVN::Ra->new($ra_url);
3995 $ra_invalid = undef;
3996 }
0af9c9f9 3997 }
9c93fee5
EW
3998 # pre-fill the .rev_db since it'll eventually get filled in
3999 # with '0' x40 if something new gets committed
e518192f 4000 foreach my $gs (@$gsv) {
66ab84b9
EW
4001 next if $gs->rev_map_max >= $max;
4002 next if defined $gs->rev_map_get($max);
4003 $gs->rev_map_set($max, 0 x40);
9c93fee5 4004 }
c3560e53
EW
4005 foreach my $g (@$globs) {
4006 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4007 Git::SVN::tmp_config($k, $max);
4008 }
0af9c9f9
EW
4009 last if $max >= $head;
4010 $min = $max + 1;
4011 $max += $inc;
4012 $max = $head if ($max > $head);
4013 }
94bc914c 4014 Git::SVN::gc();
0af9c9f9
EW
4015}
4016
e518192f
EW
4017sub match_globs {
4018 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
4019
4020 sub get_dir_check {
4021 my ($self, $exists, $g, $r) = @_;
4022 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
4023 return unless scalar @x == 3;
4024 my $dirents = $x[0];
4025 foreach my $de (keys %$dirents) {
0dc03d6a 4026 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
74a81227
EW
4027 my $p = $g->{path}->full_path($de);
4028 next if $exists->{$p};
4029 next if (length $g->{path}->{right} &&
4030 ($self->check_path($p, $r) !=
4031 $SVN::Node::dir));
4032 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4033 $g->{ref}->full_path($de), 1);
4034 }
4035 }
e518192f 4036 foreach my $g (@$globs) {
74a81227
EW
4037 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4038 if ($path->{action} =~ /^[AR]$/) {
4039 get_dir_check($self, $exists, $g, $r);
4040 }
4041 }
e518192f 4042 foreach (keys %$paths) {
28710f74
EW
4043 if (/$g->{path}->{left_regex}/ &&
4044 !/$g->{path}->{regex}/) {
74a81227
EW
4045 next if $paths->{$_}->{action} !~ /^[AR]$/;
4046 get_dir_check($self, $exists, $g, $r);
4047 }
e518192f
EW
4048 next unless /$g->{path}->{regex}/;
4049 my $p = $1;
4050 my $pathname = $g->{path}->full_path($p);
4051 next if $exists->{$pathname};
0c1ec5a1
EW
4052 next if ($self->check_path($pathname, $r) !=
4053 $SVN::Node::dir);
e518192f
EW
4054 $exists->{$pathname} = Git::SVN->init(
4055 $self->{url}, $pathname, undef,
4056 $g->{ref}->full_path($p), 1);
4057 }
4058 my $c = '';
4059 foreach (split m#/#, $g->{path}->{left}) {
4060 $c .= "/$_";
4061 next unless ($paths->{$c} &&
74a81227
EW
4062 ($paths->{$c}->{action} =~ /^[AR]$/));
4063 get_dir_check($self, $exists, $g, $r);
e518192f
EW
4064 }
4065 }
4066 values %$exists;
4067}
4068
e6434f87
EW
4069sub minimize_url {
4070 my ($self) = @_;
4071 return $self->{url} if ($self->{url} eq $self->{repos_root});
4072 my $url = $self->{repos_root};
4073 my @components = split(m!/!, $self->{svn_path});
4074 my $c = '';
4075 do {
4076 $url .= "/$c" if length $c;
4077 eval { (ref $self)->new($url)->get_latest_revnum };
4078 } while ($@ && ($c = shift @components));
4079 $url;
4080}
4081
d81bf827
EW
4082sub can_do_switch {
4083 my $self = shift;
4084 unless (defined $can_do_switch) {
4085 my $pool = SVN::Pool->new;
4086 my $rep = eval {
4087 $self->do_switch(1, '', 0, $self->{url},
4088 SVN::Delta::Editor->new, $pool);
4089 };
4090 if ($@) {
4091 $can_do_switch = 0;
4092 } else {
4093 $rep->abort_report($pool);
4094 $can_do_switch = 1;
4095 }
4096 $pool->clear;
4097 }
4098 $can_do_switch;
4099}
4100
0af9c9f9
EW
4101sub skip_unknown_revs {
4102 my ($err) = @_;
4103 my $errno = $err->apr_err();
4104 # Maybe the branch we're tracking didn't
4105 # exist when the repo started, so it's
4106 # not an error if it doesn't, just continue
4107 #
4108 # Wonderfully consistent library, eh?
4109 # 160013 - svn:// and file://
4110 # 175002 - http(s)://
4111 # 175007 - http(s):// (this repo required authorization, too...)
4112 # More codes may be discovered later...
4113 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
4114 my $err_key = $err->expanded_message;
4115 # revision numbers change every time, filter them out
4116 $err_key =~ s/\d+/\0/g;
4117 $err_key = "$errno\0$err_key";
4118 unless ($ignored_err{$err_key}) {
4119 warn "W: Ignoring error from SVN, path probably ",
4120 "does not exist: ($errno): ",
4121 $err->expanded_message,"\n";
eee8a174
EW
4122 warn "W: Do not be alarmed at the above message ",
4123 "git-svn is just searching aggressively for ",
4124 "old history.\n",
4125 "This may take a while on large repositories\n";
a6a15a99
EW
4126 $ignored_err{$err_key} = 1;
4127 }
0af9c9f9
EW
4128 return;
4129 }
4130 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4131}
4132
4133# svn_log_changed_path_t objects passed to get_log are likely to be
4134# overwritten even if only the refs are copied to an external variable,
4135# so we should dup the structures in their entirety. Using an externally
4136# passed pool (instead of our temporary and quickly cleared pool in
4137# Git::SVN::Ra) does not help matters at all...
4138sub dup_changed_paths {
4139 my ($paths) = @_;
4140 return undef unless $paths;
4141 my %ret;
4142 foreach my $p (keys %$paths) {
4143 my $i = $paths->{$p};
4144 my %s = map { $_ => $i->$_ }
4145 qw/copyfrom_path copyfrom_rev action/;
4146 $ret{$p} = \%s;
4147 }
4148 \%ret;
4149}
4150
f8c9d1d2
EW
4151package Git::SVN::Log;
4152use strict;
4153use warnings;
4154use POSIX qw/strftime/;
111947ef 4155use constant commit_log_separator => ('-' x 72) . "\n";
f8c9d1d2
EW
4156use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4157 %rusers $show_commit $incremental/;
4158my $l_fmt;
4159
4160sub cmt_showable {
4161 my ($c) = @_;
4162 return 1 if defined $c->{r};
c16d0871
EW
4163
4164 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
4165 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4166 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 4167 @{$c->{l}} = ();
44320b9e 4168 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
4169
4170 # shift off the headers
4171 shift @log while ($log[0] ne '');
44320b9e 4172 shift @log;
c16d0871
EW
4173
4174 # TODO: make $c->{l} not have a trailing newline in the future
4175 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
4176
4177 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 4178 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
4179 }
4180 return defined $c->{r};
4181}
4182
4183sub log_use_color {
cd459e3f 4184 return $color || Git->repository->get_colorbool('color.diff');
f8c9d1d2
EW
4185}
4186
4187sub git_svn_log_cmd {
3bc718ba
EW
4188 my ($r_min, $r_max, @args) = @_;
4189 my $head = 'HEAD';
6ed77266 4190 my (@files, @log_opts);
3bc718ba 4191 foreach my $x (@args) {
6ed77266
EW
4192 if ($x eq '--' || @files) {
4193 push @files, $x;
4194 } else {
4195 if (::verify_ref("$x^0")) {
4196 $head = $x;
4197 } else {
4198 push @log_opts, $x;
4199 }
4200 }
3bc718ba
EW
4201 }
4202
13c823fb
EW
4203 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4204 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
4205 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4206 $gs->refname);
4207 push @cmd, '-r' unless $non_recursive;
4208 push @cmd, qw/--raw --name-status/ if $verbose;
4209 push @cmd, '--color' if log_use_color();
6ed77266
EW
4210 push @cmd, @log_opts;
4211 if (defined $r_max && $r_max == $r_min) {
f8c9d1d2 4212 push @cmd, '--max-count=1';
060610c5 4213 if (my $c = $gs->rev_map_get($r_max)) {
f8c9d1d2
EW
4214 push @cmd, $c;
4215 }
6ed77266 4216 } elsif (defined $r_max) {
111947ef
DK
4217 if ($r_max < $r_min) {
4218 ($r_min, $r_max) = ($r_max, $r_min);
4219 }
4220 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4221 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4222 # If there are no commits in the range, both $c_max and $c_min
4223 # will be undefined. If there is at least 1 commit in the
4224 # range, both will be defined.
4225 return () if !defined $c_min || !defined $c_max;
4226 if ($c_min eq $c_max) {
4227 push @cmd, '--max-count=1', $c_min;
f8c9d1d2 4228 } else {
111947ef 4229 push @cmd, '--boundary', "$c_min..$c_max";
f8c9d1d2
EW
4230 }
4231 }
6ed77266 4232 return (@cmd, @files);
f8c9d1d2
EW
4233}
4234
4235# adapted from pager.c
4236sub config_pager {
4237 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4238 if (!defined $pager) {
4239 $pager = 'less';
4240 } elsif (length $pager == 0 || $pager eq 'cat') {
4241 $pager = undef;
4242 }
cd459e3f 4243 $ENV{GIT_PAGER_IN_USE} = defined($pager);
f8c9d1d2
EW
4244}
4245
4246sub run_pager {
b0193048 4247 return unless -t *STDOUT && defined $pager;
f8c9d1d2 4248 pipe my $rfd, my $wfd or return;
207f1a75 4249 defined(my $pid = fork) or ::fatal "Can't fork: $!";
f8c9d1d2
EW
4250 if (!$pid) {
4251 open STDOUT, '>&', $wfd or
207f1a75 4252 ::fatal "Can't redirect to stdout: $!";
f8c9d1d2
EW
4253 return;
4254 }
207f1a75 4255 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
f8c9d1d2 4256 $ENV{LESS} ||= 'FRSX';
207f1a75 4257 exec $pager or ::fatal "Can't run pager: $! ($pager)";
f8c9d1d2
EW
4258}
4259
b2b3ada7
DK
4260sub format_svn_date {
4261 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4262}
4263
4264sub parse_git_date {
4265 my ($t, $tz) = @_;
4266 # Date::Parse isn't in the standard Perl distro :(
4267 if ($tz =~ s/^\+//) {
4268 $t += tz_to_s_offset($tz);
4269 } elsif ($tz =~ s/^\-//) {
4270 $t -= tz_to_s_offset($tz);
4271 }
4272 return $t;
4273}
4274
4275sub set_local_timezone {
4276 if (defined $TZ) {
4277 $ENV{TZ} = $TZ;
4278 } else {
4279 delete $ENV{TZ};
4280 }
4281}
4282
21819a37
EW
4283sub tz_to_s_offset {
4284 my ($tz) = @_;
4285 $tz =~ s/(\d\d)$//;
4286 return ($1 * 60) + ($tz * 3600);
4287}
4288
f8c9d1d2
EW
4289sub get_author_info {
4290 my ($dest, $author, $t, $tz) = @_;
4291 $author =~ s/(?:^\s*|\s*$)//g;
4292 $dest->{a_raw} = $author;
4293 my $au;
1c8443b0 4294 if ($::_authors) {
f8c9d1d2
EW
4295 $au = $rusers{$author} || undef;
4296 }
4297 if (!$au) {
4298 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4299 }
4300 $dest->{t} = $t;
4301 $dest->{tz} = $tz;
4302 $dest->{a} = $au;
b2b3ada7 4303 $dest->{t_utc} = parse_git_date($t, $tz);
f8c9d1d2
EW
4304}
4305
4306sub process_commit {
4307 my ($c, $r_min, $r_max, $defer) = @_;
4308 if (defined $r_min && defined $r_max) {
4309 if ($r_min == $c->{r} && $r_min == $r_max) {
4310 show_commit($c);
4311 return 0;
4312 }
4313 return 1 if $r_min == $r_max;
4314 if ($r_min < $r_max) {
4315 # we need to reverse the print order
4316 return 0 if (defined $limit && --$limit < 0);
4317 push @$defer, $c;
4318 return 1;
4319 }
4320 if ($r_min != $r_max) {
4321 return 1 if ($r_min < $c->{r});
4322 return 1 if ($r_max > $c->{r});
4323 }
4324 }
4325 return 0 if (defined $limit && --$limit < 0);
4326 show_commit($c);
4327 return 1;
4328}
4329
4330sub show_commit {
4331 my $c = shift;
4332 if ($oneline) {
4333 my $x = "\n";
4334 if (my $l = $c->{l}) {
4335 while ($l->[0] =~ /^\s*$/) { shift @$l }
4336 $x = $l->[0];
4337 }
4338 $l_fmt ||= 'A' . length($c->{r});
4339 print 'r',pack($l_fmt, $c->{r}),' | ';
4340 print "$c->{c} | " if $show_commit;
4341 print $x;
4342 } else {
4343 show_commit_normal($c);
4344 }
4345}
4346
4347sub show_commit_changed_paths {
4348 my ($c) = @_;
4349 return unless $c->{changed};
4350 print "Changed paths:\n", @{$c->{changed}};
4351}
4352
4353sub show_commit_normal {
4354 my ($c) = @_;
111947ef 4355 print commit_log_separator, "r$c->{r} | ";
f8c9d1d2 4356 print "$c->{c} | " if $show_commit;
b2b3ada7 4357 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
f8c9d1d2
EW
4358 my $nr_line = 0;
4359
4360 if (my $l = $c->{l}) {
4361 while ($l->[$#$l] eq "\n" && $#$l > 0
4362 && $l->[($#$l - 1)] eq "\n") {
4363 pop @$l;
4364 }
4365 $nr_line = scalar @$l;
4366 if (!$nr_line) {
4367 print "1 line\n\n\n";
4368 } else {
4369 if ($nr_line == 1) {
4370 $nr_line = '1 line';
4371 } else {
4372 $nr_line .= ' lines';
4373 }
4374 print $nr_line, "\n";
4375 show_commit_changed_paths($c);
4376 print "\n";
4377 print $_ foreach @$l;
4378 }
4379 } else {
4380 print "1 line\n";
4381 show_commit_changed_paths($c);
4382 print "\n";
4383
4384 }
488a63ec 4385 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
4386 if ($c->{$x}) {
4387 print "\n";
4388 print $_ foreach @{$c->{$x}}
4389 }
4390 }
4391}
4392
4393sub cmd_show_log {
4394 my (@args) = @_;
4395 my ($r_min, $r_max);
4396 my $r_last = -1; # prevent dupes
b2b3ada7 4397 set_local_timezone();
f8c9d1d2
EW
4398 if (defined $::_revision) {
4399 if ($::_revision =~ /^(\d+):(\d+)$/) {
4400 ($r_min, $r_max) = ($1, $2);
4401 } elsif ($::_revision =~ /^\d+$/) {
4402 $r_min = $r_max = $::_revision;
4403 } else {
4404 ::fatal "-r$::_revision is not supported, use ",
207f1a75 4405 "standard 'git log' arguments instead";
f8c9d1d2
EW
4406 }
4407 }
4408
4409 config_pager();
6ed77266 4410 @args = git_svn_log_cmd($r_min, $r_max, @args);
111947ef
DK
4411 if (!@args) {
4412 print commit_log_separator unless $incremental || $oneline;
4413 return;
4414 }
f8c9d1d2
EW
4415 my $log = command_output_pipe(@args);
4416 run_pager();
488a63ec 4417 my (@k, $c, $d, $stat);
f8c9d1d2
EW
4418 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4419 while (<$log>) {
60f3ff12 4420 if (/^${esc_color}commit -?($::sha1_short)/o) {
f8c9d1d2
EW
4421 my $cmt = $1;
4422 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4423 $r_last = $c->{r};
4424 process_commit($c, $r_min, $r_max, \@k) or
4425 goto out;
4426 }
4427 $d = undef;
4428 $c = { c => $cmt };
4429 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4430 get_author_info($c, $1, $2, $3);
4431 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4432 # ignore
4433 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4434 push @{$c->{raw}}, $_;
4435 } elsif (/^${esc_color}[ACRMDT]\t/) {
4436 # we could add $SVN->{svn_path} here, but that requires
4437 # remote access at the moment (repo_path_split)...
4438 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4439 push @{$c->{changed}}, $_;
4440 } elsif (/^${esc_color}diff /o) {
4441 $d = 1;
4442 push @{$c->{diff}}, $_;
4443 } elsif ($d) {
4444 push @{$c->{diff}}, $_;
488a63ec
EW
4445 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4446 $esc_color*[\+\-]*$esc_color$/x) {
4447 $stat = 1;
4448 push @{$c->{stat}}, $_;
4449 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4450 push @{$c->{stat}}, $_;
4451 $stat = undef;
f8c9d1d2
EW
4452 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4453 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4454 } elsif (s/^${esc_color} //o) {
4455 push @{$c->{l}}, $_;
4456 }
4457 }
4458 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4459 $r_last = $c->{r};
4460 process_commit($c, $r_min, $r_max, \@k);
4461 }
4462 if (@k) {
111947ef 4463 ($r_min, $r_max) = ($r_max, $r_min);
f8c9d1d2
EW
4464 process_commit($_, $r_min, $r_max) foreach reverse @k;
4465 }
4466out:
c843c464 4467 close $log;
111947ef 4468 print commit_log_separator unless $incremental || $oneline;
f8c9d1d2
EW
4469}
4470
6fb5375e 4471sub cmd_blame {
4be40381 4472 my $path = pop;
6fb5375e
TS
4473
4474 config_pager();
4475 run_pager();
4476
4be40381
SG
4477 my ($fh, $ctx, $rev);
4478
4479 if ($_git_format) {
4480 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4481 while (my $line = <$fh>) {
4482 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4483 # Uncommitted edits show up as a rev ID of
4484 # all zeros, which we can't look up with
4485 # cmt_metadata
4486 if ($1 !~ /^0+$/) {
4487 (undef, $rev, undef) =
4488 ::cmt_metadata($1);
4489 $rev = '0' if (!$rev);
4490 } else {
4491 $rev = '0';
4492 }
4493 $rev = sprintf('%-10s', $rev);
4494 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4495 }
4496 print $line;
4497 }
4498 } else {
4499 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4500 '--', $path);
4501 my ($sha1);
4502 my %authors;
4503 while (my $line = <$fh>) {
4504 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4505 $sha1 = $1;
4506 (undef, $rev, undef) = ::cmt_metadata($1);
4507 $rev = '0' if (!$rev);
4508 }
4509 elsif ($line =~ /^author (.*)/) {
4510 $authors{$rev} = $1;
4511 $authors{$rev} =~ s/\s/_/g;
4512 }
4513 elsif ($line =~ /^\t(.*)$/) {
4514 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4515 }
6fb5375e 4516 }
6fb5375e
TS
4517 }
4518 command_close_pipe($fh, $ctx);
4519}
4520
706587fc
EW
4521package Git::SVN::Migration;
4522# these version numbers do NOT correspond to actual version numbers
4523# of git nor git-svn. They are just relative.
4524#
4525# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4526#
4527# v1 layout: .git/$id/info/url, refs/remotes/$id
4528#
4529# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4530#
4531# v3 layout: .git/svn/$id, refs/remotes/$id
4532# - info/url may remain for backwards compatibility
4533# - this is what we migrate up to this layout automatically,
4534# - this will be used by git svn init on single branches
26a62d57
EW
4535# v3.1 layout (auto migrated):
4536# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4537# for backwards compatibility
706587fc
EW
4538#
4539# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4540# - this is only created for newly multi-init-ed
4541# repositories. Similar in spirit to the
4542# --use-separate-remotes option in git-clone (now default)
4543# - we do not automatically migrate to this (following
4544# the example set by core git)
060610c5
EW
4545#
4546# v5 layout: .rev_db.$UUID => .rev_map.$UUID
4547# - newer, more-efficient format that uses 24-bytes per record
4548# with no filler space.
4549# - use xxd -c24 < .rev_map.$UUID to view and debug
4550# - This is a one-way migration, repositories updated to the
4551# new format will not be able to use old git-svn without
4552# rebuilding the .rev_db. Rebuilding the rev_db is not
4553# possible if noMetadata or useSvmProps are set; but should
4554# be no problem for users that use the (sensible) defaults.
706587fc
EW
4555use strict;
4556use warnings;
4557use Carp qw/croak/;
4558use File::Path qw/mkpath/;
47e39c55
EW
4559use File::Basename qw/dirname basename/;
4560use vars qw/$_minimize/;
706587fc
EW
4561
4562sub migrate_from_v0 {
4563 my $git_dir = $ENV{GIT_DIR};
4564 return undef unless -d $git_dir;
4565 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4566 my $migrated = 0;
4567 while (<$fh>) {
4568 chomp;
4569 my ($id, $orig_ref) = ($_, $_);
4570 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4571 next unless -f "$git_dir/$id/info/url";
4572 my $new_ref = "refs/remotes/$id";
4573 if (::verify_ref("$new_ref^0")) {
4574 print STDERR "W: $orig_ref is probably an old ",
4575 "branch used by an ancient version of ",
4576 "git-svn.\n",
4577 "However, $new_ref also exists.\n",
4578 "We will not be able ",
4579 "to use this branch until this ",
4580 "ambiguity is resolved.\n";
4581 next;
4582 }
4583 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4584 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4585 command_noisy('update-ref', $new_ref, $orig_ref);
4586 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4587 $migrated++;
4588 }
4589 command_close_pipe($fh, $ctx);
4590 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4591 $migrated;
4592}
4593
4594sub migrate_from_v1 {
4595 my $git_dir = $ENV{GIT_DIR};
4596 my $migrated = 0;
4597 return $migrated unless -d $git_dir;
4598 my $svn_dir = "$git_dir/svn";
4599
4600 # just in case somebody used 'svn' as their $id at some point...
4601 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4602
4603 print STDERR "Migrating from a git-svn v1 layout...\n";
4604 mkpath([$svn_dir]);
4605 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4606 "$svn_dir\n\t(required for this version ",
4607 "($::VERSION) of git-svn) does not. exist\n";
4608 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4609 while (<$fh>) {
4610 my $x = $_;
4611 next unless $x =~ s#^refs/remotes/##;
4612 chomp $x;
4613 next unless -f "$git_dir/$x/info/url";
4614 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4615 next unless $u;
4616 my $dn = dirname("$git_dir/svn/$x");
4617 mkpath([$dn]) unless -d $dn;
4618 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4619 mkpath(["$git_dir/svn/svn"]);
4620 print STDERR " - $git_dir/$x/info => ",
4621 "$git_dir/svn/$x/info\n";
4622 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4623 croak "$!: $x";
4624 # don't worry too much about these, they probably
4625 # don't exist with repos this old (save for index,
4626 # and we can easily regenerate that)
4627 foreach my $f (qw/unhandled.log index .rev_db/) {
4628 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4629 }
4630 } else {
4631 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4632 rename "$git_dir/$x", "$git_dir/svn/$x" or
4633 croak "$!: $x";
4634 }
4635 $migrated++;
4636 }
4637 command_close_pipe($fh, $ctx);
4638 print STDERR "Done migrating from a git-svn v1 layout\n";
4639 $migrated;
4640}
4641
4642sub read_old_urls {
4643 my ($l_map, $pfx, $path) = @_;
4644 my @dir;
4645 foreach (<$path/*>) {
4646 if (-r "$_/info/url") {
4647 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4648 my $ref_id = $pfx . basename $_;
4649 my $url = ::file_to_s("$_/info/url");
4650 $l_map->{$ref_id} = $url;
4651 } elsif (-d $_) {
4652 push @dir, $_;
4653 }
4654 }
4655 foreach (@dir) {
4656 my $x = $_;
4657 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4658 read_old_urls($l_map, $x, $_);
4659 }
4660}
4661
4662sub migrate_from_v2 {
4663 my @cfg = command(qw/config -l/);
4664 return if grep /^svn-remote\..+\.url=/, @cfg;
4665 my %l_map;
4666 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4667 my $migrated = 0;
4668
4669 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
4670 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4671 if ($@) {
4672 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4673 }
706587fc
EW
4674 $migrated++;
4675 }
4676 $migrated;
4677}
4678
47e39c55
EW
4679sub minimize_connections {
4680 my $r = Git::SVN::read_all_remotes();
4681 my $new_urls = {};
4682 my $root_repos = {};
4683 foreach my $repo_id (keys %$r) {
4684 my $url = $r->{$repo_id}->{url} or next;
4685 my $fetch = $r->{$repo_id}->{fetch} or next;
4686 my $ra = Git::SVN::Ra->new($url);
4687
4688 # skip existing cases where we already connect to the root
4689 if (($ra->{url} eq $ra->{repos_root}) ||
4690 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4691 $repo_id)) {
4692 $root_repos->{$ra->{url}} = $repo_id;
4693 next;
4694 }
4695
4696 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4697 my $root_path = $ra->{url};
4e9f6cc7 4698 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
4699 foreach my $path (keys %$fetch) {
4700 my $ref_id = $fetch->{$path};
4701 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4702
4703 # make sure we can read when connecting to
4704 # a higher level of a repository
4705 my ($last_rev, undef) = $gs->last_rev_commit;
4706 if (!defined $last_rev) {
4707 $last_rev = eval {
4708 $root_ra->get_latest_revnum;
4709 };
4710 next if $@;
4711 }
4712 my $new = $root_path;
4713 $new .= length $path ? "/$path" : '';
4714 eval {
4715 $root_ra->get_log([$new], $last_rev, $last_rev,
4716 0, 0, 1, sub { });
4717 };
4718 next if $@;
4719 $new_urls->{$ra->{repos_root}}->{$new} =
4720 { ref_id => $ref_id,
4721 old_repo_id => $repo_id,
4722 old_path => $path };
4723 }
4724 }
4725
4726 my @emptied;
4727 foreach my $url (keys %$new_urls) {
4728 # see if we can re-use an existing [svn-remote "repo_id"]
4729 # instead of creating a(n ugly) new section:
4730 my $repo_id = $root_repos->{$url} ||
4731 Git::SVN::sanitize_remote_name($url);
4732
4733 my $fetch = $new_urls->{$url};
4734 foreach my $path (keys %$fetch) {
4735 my $x = $fetch->{$path};
4736 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4737 my $pfx = "svn-remote.$x->{old_repo_id}";
4738
4739 my $old_fetch = quotemeta("$x->{old_path}:".
4740 "refs/remotes/$x->{ref_id}");
8b8fc068 4741 command_noisy(qw/config --unset/,
47e39c55
EW
4742 "$pfx.fetch", '^'. $old_fetch . '$');
4743 delete $r->{$x->{old_repo_id}}->
4744 {fetch}->{$x->{old_path}};
4745 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 4746 command_noisy(qw/config --unset/,
47e39c55
EW
4747 "$pfx.url");
4748 push @emptied, $x->{old_repo_id}
4749 }
4750 }
4751 }
4752 if (@emptied) {
4753 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4754 "$ENV{GIT_DIR}/config";
4755 print STDERR <<EOF;
4756The following [svn-remote] sections in your config file ($file) are empty
4757and can be safely removed:
4758EOF
4759 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4760 }
4761}
4762
706587fc
EW
4763sub migration_check {
4764 migrate_from_v0();
4765 migrate_from_v1();
4766 migrate_from_v2();
47e39c55 4767 minimize_connections() if $_minimize;
706587fc
EW
4768}
4769
ef3cfaad
EW
4770package Git::IndexInfo;
4771use strict;
4772use warnings;
4773use Git qw/command_input_pipe command_close_pipe/;
4774
4775sub new {
4776 my ($class) = @_;
4777 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4778 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4779}
4780
4781sub remove {
4782 my ($self, $path) = @_;
4783 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4784 return ++$self->{nr};
4785 }
4786 undef;
4787}
4788
4789sub update {
4790 my ($self, $mode, $hash, $path) = @_;
4791 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4792 return ++$self->{nr};
4793 }
4794 undef;
4795}
4796
4797sub DESTROY {
4798 my ($self) = @_;
4799 command_close_pipe($self->{gui}, $self->{ctx});
4800}
4801
4bb9ed04
EW
4802package Git::SVN::GlobSpec;
4803use strict;
4804use warnings;
4805
4806sub new {
4807 my ($class, $glob) = @_;
4bb9ed04
EW
4808 my $re = $glob;
4809 $re =~ s!/+$!!g; # no need for trailing slashes
4e9f6cc7 4810 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4bb9ed04
EW
4811 my ($left, $right) = ($1, $2);
4812 if ($nr > 1) {
e518192f
EW
4813 die "Only one '*' wildcard expansion ",
4814 "is supported (got $nr): '$glob'\n";
4bb9ed04 4815 } elsif ($nr == 0) {
e518192f 4816 die "One '*' is needed for glob: '$glob'\n";
4bb9ed04
EW
4817 }
4818 $re = quotemeta($left) . $re . quotemeta($right);
4e9f6cc7
EW
4819 if (length $left && !($left =~ s!/+$!!g)) {
4820 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4821 }
4822 if (length $right && !($right =~ s!^/+!!g)) {
4823 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4824 }
74a81227
EW
4825 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4826 bless { left => $left, right => $right, left_regex => $left_re,
4bb9ed04
EW
4827 regex => qr/$re/, glob => $glob }, $class;
4828}
4829
4830sub full_path {
4831 my ($self, $path) = @_;
4832 return (length $self->{left} ? "$self->{left}/" : '') .
4833 $path . (length $self->{right} ? "/$self->{right}" : '');
4834}
4835
3397f9df
EW
4836__END__
4837
4838Data structures:
4839
4bb9ed04
EW
4840
4841$remotes = { # returned by read_all_remotes()
4842 'svn' => {
4843 # svn-remote.svn.url=https://svn.musicpd.org
4844 url => 'https://svn.musicpd.org',
4845 # svn-remote.svn.fetch=mpd/trunk:trunk
4846 fetch => {
4847 'mpd/trunk' => 'trunk',
4848 },
4849 # svn-remote.svn.tags=mpd/tags/*:tags/*
4850 tags => {
4851 path => {
4852 left => 'mpd/tags',
4853 right => '',
4854 regex => qr!mpd/tags/([^/]+)$!,
4855 glob => 'tags/*',
4856 },
4857 ref => {
4858 left => 'tags',
4859 right => '',
4860 regex => qr!tags/([^/]+)$!,
4861 glob => 'tags/*',
4862 },
4863 }
4864 }
4865};
4866
44320b9e 4867$log_entry hashref as returned by libsvn_log_entry()
3397f9df 4868{
44320b9e 4869 log => 'whitespace-formatted log entry
3397f9df
EW
4870', # trailing newline is preserved
4871 revision => '8', # integer
4872 date => '2004-02-24T17:01:44.108345Z', # commit date
4873 author => 'committer name'
4874};
4875
6e8548cc
EW
4876
4877# this is generated by generate_diff();
3397f9df
EW
4878@mods = array of diff-index line hashes, each element represents one line
4879 of diff-index output
4880
4881diff-index line ($m hash)
4882{
4883 mode_a => first column of diff-index output, no leading ':',
4884 mode_b => second column of diff-index output,
4885 sha1_b => sha1sum of the final blob,
ac8e0b91 4886 chg => change type [MCRADT],
3397f9df
EW
4887 file_a => original file name of a file (iff chg is 'C' or 'R')
4888 file_b => new/current file name of a file (any chg)
4889}
4890;
a5e0cedc 4891
a00439ac
EW
4892# retval of read_url_paths{,_all}();
4893$l_map = {
4894 # repository root url
4895 'https://svn.musicpd.org' => {
4896 # repository path # GIT_SVN_ID
4897 'mpd/trunk' => 'trunk',
4898 'mpd/tags/0.11.5' => 'tags/0.11.5',
4899 },
4900}
4901
a5e0cedc
EW
4902Notes:
4903 I don't trust the each() function on unless I created %hash myself
4904 because the internal iterator may not have started at base.