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