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