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