git-svn: fix delete+add branch tracking with empty files
[git/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,
5de70efb 69 $_git_format, $_commit_url, $_tag);
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,
edc662f9
VS
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
74 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
0bed5eaa 75my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 76 'authors-file|A=s' => \$_authors,
ecc712dd 77 'repack:i' => \$Git::SVN::_repack,
97ae0911
EW
78 'noMetadata' => \$Git::SVN::_no_metadata,
79 'useSvmProps' => \$Git::SVN::_use_svm_props,
62e349d2 80 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
6af1db44 81 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
1e889ef3 82 'no-checkout' => \$_no_checkout,
80f50749 83 'quiet|q' => \$_q,
ecc712dd
EW
84 'repack-flags|repack-args|repack-opts=s' =>
85 \$Git::SVN::_repack_flags,
70ae04e4 86 'use-log-author' => \$Git::SVN::_use_log_author,
6aa9ba14 87 'add-author-from' => \$Git::SVN::_add_author_from,
e82f0d73 88 'localtime' => \$Git::SVN::_localtime,
706587fc 89 %remote_opts );
36f5b1f0 90
8f728fb9 91my ($_trunk, $_tags, $_branches, $_stdlayout);
0dfaf0a4 92my %icv;
dadc6d2a
EW
93my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
94 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
95 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
8f728fb9 96 'stdlayout|s' => \$_stdlayout,
4a1bb4c3 97 'minimize-url|m' => \$Git::SVN::_minimize_url,
0dfaf0a4
EW
98 'no-metadata' => sub { $icv{noMetadata} = 1 },
99 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
100 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
101 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
dadc6d2a 102 %remote_opts );
27e9fb8d 103my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
104 'rmdir' => \$SVN::Git::Editor::_rmdir,
105 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
106 'l=i' => \$SVN::Git::Editor::_rename_limit,
107 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 108);
9d55b41a 109
3397f9df 110my %cmd = (
2a3240be 111 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
e98671e5 112 { 'revision|r=s' => \$_revision,
905f8b7d 113 'fetch-all|all' => \$_fetch_all,
e98671e5 114 %fc_opts } ],
0425ea90
EW
115 clone => [ \&cmd_clone, "Initialize and fetch revisions",
116 { 'revision|r=s' => \$_revision,
117 %fc_opts, %init_opts } ],
d2866f9e 118 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 119 " (requires URL argument)",
9d55b41a 120 \%init_opts ],
dadc6d2a
EW
121 'multi-init' => [ \&cmd_multi_init,
122 "Deprecated alias for ".
123 "'$0 init -T<trunk> -b<branches> -t<tags>'",
124 \%init_opts ],
d7ad3bed
EW
125 dcommit => [ \&cmd_dcommit,
126 'Commit several diffs to merge with upstream',
3289e86e
EW
127 { 'merge|m|M' => \$_merge,
128 'strategy|s=s' => \$_strategy,
905f8b7d 129 'verbose|v' => \$_verbose,
3289e86e 130 'dry-run|n' => \$_dry_run,
905f8b7d 131 'fetch-all|all' => \$_fetch_all,
ba24e745
EW
132 'commit-url=s' => \$_commit_url,
133 'revision|r=i' => \$_revision,
171af110 134 'no-rebase' => \$_no_rebase,
4b155223 135 %cmt_opts, %fc_opts } ],
5de70efb
FR
136 branch => [ \&cmd_branch,
137 'Create a branch in the SVN repository',
138 { 'message|m=s' => \$_message,
139 'dry-run|n' => \$_dry_run,
140 'tag|t' => \$_tag } ],
141 tag => [ sub { $_tag = 1; cmd_branch(@_) },
142 'Create a tag in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run } ],
1ce255dc
EW
145 'set-tree' => [ \&cmd_set_tree,
146 "Set an SVN repository to a git tree-ish",
147 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
148 'create-ignore' => [ \&cmd_create_ignore,
149 'Create a .gitignore per svn:ignore',
150 { 'revision|r=i' => \$_revision
151 } ],
15153451
BS
152 'propget' => [ \&cmd_propget,
153 'Print the value of a property on a file or directory',
154 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
155 'proplist' => [ \&cmd_proplist,
156 'List all properties of a file or directory',
157 { 'revision|r=i' => \$_revision } ],
5969cbe1 158 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 159 { 'revision|r=i' => \$_revision
05b4df31 160 } ],
2d879792
VK
161 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
162 { 'revision|r=i' => \$_revision
163 } ],
1c8443b0 164 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
165 "Deprecated alias for $0 fetch --all",
166 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
167 'migrate' => [ sub { },
168 # no-op, we automatically run this anyways,
706587fc
EW
169 'Migrate configuration/metadata/layout from
170 previous versions of git-svn',
a836a0e1
EW
171 { 'minimize' => \$Git::SVN::Migration::_minimize,
172 %remote_opts } ],
f8c9d1d2
EW
173 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
174 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 175 'revision|r=s' => \$_revision,
f8c9d1d2
EW
176 'verbose|v' => \$Git::SVN::Log::verbose,
177 'incremental' => \$Git::SVN::Log::incremental,
178 'oneline' => \$Git::SVN::Log::oneline,
179 'show-commit' => \$Git::SVN::Log::show_commit,
180 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 181 'authors-file|A=s' => \$_authors,
f8c9d1d2 182 'color' => \$Git::SVN::Log::color,
4dbfe2e9 183 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 184 } ],
222566e4
EW
185 'find-rev' => [ \&cmd_find_rev,
186 "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 187 {} ],
905f8b7d
EW
188 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
189 { 'merge|m|M' => \$_merge,
190 'verbose|v' => \$_verbose,
191 'strategy|s=s' => \$_strategy,
dee41f3e 192 'local|l' => \$_local,
905f8b7d 193 'fetch-all|all' => \$_fetch_all,
7d45e146 194 'dry-run|n' => \$_dry_run,
905f8b7d 195 %fc_opts } ],
44320b9e
EW
196 'commit-diff' => [ \&cmd_commit_diff,
197 'Commit a diff between two trees',
27e9fb8d
EW
198 { 'message|m=s' => \$_message,
199 'file|F=s' => \$_file,
45bf473a 200 'revision|r=s' => \$_revision,
27e9fb8d 201 %cmt_opts } ],
e6fefa92
DK
202 'info' => [ \&cmd_info,
203 "Show info about the latest SVN revision
204 on the current branch",
8b014d71 205 { 'url' => \$_url, } ],
6fb5375e
TS
206 'blame' => [ \&Git::SVN::Log::cmd_blame,
207 "Show what revision and author last modified each line of a file",
4be40381 208 { 'git-format' => \$_git_format } ],
3397f9df 209);
9d55b41a 210
3397f9df
EW
211my $cmd;
212for (my $i = 0; $i < @ARGV; $i++) {
213 if (defined $cmd{$ARGV[$i]}) {
214 $cmd = $ARGV[$i];
215 splice @ARGV, $i, 1;
216 last;
217 }
218};
219
540424b2
EW
220# make sure we're always running at the top-level working directory
221unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
222 unless (-d $ENV{GIT_DIR}) {
223 if ($git_dir_user_set) {
224 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
225 "but it is not a directory\n";
226 }
227 my $git_dir = delete $ENV{GIT_DIR};
fe4003f6
DM
228 my $cdup = undef;
229 git_cmd_try {
230 $cdup = command_oneline(qw/rev-parse --show-cdup/);
231 $git_dir = '.' unless ($cdup);
232 chomp $cdup if ($cdup);
233 $cdup = "." unless ($cdup && length $cdup);
234 } "Already at toplevel, but $git_dir not found\n";
5253dc33
EW
235 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
236 unless (-d $git_dir) {
237 die "$git_dir still not found after going to ",
238 "'$cdup'\n";
239 }
240 $ENV{GIT_DIR} = $git_dir;
241 }
ffe256f9 242 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
5253dc33 243}
f4dd334b
GH
244
245my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
246
247read_repo_config(\%opts);
222566e4
EW
248if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
249 Getopt::Long::Configure('pass_through');
250}
f4dd334b
GH
251my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
252 'minimize-connections' => \$Git::SVN::Migration::_minimize,
253 'id|i=s' => \$Git::SVN::default_ref_id,
254 'svn-remote|remote|R=s' => sub {
255 $Git::SVN::no_reuse_existing = 1;
256 $Git::SVN::default_repo_id = $_[1] });
257exit 1 if (!$rv && $cmd && $cmd ne 'log');
258
259usage(0) if $_help;
260version() if $_version;
261usage(1) unless defined $cmd;
262load_authors() if $_authors;
263
0425ea90 264unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
265 Git::SVN::Migration::migration_check();
266}
ecc712dd 267Git::SVN::init_vars();
b805b44a
EW
268eval {
269 Git::SVN::verify_remotes_sanity();
270 $cmd{$cmd}->[0]->(@ARGV);
271};
272fatal $@ if $@;
1e889ef3 273post_fetch_checkout();
3397f9df
EW
274exit 0;
275
276####################### primary functions ######################
277sub usage {
278 my $exit = shift || 0;
279 my $fd = $exit ? \*STDERR : \*STDOUT;
280 print $fd <<"";
281git-svn - bidirectional operations between a single Subversion tree and git
1b1dd23f 282Usage: git svn <command> [options] [arguments]\n
448c81b4
EW
283
284 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
285
286 foreach (sort keys %cmd) {
448c81b4 287 next if $cmd && $cmd ne $_;
a836a0e1 288 next if /^multi-/; # don't show deprecated commands
b203b769 289 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 290 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
291 # mixed-case options are for .git/config only
292 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 293 # prints out arguments as they should be passed:
b8c92cad 294 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 295 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
296 "--$_" : "-$_" }
297 split /\|/,$_)," $x\n";
298 }
3397f9df
EW
299 }
300 print $fd <<"";
448c81b4
EW
301\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
302arbitrary identifier if you're tracking multiple SVN branches/repositories in
303one git repository and want to keep them separate. See git-svn(1) for more
304information.
3397f9df
EW
305
306 exit $exit;
307}
308
551ce28f 309sub version {
7d60ab2c 310 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
311 exit 0;
312}
313
8164b652
EW
314sub do_git_init_db {
315 unless (-d $ENV{GIT_DIR}) {
316 my @init_db = ('init');
317 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
318 if (defined $_shared) {
319 if ($_shared =~ /[a-z]/) {
320 push @init_db, "--shared=$_shared";
321 } else {
322 push @init_db, "--shared";
323 }
324 }
8164b652 325 command_noisy(@init_db);
ffe256f9 326 $_repository = Git->repository(Repository => ".git");
8164b652 327 }
0dfaf0a4
EW
328 my $set;
329 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
330 foreach my $i (keys %icv) {
331 die "'$set' and '$i' cannot both be set\n" if $set;
332 next unless defined $icv{$i};
333 command_noisy('config', "$pfx.$i", $icv{$i});
334 $set = $i;
335 }
8164b652
EW
336}
337
dadc6d2a
EW
338sub init_subdir {
339 my $repo_path = shift or return;
340 mkpath([$repo_path]) unless -d $repo_path;
341 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 342 $ENV{GIT_DIR} = '.git';
ffe256f9 343 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
dadc6d2a
EW
344}
345
0425ea90
EW
346sub cmd_clone {
347 my ($url, $path) = @_;
348 if (!defined $path &&
8f728fb9 349 (defined $_trunk || defined $_branches || defined $_tags ||
350 defined $_stdlayout) &&
0425ea90
EW
351 $url !~ m#^[a-z\+]+://#) {
352 $path = $url;
353 }
0425ea90 354 $path = basename($url) if !defined $path || !length $path;
f30603fc 355 cmd_init($url, $path);
0425ea90
EW
356 Git::SVN::fetch_all($Git::SVN::default_repo_id);
357}
358
d2866f9e 359sub cmd_init {
8f728fb9 360 if (defined $_stdlayout) {
361 $_trunk = 'trunk' if (!defined $_trunk);
362 $_tags = 'tags' if (!defined $_tags);
363 $_branches = 'branches' if (!defined $_branches);
364 }
dadc6d2a
EW
365 if (defined $_trunk || defined $_branches || defined $_tags) {
366 return cmd_multi_init(@_);
03e0ea87 367 }
dadc6d2a
EW
368 my $url = shift or die "SVN repository location required ",
369 "as a command-line argument\n";
370 init_subdir(@_);
8164b652 371 do_git_init_db();
03e0ea87 372
706587fc 373 Git::SVN->init($url);
3397f9df
EW
374}
375
2a3240be 376sub cmd_fetch {
e98671e5
EW
377 if (grep /^\d+=./, @_) {
378 die "'<rev>=<commit>' fetch arguments are ",
379 "no longer supported.\n";
07a1c950 380 }
e98671e5
EW
381 my ($remote) = @_;
382 if (@_ > 1) {
905f8b7d 383 die "Usage: $0 fetch [--all] [svn-remote]\n";
e98671e5
EW
384 }
385 $remote ||= $Git::SVN::default_repo_id;
386 if ($_fetch_all) {
387 cmd_multi_fetch();
388 } else {
389 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 390 }
2a3240be
EW
391}
392
1ce255dc 393sub cmd_set_tree {
3397f9df
EW
394 my (@commits) = @_;
395 if ($_stdin || !@commits) {
396 print "Reading from stdin...\n";
397 @commits = ();
398 while (<STDIN>) {
1ca72aef 399 if (/\b($sha1_short)\b/o) {
3397f9df
EW
400 unshift @commits, $1;
401 }
402 }
403 }
404 my @revs;
8de010ad 405 foreach my $c (@commits) {
aef4e921 406 my @tmp = command('rev-parse',$c);
8de010ad
EW
407 if (scalar @tmp == 1) {
408 push @revs, $tmp[0];
409 } elsif (scalar @tmp > 1) {
aef4e921 410 push @revs, reverse(command('rev-list',@tmp));
8de010ad 411 } else {
207f1a75 412 fatal "Failed to rev-parse $c";
8de010ad 413 }
3397f9df 414 }
1ce255dc
EW
415 my $gs = Git::SVN->new;
416 my ($r_last, $cmt_last) = $gs->last_rev_commit;
417 $gs->fetch;
97f6987a 418 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
419 fatal "There are new revisions that were fetched ",
420 "and need to be merged (or acknowledged) ",
421 "before committing.\nlast rev: $r_last\n",
207f1a75 422 " current: $gs->{last_rev}";
a5e0cedc 423 }
1ce255dc
EW
424 $gs->set_tree($_) foreach @revs;
425 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 426 unlink $gs->{index};
a5e0cedc 427}
8f22562c 428
d7ad3bed
EW
429sub cmd_dcommit {
430 my $head = shift;
c8cfa3e4 431 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 432 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 433 . "or stash them with `git stash'.\n";
d7ad3bed 434 $head ||= 'HEAD';
a8ae2623 435 my @refs;
13c823fb 436 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
2cb61105
TR
437 unless ($gs) {
438 die "Unable to determine upstream SVN information from ",
439 "$head history.\nPerhaps the repository is empty.";
440 }
711521e2 441 $url = defined $_commit_url ? $_commit_url : $gs->full_url;
ba24e745 442 my $last_rev = $_revision if defined $_revision;
59b0c24d
MM
443 if ($url) {
444 print "Committing to $url ...\n";
445 }
733a65aa 446 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
447 if ($_no_rebase && scalar(@$linear_refs) > 1) {
448 warn "Attempting to commit more than one change while ",
449 "--no-rebase is enabled.\n",
450 "If these changes depend on each other, re-running ",
7dfa16b9 451 "without --no-rebase may be required."
751eb395 452 }
711521e2
EW
453 my $expect_url = $url;
454 Git::SVN::remove_username($expect_url);
c74d9acf
EW
455 while (1) {
456 my $d = shift @$linear_refs or last;
45bf473a
EW
457 unless (defined $last_rev) {
458 (undef, $last_rev, undef) = cmt_metadata("$d~1");
459 unless (defined $last_rev) {
d7ad3bed 460 fatal "Unable to extract revision information ",
207f1a75 461 "from commit $d~1";
45bf473a
EW
462 }
463 }
b22d4497
EW
464 if ($_dry_run) {
465 print "diff-tree $d~1 $d\n";
466 } else {
751eb395 467 my $cmt_rev;
d7ad3bed 468 my %ed_opts = ( r => $last_rev,
61395354 469 log => get_commit_entry($d)->{log},
ba24e745 470 ra => Git::SVN::Ra->new($url),
3caf320b
KA
471 config => SVN::Core::config_get_config(
472 $Git::SVN::Ra::config_dir
473 ),
61395354
EW
474 tree_a => "$d~1",
475 tree_b => $d,
476 editor_cb => sub {
477 print "Committed r$_[0]\n";
751eb395
EW
478 $cmt_rev = $_[0];
479 },
a8ae2623 480 svn_path => '');
61395354 481 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 482 print "No changes\n$d~1 == $d\n";
733a65aa 483 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 484 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 485 $parents->{$d};
d7ad3bed 486 }
751eb395 487 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 488 $last_rev = $cmt_rev;
751eb395
EW
489 next if $_no_rebase;
490
491 # we always want to rebase against the current HEAD,
492 # not any head that was passed to us
c74d9acf 493 my @diff = command('diff-tree', $d,
751eb395
EW
494 $gs->refname, '--');
495 my @finish;
496 if (@diff) {
497 @finish = rebase_cmd();
c74d9acf 498 print STDERR "W: $d and ", $gs->refname,
751eb395 499 " differ, using @finish:\n",
c74d9acf 500 join("\n", @diff), "\n";
751eb395
EW
501 } else {
502 print "No changes between current HEAD and ",
503 $gs->refname,
504 "\nResetting to the latest ",
505 $gs->refname, "\n";
506 @finish = qw/reset --mixed/;
507 }
508 command_noisy(@finish, $gs->refname);
c74d9acf
EW
509 if (@diff) {
510 @refs = ();
511 my ($url_, $rev_, $uuid_, $gs_) =
512 working_head_info($head, \@refs);
513 my ($linear_refs_, $parents_) =
514 linearize_history($gs_, \@refs);
515 if (scalar(@$linear_refs) !=
516 scalar(@$linear_refs_)) {
517 fatal "# of revisions changed ",
518 "\nbefore:\n",
519 join("\n", @$linear_refs),
520 "\n\nafter:\n",
521 join("\n", @$linear_refs_), "\n",
522 'If you are attempting to commit ',
523 "merges, try running:\n\t",
524 'git rebase --interactive',
525 '--preserve-merges ',
526 $gs->refname,
527 "\nBefore dcommitting";
528 }
711521e2 529 if ($url_ ne $expect_url) {
c74d9acf 530 fatal "URL mismatch after rebase: ",
711521e2 531 "$url_ != $expect_url";
c74d9acf
EW
532 }
533 if ($uuid_ ne $uuid) {
534 fatal "uuid mismatch after rebase: ",
535 "$uuid_ != $uuid";
536 }
537 # remap parents
538 my (%p, @l, $i);
539 for ($i = 0; $i < scalar @$linear_refs; $i++) {
540 my $new = $linear_refs_->[$i] or next;
541 $p{$new} =
542 $parents->{$linear_refs->[$i]};
543 push @l, $new;
544 }
545 $parents = \%p;
546 $linear_refs = \@l;
547 }
b22d4497
EW
548 }
549 }
3157dd9e 550 unlink $gs->{index};
b22d4497
EW
551}
552
5de70efb
FR
553sub cmd_branch {
554 my ($branch_name, $head) = @_;
555
556 unless (defined $branch_name && length $branch_name) {
557 die(($_tag ? "tag" : "branch") . " name required\n");
558 }
559 $head ||= 'HEAD';
560
561 my ($src, $rev, undef, $gs) = working_head_info($head);
562
a0fbc87c 563 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
5de70efb
FR
564 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
565 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
566 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
567
568 my $ctx = SVN::Client->new(
569 auth => Git::SVN::Ra::_auth_providers(),
570 log_msg => sub {
571 ${ $_[0] } = defined $_message
572 ? $_message
573 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
574 . $branch_name;
575 },
576 );
577
578 eval {
579 $ctx->ls($dst, 'HEAD', 0);
580 } and die "branch ${branch_name} already exists\n";
581
582 print "Copying ${src} at r${rev} to ${dst}...\n";
583 $ctx->copy($src, $rev, $dst)
584 unless $_dry_run;
585
586 $gs->fetch_all;
587}
588
26e60160 589sub cmd_find_rev {
ea14e6c5
MAL
590 my $revision_or_hash = shift or die "SVN or git revision required ",
591 "as a command-line argument\n";
26e60160
AR
592 my $result;
593 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
594 my $head = shift;
595 $head ||= 'HEAD';
596 my @refs;
63c56022 597 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
b3cb7e45
AR
598 unless ($gs) {
599 die "Unable to determine upstream SVN information from ",
600 "$head history\n";
26e60160 601 }
b3cb7e45 602 my $desired_revision = substr($revision_or_hash, 1);
63c56022 603 $result = $gs->rev_map_get($desired_revision, $uuid);
26e60160
AR
604 } else {
605 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
606 $result = $rev;
607 }
608 print "$result\n" if $result;
609}
610
905f8b7d
EW
611sub cmd_rebase {
612 command_noisy(qw/update-index --refresh/);
13c823fb
EW
613 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
614 unless ($gs) {
905f8b7d
EW
615 die "Unable to determine upstream SVN information from ",
616 "working tree history\n";
617 }
7d45e146
SF
618 if ($_dry_run) {
619 print "Remote Branch: " . $gs->refname . "\n";
620 print "SVN URL: " . $url . "\n";
621 return;
622 }
905f8b7d
EW
623 if (command(qw/diff-index HEAD --/)) {
624 print STDERR "Cannot rebase with uncommited changes:\n";
625 command_noisy('status');
626 exit 1;
627 }
dee41f3e 628 unless ($_local) {
cec0d5a3
SG
629 # rebase will checkout for us, so no need to do it explicitly
630 $_no_checkout = 'true';
dee41f3e
EW
631 $_fetch_all ? $gs->fetch_all : $gs->fetch;
632 }
905f8b7d
EW
633 command_noisy(rebase_cmd(), $gs->refname);
634}
635
5969cbe1 636sub cmd_show_ignore {
13c823fb
EW
637 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
638 $gs ||= Git::SVN->new;
5969cbe1 639 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
01bdab84
BS
640 $gs->prop_walk($gs->{path}, $r, sub {
641 my ($gs, $path, $props) = @_;
642 print STDOUT "\n# $path\n";
643 my $s = $props->{'svn:ignore'} or return;
644 $s =~ s/[\r\n]+/\n/g;
645 chomp $s;
646 $s =~ s#^#$path#gm;
647 print STDOUT "$s\n";
648 });
a5e0cedc
EW
649}
650
2d879792
VK
651sub cmd_show_externals {
652 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
653 $gs ||= Git::SVN->new;
654 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
655 $gs->prop_walk($gs->{path}, $r, sub {
656 my ($gs, $path, $props) = @_;
657 print STDOUT "\n# $path\n";
658 my $s = $props->{'svn:externals'} or return;
659 $s =~ s/[\r\n]+/\n/g;
660 chomp $s;
661 $s =~ s#^#$path#gm;
662 print STDOUT "$s\n";
663 });
664}
665
d05ddec5
BS
666sub cmd_create_ignore {
667 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
668 $gs ||= Git::SVN->new;
669 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
670 $gs->prop_walk($gs->{path}, $r, sub {
671 my ($gs, $path, $props) = @_;
672 # $path is of the form /path/to/dir/
7d9fd459
BG
673 $path = '.' . $path;
674 # SVN can have attributes on empty directories,
675 # which git won't track
676 mkpath([$path]) unless -d $path;
677 my $ignore = $path . '.gitignore';
d05ddec5
BS
678 my $s = $props->{'svn:ignore'} or return;
679 open(GITIGNORE, '>', $ignore)
207f1a75 680 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5
BS
681 $s =~ s/[\r\n]+/\n/g;
682 chomp $s;
683 # Prefix all patterns so that the ignore doesn't apply
684 # to sub-directories.
685 $s =~ s#^#/#gm;
686 print GITIGNORE "$s\n";
687 close(GITIGNORE)
207f1a75 688 or fatal("Failed to close `$ignore': $!");
c4c66b26 689 command_noisy('add', '-f', $ignore);
d05ddec5
BS
690 });
691}
692
b2b3ada7
DK
693sub canonicalize_path {
694 my ($path) = @_;
e6fefa92
DK
695 my $dot_slash_added = 0;
696 if (substr($path, 0, 1) ne "/") {
697 $path = "./" . $path;
698 $dot_slash_added = 1;
699 }
b2b3ada7
DK
700 # File::Spec->canonpath doesn't collapse x/../y into y (for a
701 # good reason), so let's do this manually.
702 $path =~ s#/+#/#g;
703 $path =~ s#/\.(?:/|$)#/#g;
704 $path =~ s#/[^/]+/\.\.##g;
705 $path =~ s#/$##g;
e6fefa92 706 $path =~ s#^\./## if $dot_slash_added;
2fe403e7
GP
707 $path =~ s#^/##;
708 $path =~ s#^\.$##;
b2b3ada7
DK
709 return $path;
710}
711
15153451
BS
712# get_svnprops(PATH)
713# ------------------
51e057cf 714# Helper for cmd_propget and cmd_proplist below.
15153451
BS
715sub get_svnprops {
716 my $path = shift;
717 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
718 $gs ||= Git::SVN->new;
719
720 # prefix THE PATH by the sub-directory from which the user
721 # invoked us.
722 $path = $cmd_dir_prefix . $path;
207f1a75 723 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
724 my $is_dir = -d $path ? 1 : 0;
725 $path = $gs->{path} . '/' . $path;
726
727 # canonicalize the path (otherwise libsvn will abort or fail to
728 # find the file)
b2b3ada7 729 $path = canonicalize_path($path);
15153451
BS
730
731 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
732 my $props;
733 if ($is_dir) {
734 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
735 }
736 else {
737 (undef, $props) = $gs->ra->get_file($path, $r, undef);
738 }
739 return $props;
740}
741
742# cmd_propget (PROP, PATH)
743# ------------------------
744# Print the SVN property PROP for PATH.
745sub cmd_propget {
746 my ($prop, $path) = @_;
747 $path = '.' if not defined $path;
748 usage(1) if not defined $prop;
749 my $props = get_svnprops($path);
750 if (not defined $props->{$prop}) {
207f1a75 751 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
752 }
753 print $props->{$prop} . "\n";
754}
755
51e057cf
BS
756# cmd_proplist (PATH)
757# -------------------
758# Print the list of SVN properties for PATH.
759sub cmd_proplist {
760 my $path = shift;
761 $path = '.' if not defined $path;
762 my $props = get_svnprops($path);
763 print "Properties on '$path':\n";
764 foreach (sort keys %{$props}) {
765 print " $_\n";
766 }
767}
768
8164b652 769sub cmd_multi_init {
9d55b41a 770 my $url = shift;
98327e58
EW
771 unless (defined $_trunk || defined $_branches || defined $_tags) {
772 usage(1);
9d55b41a 773 }
dc431666
EW
774
775 # there are currently some bugs that prevent multi-init/multi-fetch
776 # setups from working well without this.
777 $Git::SVN::_minimize_url = 1;
778
8164b652 779 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
780 if (defined $url) {
781 $url =~ s#/+$##;
782 init_subdir(@_);
783 }
f30603fc 784 do_git_init_db();
98327e58 785 if (defined $_trunk) {
706587fc
EW
786 my $trunk_ref = $_prefix . 'trunk';
787 # try both old-style and new-style lookups:
788 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 789 unless ($gs_trunk) {
706587fc
EW
790 my ($trunk_url, $trunk_path) =
791 complete_svn_url($url, $_trunk);
792 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
793 undef, $trunk_ref);
98327e58 794 }
c35b96e7 795 }
706587fc 796 return unless defined $_branches || defined $_tags;
e7db67e6
EW
797 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
798 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
799 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
800}
801
1c8443b0 802sub cmd_multi_fetch {
0af9c9f9
EW
803 my $remotes = Git::SVN::read_all_remotes();
804 foreach my $repo_id (sort keys %$remotes) {
db03cd24 805 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
806 Git::SVN::fetch_all($repo_id, $remotes);
807 }
9d55b41a 808 }
9d55b41a
EW
809}
810
44320b9e
EW
811# this command is special because it requires no metadata
812sub cmd_commit_diff {
813 my ($ta, $tb, $url) = @_;
814 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 815 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 816 fatal($usage) if (!defined $ta || !defined $tb);
d72ab8c8 817 my $svn_path = '';
44320b9e
EW
818 if (!defined $url) {
819 my $gs = eval { Git::SVN->new };
820 if (!$gs) {
821 fatal("Needed URL or usable git-svn --id in ",
822 "the command-line\n", $usage);
823 }
824 $url = $gs->{url};
d3a840dc 825 $svn_path = $gs->{path};
44320b9e
EW
826 }
827 unless (defined $_revision) {
828 fatal("-r|--revision is a required argument\n", $usage);
829 }
830 if (defined $_message && defined $_file) {
831 fatal("Both --message/-m and --file/-F specified ",
832 "for the commit message.\n",
207f1a75 833 "I have no idea what you mean");
44320b9e
EW
834 }
835 if (defined $_file) {
836 $_message = file_to_s($_file);
837 } else {
838 $_message ||= get_commit_entry($tb)->{log};
839 }
840 my $ra ||= Git::SVN::Ra->new($url);
841 my $r = $_revision;
842 if ($r eq 'HEAD') {
843 $r = $ra->get_latest_revnum;
844 } elsif ($r !~ /^\d+$/) {
845 die "revision argument: $r not understood by git-svn\n";
846 }
61395354
EW
847 my %ed_opts = ( r => $r,
848 log => $_message,
849 ra => $ra,
850 tree_a => $ta,
851 tree_b => $tb,
852 editor_cb => sub { print "Committed r$_[0]\n" },
853 svn_path => $svn_path );
854 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
855 print "No changes\n$ta == $tb\n";
856 }
44320b9e
EW
857}
858
05427b91
TR
859sub escape_uri_only {
860 my ($uri) = @_;
861 my @tmp;
862 foreach (split m{/}, $uri) {
6a004d3f 863 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
05427b91
TR
864 push @tmp, $_;
865 }
866 join('/', @tmp);
867}
868
869sub escape_url {
870 my ($url) = @_;
871 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
872 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
873 $url = "$scheme://$domain$uri";
874 }
875 $url;
876}
877
e6fefa92 878sub cmd_info {
bd2d4f96 879 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
edde9112 880 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
bd2d4f96 881 if (exists $_[1]) {
e6fefa92
DK
882 die "Too many arguments specified\n";
883 }
884
885 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
886
887 if (!$file_type && !$diff_status) {
2cf3e3ac
TR
888 print STDERR "svn: '$path' is not under version control\n";
889 exit 1;
e6fefa92
DK
890 }
891
892 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
893 unless ($gs) {
894 die "Unable to determine upstream SVN information from ",
895 "working tree history\n";
896 }
bd2d4f96
EW
897
898 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
899 $path = "." if $path eq "";
900
edde9112 901 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
e6fefa92 902
8b014d71 903 if ($_url) {
05427b91 904 print escape_url($full_url), "\n";
8b014d71
DK
905 return;
906 }
907
e6fefa92
DK
908 my $result = "Path: $path\n";
909 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
05427b91 910 $result .= "URL: " . escape_url($full_url) . "\n";
e6fefa92 911
a5460eb7
EW
912 eval {
913 my $repos_root = $gs->repos_root;
914 Git::SVN::remove_username($repos_root);
05427b91 915 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
a5460eb7
EW
916 };
917 if ($@) {
918 $result .= "Repository Root: (offline)\n";
919 }
22ba47f5
MK
920 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
921 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
e6fefa92
DK
922 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
923
924 $result .= "Node Kind: " .
925 ($file_type eq "dir" ? "directory" : "file") . "\n";
926
927 my $schedule = $diff_status eq "A"
928 ? "add"
929 : ($diff_status eq "D" ? "delete" : "normal");
930 $result .= "Schedule: $schedule\n";
931
932 if ($diff_status eq "A") {
933 print $result, "\n";
934 return;
935 }
936
937 my ($lc_author, $lc_rev, $lc_date_utc);
edde9112 938 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
e6fefa92
DK
939 my $log = command_output_pipe(@args);
940 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
941 while (<$log>) {
942 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
943 $lc_author = $1;
944 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
945 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
946 (undef, $lc_rev, undef) = ::extract_metadata($1);
947 }
948 }
949 close $log;
950
951 Git::SVN::Log::set_local_timezone();
952
953 $result .= "Last Changed Author: $lc_author\n";
954 $result .= "Last Changed Rev: $lc_rev\n";
955 $result .= "Last Changed Date: " .
956 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
957
958 if ($file_type ne "dir") {
959 my $text_last_updated_date =
960 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
961 $result .=
962 "Text Last Updated: " .
963 Git::SVN::Log::format_svn_date($text_last_updated_date) .
964 "\n";
965 my $checksum;
966 if ($diff_status eq "D") {
967 my ($fh, $ctx) =
968 command_output_pipe(qw(cat-file blob), "HEAD:$path");
969 if ($file_type eq "link") {
970 my $file_name = <$fh>;
8d7c4fad 971 $checksum = md5sum("link $file_name");
e6fefa92 972 } else {
8d7c4fad 973 $checksum = md5sum($fh);
e6fefa92
DK
974 }
975 command_close_pipe($fh, $ctx);
976 } elsif ($file_type eq "link") {
977 my $file_name =
978 command(qw(cat-file blob), "HEAD:$path");
979 $checksum =
8d7c4fad 980 md5sum("link " . $file_name);
e6fefa92
DK
981 } else {
982 open FILE, "<", $path or die $!;
8d7c4fad 983 $checksum = md5sum(\*FILE);
e6fefa92
DK
984 close FILE or die $!;
985 }
986 $result .= "Checksum: " . $checksum . "\n";
987 }
988
989 print $result, "\n";
990}
991
3397f9df
EW
992########################### utility functions #########################
993
905f8b7d
EW
994sub rebase_cmd {
995 my @cmd = qw/rebase/;
996 push @cmd, '-v' if $_verbose;
997 push @cmd, qw/--merge/ if $_merge;
998 push @cmd, "--strategy=$_strategy" if $_strategy;
999 @cmd;
1000}
1001
1e889ef3
EW
1002sub post_fetch_checkout {
1003 return if $_no_checkout;
1004 my $gs = $Git::SVN::_head or return;
1005 return if verify_ref('refs/heads/master^0');
1006
1007 my $valid_head = verify_ref('HEAD^0');
1008 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1009 return if ($valid_head || !verify_ref('HEAD^0'));
1010
1011 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1012 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1013 return if -f $index;
1014
7ae3df8c 1015 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
1016 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1017 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1018 print STDERR "Checked out HEAD:\n ",
1019 $gs->full_url, " r", $gs->last_rev, "\n";
1020}
1021
98327e58
EW
1022sub complete_svn_url {
1023 my ($url, $path) = @_;
1024 $path =~ s#/+$##;
98327e58 1025 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
1026 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1027 fatal("E: '$path' is not a complete URL ",
207f1a75 1028 "and a separate URL is not specified");
98327e58 1029 }
706587fc 1030 return ($url, $path);
98327e58 1031 }
706587fc 1032 return ($path, '');
98327e58
EW
1033}
1034
9d55b41a 1035sub complete_url_ls_init {
706587fc
EW
1036 my ($ra, $repo_path, $switch, $pfx) = @_;
1037 unless ($repo_path) {
9d55b41a
EW
1038 print STDERR "W: $switch not specified\n";
1039 return;
1040 }
706587fc
EW
1041 $repo_path =~ s#/+$##;
1042 if ($repo_path =~ m#^[a-z\+]+://#) {
1043 $ra = Git::SVN::Ra->new($repo_path);
1044 $repo_path = '';
e7db67e6 1045 } else {
706587fc 1046 $repo_path =~ s#^/+##;
e7db67e6 1047 unless ($ra) {
706587fc 1048 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 1049 "and a separate URL is not specified");
8164b652 1050 }
e7db67e6 1051 }
706587fc 1052 my $url = $ra->{url};
b4d57e5e
EW
1053 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1054 my $k = "svn-remote.$gs->{repo_id}.url";
1055 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1056 if ($orig_url && ($orig_url ne $gs->{url})) {
1057 die "$k already set: $orig_url\n",
1058 "wanted to set to: $gs->{url}\n";
88cf4107 1059 }
b4d57e5e 1060 command_oneline('config', $k, $gs->{url}) unless $orig_url;
ed0b9d43 1061 my $remote_path = "$ra->{svn_path}/$repo_path";
b4d57e5e
EW
1062 $remote_path =~ s#/+#/#g;
1063 $remote_path =~ s#^/##g;
ed0b9d43 1064 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
1065 my ($n) = ($switch =~ /^--(\w+)/);
1066 if (length $pfx && $pfx !~ m#/$#) {
1067 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 1068 }
570d35c2
MG
1069 command_noisy('config',
1070 "svn-remote.$gs->{repo_id}.$n",
1071 "$remote_path:refs/remotes/$pfx*" .
1072 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
9d55b41a
EW
1073}
1074
aef4e921
EW
1075sub verify_ref {
1076 my ($ref) = @_;
2c5c1d53
EW
1077 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1078 { STDERR => 0 }); };
aef4e921
EW
1079}
1080
a5e0cedc 1081sub get_tree_from_treeish {
cf52b8f0 1082 my ($treeish) = @_;
44320b9e 1083 # $treeish can be a symbolic ref, too:
aef4e921 1084 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
1085 my $expected;
1086 while ($type eq 'tag') {
aef4e921 1087 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
1088 }
1089 if ($type eq 'commit') {
aef4e921
EW
1090 $expected = (grep /^tree /, command(qw/cat-file commit/,
1091 $treeish))[0];
44320b9e 1092 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
1093 die "Unable to get tree from $treeish\n" unless $expected;
1094 } elsif ($type eq 'tree') {
1095 $expected = $treeish;
1096 } else {
1097 die "$treeish is a $type, expected tree, tag or commit\n";
1098 }
a5e0cedc
EW
1099 return $expected;
1100}
1101
44320b9e
EW
1102sub get_commit_entry {
1103 my ($treeish) = shift;
1104 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1105 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1106 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1107 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1108
44320b9e 1109 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1110 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1111 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1112 $type, $treeish);
3397f9df 1113 my $in_msg = 0;
6aa9ba14
AP
1114 my $author;
1115 my $saw_from = 0;
328eb9b3 1116 my $msgbuf = "";
3397f9df
EW
1117 while (<$msg_fh>) {
1118 if (!$in_msg) {
1119 $in_msg = 1 if (/^\s*$/);
6aa9ba14 1120 $author = $1 if (/^author (.*>)/);
df746c5a 1121 } elsif (/^git-svn-id: /) {
44320b9e
EW
1122 # skip this for now, we regenerate the
1123 # correct one on re-fetch anyways
1124 # TODO: set *:merge properties or like...
3397f9df 1125 } else {
6aa9ba14
AP
1126 if (/^From:/ || /^Signed-off-by:/) {
1127 $saw_from = 1;
1128 }
328eb9b3 1129 $msgbuf .= $_;
3397f9df
EW
1130 }
1131 }
328eb9b3 1132 $msgbuf =~ s/\s+$//s;
6aa9ba14
AP
1133 if ($Git::SVN::_add_author_from && defined($author)
1134 && !$saw_from) {
328eb9b3 1135 $msgbuf .= "\n\nFrom: $author";
6aa9ba14 1136 }
328eb9b3 1137 print $log_fh $msgbuf or croak $!;
aef4e921 1138 command_close_pipe($msg_fh, $ctx);
3397f9df 1139 }
44320b9e 1140 close $log_fh or croak $!;
3397f9df
EW
1141
1142 if ($_edit || ($type eq 'tree')) {
1143 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
1144 # TODO: strip out spaces, comments, like git-commit.sh
1145 system($editor, $commit_editmsg);
3397f9df 1146 }
44320b9e 1147 rename $commit_editmsg, $commit_msg or croak $!;
16fc08e2
EW
1148 {
1149 # SVN requires messages to be UTF-8 when entering the repo
1150 local $/;
1151 open $log_fh, '<', $commit_msg or croak $!;
1152 binmode $log_fh;
1153 chomp($log_entry{log} = <$log_fh>);
1154
1155 if (my $enc = Git::config('i18n.commitencoding')) {
1156 require Encode;
1157 Encode::from_to($log_entry{log}, $enc, 'UTF-8');
1158 }
1159 close $log_fh or croak $!;
1160 }
44320b9e
EW
1161 unlink $commit_msg;
1162 \%log_entry;
a5e0cedc
EW
1163}
1164
3397f9df
EW
1165sub s_to_file {
1166 my ($str, $file, $mode) = @_;
1167 open my $fd,'>',$file or croak $!;
1168 print $fd $str,"\n" or croak $!;
1169 close $fd or croak $!;
1170 chmod ($mode &~ umask, $file) if (defined $mode);
1171}
1172
1173sub file_to_s {
1174 my $file = shift;
1175 open my $fd,'<',$file or croak "$!: file: $file\n";
1176 local $/;
1177 my $ret = <$fd>;
1178 close $fd or croak $!;
1179 $ret =~ s/\s*$//s;
1180 return $ret;
1181}
1182
eeb0abe0
EW
1183# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1184sub load_authors {
1185 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1186 my $log = $cmd eq 'log';
eeb0abe0
EW
1187 while (<$authors>) {
1188 chomp;
575d025c 1189 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1190 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1191 if ($log) {
1192 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1193 } else {
1194 $users{$user} = [$name, $email];
1195 }
79bb8d88
EW
1196 }
1197 close $authors or croak $!;
1198}
1199
e0d10e1c 1200# convert GetOpt::Long specs for use by git-config
b8c92cad 1201sub read_repo_config {
706587fc 1202 return unless -d $ENV{GIT_DIR};
b8c92cad 1203 my $opts = shift;
97ae0911 1204 my @config_only;
b8c92cad 1205 foreach my $o (keys %$opts) {
97ae0911
EW
1206 # if we have mixedCase and a long option-only, then
1207 # it's a config-only variable that we don't need for
1208 # the command-line.
1209 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1210 my $v = $opts->{$o};
97ae0911 1211 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1212 $key =~ s/-//g;
225f1d0c 1213 my $arg = 'git config';
b8c92cad
EW
1214 $arg .= ' --int' if ($o =~ /[:=]i$/);
1215 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1216 if (ref $v eq 'ARRAY') {
1217 chomp(my @tmp = `$arg --get-all svn.$key`);
1218 @$v = @tmp if @tmp;
1219 } else {
1220 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1221 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1222 $$v = $tmp;
1223 }
1224 }
1225 }
97ae0911 1226 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1227}
1228
79bb8d88 1229sub extract_metadata {
c1927a85 1230 my $id = shift or return (undef, undef, undef);
3dfab993 1231 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
79bb8d88 1232 \s([a-f\d\-]+)$/x);
e70dc780 1233 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1234 # some of the original repositories I made had
82e5a82f 1235 # identifiers like this:
3dfab993 1236 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
79bb8d88
EW
1237 }
1238 return ($url, $rev, $uuid);
1239}
1240
c1927a85
EW
1241sub cmt_metadata {
1242 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1243 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1244}
1245
905f8b7d
EW
1246sub working_head_info {
1247 my ($head, $refs) = @_;
b6309ac2 1248 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
05b4df31 1249 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1250 my $hash;
40cb8f8f 1251 my %max;
3dfab993
SV
1252 while (<$fh>) {
1253 if ( m{^commit ($::sha1)$} ) {
1254 unshift @$refs, $hash if $hash and $refs;
1255 $hash = $1;
1256 next;
1257 }
1258 next unless s{^\s*(git-svn-id:)}{$1};
1259 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1260 if (defined $url && defined $rev) {
40cb8f8f 1261 next if $max{$url} and $max{$url} < $rev;
13c823fb 1262 if (my $gs = Git::SVN->find_by_url($url)) {
63c56022 1263 my $c = $gs->rev_map_get($rev, $uuid);
b03c7a63 1264 if ($c && $c eq $hash) {
13c823fb
EW
1265 close $fh; # break the pipe
1266 return ($url, $rev, $uuid, $gs);
40cb8f8f 1267 } else {
060610c5 1268 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1269 }
1270 }
1271 }
905f8b7d 1272 }
13c823fb
EW
1273 command_close_pipe($fh, $ctx);
1274 (undef, undef, undef, undef);
905f8b7d
EW
1275}
1276
733a65aa
EW
1277sub read_commit_parents {
1278 my ($parents, $c) = @_;
7b02b85a
EW
1279 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1280 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1281 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1282}
1283
1284sub linearize_history {
1285 my ($gs, $refs) = @_;
1286 my %parents;
1287 foreach my $c (@$refs) {
1288 read_commit_parents(\%parents, $c);
1289 }
1290
1291 my @linear_refs;
1292 my %skip = ();
1293 my $last_svn_commit = $gs->last_commit;
1294 foreach my $c (reverse @$refs) {
1295 next if $c eq $last_svn_commit;
1296 last if $skip{$c};
1297
1298 unshift @linear_refs, $c;
1299 $skip{$c} = 1;
1300
1301 # we only want the first parent to diff against for linear
1302 # history, we save the rest to inject when we finalize the
1303 # svn commit
1304 my $fp_a = verify_ref("$c~1");
1305 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1306 if (!$fp_a || !$fp_b) {
1307 die "Commit $c\n",
1308 "has no parent commit, and therefore ",
1309 "nothing to diff against.\n",
1310 "You should be working from a repository ",
1311 "originally created by git-svn\n";
1312 }
1313 if ($fp_a ne $fp_b) {
1314 die "$c~1 = $fp_a, however parsing commit $c ",
1315 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1316 }
1317
1318 foreach my $p (@{$parents{$c}}) {
1319 $skip{$p} = 1;
1320 }
1321 }
1322 (\@linear_refs, \%parents);
1323}
1324
e6fefa92
DK
1325sub find_file_type_and_diff_status {
1326 my ($path) = @_;
107cee50 1327 return ('dir', '') if $path eq '';
e6fefa92
DK
1328
1329 my $diff_output =
1330 command_oneline(qw(diff --cached --name-status --), $path) || "";
1331 my $diff_status = (split(' ', $diff_output))[0] || "";
1332
1333 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1334
1335 return (undef, undef) if !$diff_status && !$ls_tree;
1336
1337 if ($diff_status eq "A") {
1338 return ("link", $diff_status) if -l $path;
1339 return ("dir", $diff_status) if -d $path;
1340 return ("file", $diff_status);
1341 }
1342
1343 my $mode = (split(' ', $ls_tree))[0] || "";
1344
1345 return ("link", $diff_status) if $mode eq "120000";
1346 return ("dir", $diff_status) if $mode eq "040000";
1347 return ("file", $diff_status);
1348}
1349
b2b3ada7
DK
1350sub md5sum {
1351 my $arg = shift;
1352 my $ref = ref $arg;
1353 my $md5 = Digest::MD5->new();
0b19138b 1354 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
b2b3ada7
DK
1355 $md5->addfile($arg) or croak $!;
1356 } elsif ($ref eq 'SCALAR') {
1357 $md5->add($$arg) or croak $!;
1358 } elsif (!$ref) {
1359 $md5->add($arg) or croak $!;
1360 } else {
1361 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1362 }
1363 return $md5->hexdigest();
1364}
1365
9b981fc6
EW
1366package Git::SVN;
1367use strict;
1368use warnings;
060610c5
EW
1369use Fcntl qw/:DEFAULT :seek/;
1370use constant rev_map_fmt => 'NH40';
ecc712dd 1371use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 1372 $_repack $_repack_flags $_use_svm_props $_head
70ae04e4 1373 $_use_svnsync_props $no_reuse_existing $_minimize_url
e82f0d73 1374 $_use_log_author $_add_author_from $_localtime/;
9b981fc6
EW
1375use Carp qw/croak/;
1376use File::Path qw/mkpath/;
373274f9 1377use File::Copy qw/copy/;
9b981fc6
EW
1378use IPC::Open3;
1379
94bc914c
KW
1380my ($_gc_nr, $_gc_period);
1381
9b981fc6
EW
1382# properties that we do not log:
1383my %SKIP_PROP;
1384BEGIN {
1385 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1386 svn:special svn:executable
1387 svn:entry:committed-rev
1388 svn:entry:last-author
1389 svn:entry:uuid
1390 svn:entry:committed-date/;
91b03282
EW
1391
1392 # some options are read globally, but can be overridden locally
1393 # per [svn-remote "..."] section. Command-line options will *NOT*
1394 # override options set in an [svn-remote "..."] section
c5f71ad0
SV
1395 no strict 'refs';
1396 for my $option (qw/follow_parent no_metadata use_svm_props
1397 use_svnsync_props/) {
1398 my $key = $option;
91b03282 1399 $key =~ tr/_//d;
c5f71ad0
SV
1400 my $prop = "-$option";
1401 *$option = sub {
1402 my ($self) = @_;
1403 return $self->{$prop} if exists $self->{$prop};
1404 my $k = "svn-remote.$self->{repo_id}.$key";
1405 eval { command_oneline(qw/config --get/, $k) };
1406 if ($@) {
1407 $self->{$prop} = ${"Git::SVN::_$option"};
91b03282 1408 } else {
c5f71ad0
SV
1409 my $v = command_oneline(qw/config --bool/,$k);
1410 $self->{$prop} = $v eq 'false' ? 0 : 1;
91b03282 1411 }
c5f71ad0
SV
1412 return $self->{$prop};
1413 }
91b03282 1414 }
9b981fc6
EW
1415}
1416
0b19138b 1417
321b1842
EW
1418my (%LOCKFILES, %INDEX_FILES);
1419END {
1420 unlink keys %LOCKFILES if %LOCKFILES;
1421 unlink keys %INDEX_FILES if %INDEX_FILES;
1422}
373274f9 1423
4bb9ed04
EW
1424sub resolve_local_globs {
1425 my ($url, $fetch, $glob_spec) = @_;
1426 return unless defined $glob_spec;
1427 my $ref = $glob_spec->{ref};
1428 my $path = $glob_spec->{path};
1429 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1430 next unless m#^refs/remotes/$ref->{regex}$#;
1431 my $p = $1;
bf655fd7
RE
1432 my $pathname = desanitize_refname($path->full_path($p));
1433 my $refname = desanitize_refname($ref->full_path($p));
4bb9ed04
EW
1434 if (my $existing = $fetch->{$pathname}) {
1435 if ($existing ne $refname) {
1436 die "Refspec conflict:\n",
1437 "existing: refs/remotes/$existing\n",
1438 " globbed: refs/remotes/$refname\n";
1439 }
1440 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 1441 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
1442 "refs/remotes/$refname: '$url' not found in '$u'\n";
1443 if ($pathname ne $u) {
1444 warn "W: Refspec glob conflict ",
1445 "(ref: refs/remotes/$refname):\n",
1446 "expected path: $pathname\n",
1447 " real path: $u\n",
1448 "Continuing ahead with $u\n";
1449 next;
1450 }
1451 } else {
4bb9ed04
EW
1452 $fetch->{$pathname} = $refname;
1453 }
1454 }
1455}
1456
e98671e5
EW
1457sub parse_revision_argument {
1458 my ($base, $head) = @_;
1459 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1460 return ($base, $head);
1461 }
1462 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1463 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1464 return ($head, $head) if ($::_revision eq 'HEAD');
1465 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1466 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1467 die "revision argument: $::_revision not understood by git-svn\n";
1468}
1469
0af9c9f9 1470sub fetch_all {
4bb9ed04 1471 my ($repo_id, $remotes) = @_;
905f8b7d
EW
1472 if (ref $repo_id) {
1473 my $gs = $repo_id;
1474 $repo_id = undef;
1475 $repo_id = $gs->{repo_id};
1476 }
1477 $remotes ||= read_all_remotes();
7447b4bc
EW
1478 my $remote = $remotes->{$repo_id} or
1479 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 1480 my $fetch = $remote->{fetch};
7447b4bc 1481 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 1482 my (@gs, @globs);
0af9c9f9 1483 my $ra = Git::SVN::Ra->new($url);
26a62d57 1484 my $uuid = $ra->get_uuid;
0af9c9f9 1485 my $head = $ra->get_latest_revnum;
28710f74 1486 my $base = defined $fetch ? $head : 0;
e518192f
EW
1487
1488 # read the max revs for wildcard expansion (branches/*, tags/*)
1489 foreach my $t (qw/branches tags/) {
1490 defined $remote->{$t} or next;
1491 push @globs, $remote->{$t};
93f2689c
EW
1492 my $max_rev = eval { tmp_config(qw/--int --get/,
1493 "svn-remote.$repo_id.${t}-maxRev") };
1494 if (defined $max_rev && ($max_rev < $base)) {
1495 $base = $max_rev;
d6d3346b
EW
1496 } elsif (!defined $max_rev) {
1497 $base = 0;
e518192f
EW
1498 }
1499 }
1500
db03cd24
EW
1501 if ($fetch) {
1502 foreach my $p (sort keys %$fetch) {
1503 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
060610c5 1504 my $lr = $gs->rev_map_max;
db03cd24
EW
1505 if (defined $lr) {
1506 $base = $lr if ($lr < $base);
1507 }
1508 push @gs, $gs;
0af9c9f9 1509 }
0af9c9f9 1510 }
e98671e5
EW
1511
1512 ($base, $head) = parse_revision_argument($base, $head);
e518192f 1513 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
1514}
1515
47e39c55
EW
1516sub read_all_remotes {
1517 my $r = {};
63c56022
JA
1518 my $use_svm_props = eval { command_oneline(qw/config --bool
1519 svn.useSvmProps/) };
1520 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
8b8fc068 1521 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
61192165
AP
1522 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1523 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1524 die("svn-remote.$remote: remote ref '$_remote_ref' "
1525 . "must start with 'refs/remotes/'\n")
1526 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1527 my $remote_ref = $1;
46cf98ba
EW
1528 $local_ref =~ s{^/}{};
1529 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
63c56022
JA
1530 $r->{$remote}->{svm} = {} if $use_svm_props;
1531 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1532 $r->{$1}->{svm} = {};
47e39c55
EW
1533 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1534 $r->{$1}->{url} = $2;
4bb9ed04
EW
1535 } elsif (m!^(.+)\.(branches|tags)=
1536 (.*):refs/remotes/(.+)\s*$/!x) {
1537 my ($p, $g) = ($3, $4);
1538 my $rs = $r->{$1}->{$2} = {
e518192f 1539 t => $2,
93f2689c 1540 remote => $1,
4bb9ed04
EW
1541 path => Git::SVN::GlobSpec->new($p),
1542 ref => Git::SVN::GlobSpec->new($g) };
1543 if (length($rs->{ref}->{right}) != 0) {
1544 die "The '*' glob character must be the last ",
1545 "character of '$g'\n";
1546 }
47e39c55
EW
1547 }
1548 }
63c56022
JA
1549
1550 map {
1551 if (defined $r->{$_}->{svm}) {
1552 my $svm;
1553 eval {
1554 my $section = "svn-remote.$_";
1555 $svm = {
1556 source => tmp_config('--get',
1557 "$section.svm-source"),
1558 replace => tmp_config('--get',
1559 "$section.svm-replace"),
1560 }
1561 };
1562 $r->{$_}->{svm} = $svm;
1563 }
1564 } keys %$r;
1565
47e39c55
EW
1566 $r;
1567}
1568
ecc712dd 1569sub init_vars {
94bc914c 1570 $_gc_nr = $_gc_period = 1000;
af788a6e
KW
1571 if (defined $_repack || defined $_repack_flags) {
1572 warn "Repack options are obsolete; they have no effect.\n";
1573 }
ecc712dd
EW
1574}
1575
b805b44a 1576sub verify_remotes_sanity {
536c4b09 1577 return unless -d $ENV{GIT_DIR};
b805b44a
EW
1578 my %seen;
1579 foreach (command(qw/config -l/)) {
1580 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1581 if ($seen{$1}) {
1582 die "Remote ref refs/remote/$1 is tracked by",
1583 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1584 "Please resolve this ambiguity in ",
1585 "your git configuration file before ",
1586 "continuing\n";
1587 }
1588 $seen{$1} = $_;
1589 }
1590 }
1591}
1592
e6434f87
EW
1593sub find_existing_remote {
1594 my ($url, $remotes) = @_;
befc9adc 1595 return undef if $no_reuse_existing;
e6434f87
EW
1596 my $existing;
1597 foreach my $repo_id (keys %$remotes) {
1598 my $u = $remotes->{$repo_id}->{url} or next;
1599 next if $u ne $url;
1600 $existing = $repo_id;
1601 last;
1602 }
1603 $existing;
1604}
b805b44a 1605
e6434f87 1606sub init_remote_config {
d8115c51 1607 my ($self, $url, $no_write) = @_;
e6434f87
EW
1608 $url =~ s!/+$!!; # strip trailing slash
1609 my $r = read_all_remotes();
1610 my $existing = find_existing_remote($url, $r);
1611 if ($existing) {
e518192f
EW
1612 unless ($no_write) {
1613 print STDERR "Using existing ",
1614 "[svn-remote \"$existing\"]\n";
1615 }
e6434f87 1616 $self->{repo_id} = $existing;
4a1bb4c3 1617 } elsif ($_minimize_url) {
e6434f87
EW
1618 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1619 $existing = find_existing_remote($min_url, $r);
1620 if ($existing) {
e518192f
EW
1621 unless ($no_write) {
1622 print STDERR "Using existing ",
1623 "[svn-remote \"$existing\"]\n";
1624 }
e6434f87
EW
1625 $self->{repo_id} = $existing;
1626 }
1627 if ($min_url ne $url) {
e518192f
EW
1628 unless ($no_write) {
1629 print STDERR "Using higher level of URL: ",
1630 "$url => $min_url\n";
1631 }
e6434f87
EW
1632 my $old_path = $self->{path};
1633 $self->{path} = $url;
4e9f6cc7 1634 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1635 if (length $old_path) {
1636 $self->{path} .= "/$old_path";
1637 }
1638 $url = $min_url;
1639 }
1640 }
1641 my $orig_url;
1642 if (!$existing) {
b805b44a 1643 # verify that we aren't overwriting anything:
e6434f87 1644 $orig_url = eval {
706587fc 1645 command_oneline('config', '--get',
e6434f87 1646 "svn-remote.$self->{repo_id}.url")
706587fc 1647 };
b805b44a 1648 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1649 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1650 "$orig_url\nwanted to set to: $url\n";
1651 }
9b981fc6 1652 }
e6434f87
EW
1653 my ($xrepo_id, $xpath) = find_ref($self->refname);
1654 if (defined $xpath) {
1655 die "svn-remote.$xrepo_id.fetch already set to track ",
1656 "$xpath:refs/remotes/", $self->refname, "\n";
1657 }
d8115c51
EW
1658 unless ($no_write) {
1659 command_noisy('config',
1660 "svn-remote.$self->{repo_id}.url", $url);
46cf98ba 1661 $self->{path} =~ s{^/}{};
d8115c51
EW
1662 command_noisy('config', '--add',
1663 "svn-remote.$self->{repo_id}.fetch",
1664 "$self->{path}:".$self->refname);
1665 }
9b981fc6 1666 $self->{url} = $url;
e6434f87
EW
1667}
1668
a8ae2623
EW
1669sub find_by_url { # repos_root and, path are optional
1670 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1671
1a97a506 1672 return undef unless defined $full_url;
56973d20
AR
1673 remove_username($full_url);
1674 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1675 my $remotes = read_all_remotes();
1676 if (defined $full_url && defined $repos_root && !defined $path) {
1677 $path = $full_url;
1678 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1679 }
1680 foreach my $repo_id (keys %$remotes) {
1681 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1682 remove_username($u);
a8ae2623
EW
1683 next if defined $repos_root && $repos_root ne $u;
1684
1685 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1686 foreach (qw/branches tags/) {
1687 resolve_local_globs($u, $fetch,
1688 $remotes->{$repo_id}->{$_});
1689 }
1690 my $p = $path;
0bb91d9a 1691 my $rwr = rewrite_root({repo_id => $repo_id});
63c56022
JA
1692 my $svm = $remotes->{$repo_id}->{svm}
1693 if defined $remotes->{$repo_id}->{svm};
a8ae2623
EW
1694 unless (defined $p) {
1695 $p = $full_url;
0bb91d9a 1696 my $z = $u;
63c56022 1697 my $prefix = '';
0bb91d9a
JG
1698 if ($rwr) {
1699 $z = $rwr;
1b7e543a 1700 remove_username($z);
63c56022
JA
1701 } elsif (defined $svm) {
1702 $z = $svm->{source};
1703 $prefix = $svm->{replace};
1704 $prefix =~ s#^\Q$u\E(?:/|$)##;
1705 $prefix =~ s#/$##;
0bb91d9a 1706 }
63c56022 1707 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
a8ae2623
EW
1708 }
1709 foreach my $f (keys %$fetch) {
1710 next if $f ne $p;
1711 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1712 }
1713 }
1714 undef;
1715}
1716
e6434f87 1717sub init {
d8115c51 1718 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1719 my $self = _new($class, $repo_id, $ref_id, $path);
1720 if (defined $url) {
d8115c51 1721 $self->init_remote_config($url, $no_write);
e6434f87 1722 }
9b981fc6
EW
1723 $self;
1724}
1725
706587fc
EW
1726sub find_ref {
1727 my ($ref_id) = @_;
1728 foreach (command(qw/config -l/)) {
1729 next unless m!^svn-remote\.(.+)\.fetch=
1730 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1731 my ($repo_id, $path, $ref) = ($1, $2, $3);
1732 if ($ref eq $ref_id) {
1733 $path = '' if ($path =~ m#^\./?#);
1734 return ($repo_id, $path);
1735 }
1736 }
1737 (undef, undef, undef);
1738}
1739
9b981fc6 1740sub new {
706587fc
EW
1741 my ($class, $ref_id, $repo_id, $path) = @_;
1742 if (defined $ref_id && !defined $repo_id && !defined $path) {
1743 ($repo_id, $path) = find_ref($ref_id);
1744 if (!defined $repo_id) {
1745 die "Could not find a \"svn-remote.*.fetch\" key ",
1746 "in the repository configuration matching: ",
1747 "refs/remotes/$ref_id\n";
1748 }
1749 }
1750 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1751 if (!defined $self->{path} || !length $self->{path}) {
1752 my $fetch = command_oneline('config', '--get',
1753 "svn-remote.$repo_id.fetch",
1754 ":refs/remotes/$ref_id\$") or
1755 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1756 "\":refs/remotes/$ref_id\$\" in config\n";
1757 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1758 }
706587fc
EW
1759 $self->{url} = command_oneline('config', '--get',
1760 "svn-remote.$repo_id.url") or
1761 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1762 $self->rebuild;
9b981fc6
EW
1763 $self;
1764}
1765
bf655fd7
RE
1766sub refname {
1767 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1768
1769 # It cannot end with a slash /, we'll throw up on this because
1770 # SVN can't have directories with a slash in their name, either:
1771 if ($refname =~ m{/$}) {
1772 die "ref: '$refname' ends with a trailing slash, this is ",
1773 "not permitted by git nor Subversion\n";
1774 }
1775
1776 # It cannot have ASCII control character space, tilde ~, caret ^,
1777 # colon :, question-mark ?, asterisk *, space, or open bracket [
1778 # anywhere.
1779 #
1780 # Additionally, % must be escaped because it is used for escaping
1781 # and we want our escaped refname to be reversible
1782 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1783
1784 # no slash-separated component can begin with a dot .
1785 # /.* becomes /%2E*
1786 $refname =~ s{/\.}{/%2E}g;
1787
1788 # It cannot have two consecutive dots .. anywhere
1789 # .. becomes %2E%2E
1790 $refname =~ s{\.\.}{%2E%2E}g;
1791
1792 return $refname;
1793}
1794
1795sub desanitize_refname {
1796 my ($refname) = @_;
1797 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1798 return $refname;
1799}
9b981fc6 1800
26a62d57
EW
1801sub svm_uuid {
1802 my ($self) = @_;
1803 return $self->{svm}->{uuid} if $self->svm;
1804 $self->ra;
1805 unless ($self->{svm}) {
1806 die "SVM UUID not cached, and reading remotely failed\n";
1807 }
1808 $self->{svm}->{uuid};
1809}
8a49ee97 1810
26a62d57
EW
1811sub svm {
1812 my ($self) = @_;
1813 return $self->{svm} if $self->{svm};
1814 my $svm;
8a49ee97
EW
1815 # see if we have it in our config, first:
1816 eval {
26a62d57
EW
1817 my $section = "svn-remote.$self->{repo_id}";
1818 $svm = {
93f2689c
EW
1819 source => tmp_config('--get', "$section.svm-source"),
1820 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1821 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1822 }
1823 };
befc9adc
EW
1824 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1825 $self->{svm} = $svm;
1826 }
26a62d57
EW
1827 $self->{svm};
1828}
1829
1830sub _set_svm_vars {
1831 my ($self, $ra) = @_;
db03cd24
EW
1832 return $ra if $self->svm;
1833
1834 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1835 "(svm:source, svm:uuid) ",
db03cd24
EW
1836 "from the following URLs:\n" );
1837 sub read_svm_props {
befc9adc
EW
1838 my ($self, $ra, $path, $r) = @_;
1839 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1840 my $src = $props->{'svm:source'};
db03cd24 1841 my $uuid = $props->{'svm:uuid'};
befc9adc 1842 return undef if (!$src || !$uuid);
26a62d57 1843
befc9adc 1844 chomp($src, $uuid);
26a62d57 1845
db03cd24
EW
1846 $uuid =~ m{^[0-9a-f\-]{30,}$}
1847 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1848
1849 # the '!' is used to mark the repos_root!/relative/path
1850 $src =~ s{/?!/?}{/};
db03cd24 1851 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1852 # username is of no interest
8a49ee97 1853 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1854
befc9adc
EW
1855 my $replace = $ra->{url};
1856 $replace .= "/$path" if length $path;
1857
db03cd24 1858 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1859 tmp_config("$section.svm-source", $src);
1860 tmp_config("$section.svm-replace", $replace);
1861 tmp_config("$section.svm-uuid", $uuid);
1862 $self->{svm} = {
1863 source => $src,
1864 uuid => $uuid,
1865 replace => $replace
1866 };
db03cd24
EW
1867 }
1868
1869 my $r = $ra->get_latest_revnum;
1870 my $path = $self->{path};
befc9adc 1871 my %tried;
db03cd24 1872 while (length $path) {
befc9adc
EW
1873 unless ($tried{"$self->{url}/$path"}) {
1874 return $ra if $self->read_svm_props($ra, $path, $r);
1875 $tried{"$self->{url}/$path"} = 1;
db03cd24 1876 }
befc9adc 1877 $path =~ s#/?[^/]+$##;
8a49ee97 1878 }
befc9adc
EW
1879 die "Path: '$path' should be ''\n" if $path ne '';
1880 return $ra if $self->read_svm_props($ra, $path, $r);
1881 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
1882
1883 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 1884 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1885 }
1886
1887 # nope, make sure we're connected to the repository root:
1888 my $ok;
1889 my @tried_b;
1890 $path = $ra->{svn_path};
db03cd24
EW
1891 $ra = Git::SVN::Ra->new($ra->{repos_root});
1892 while (length $path) {
befc9adc
EW
1893 unless ($tried{"$ra->{url}/$path"}) {
1894 $ok = $self->read_svm_props($ra, $path, $r);
1895 last if $ok;
1896 $tried{"$ra->{url}/$path"} = 1;
1897 }
1898 $path =~ s#/?[^/]+$##;
db03cd24 1899 }
befc9adc
EW
1900 die "Path: '$path' should be ''\n" if $path ne '';
1901 $ok ||= $self->read_svm_props($ra, $path, $r);
1902 $tried{"$ra->{url}/$path"} = 1;
db03cd24 1903 if (!$ok) {
befc9adc 1904 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
1905 }
1906 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
1907}
1908
62e349d2
EW
1909sub svnsync {
1910 my ($self) = @_;
1911 return $self->{svnsync} if $self->{svnsync};
1912
1913 if ($self->no_metadata) {
1914 die "Can't have both 'noMetadata' and ",
1915 "'useSvnsyncProps' options set!\n";
1916 }
1917 if ($self->rewrite_root) {
1918 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1919 "options set!\n";
1920 }
1921
1922 my $svnsync;
1923 # see if we have it in our config, first:
1924 eval {
1925 my $section = "svn-remote.$self->{repo_id}";
98fa5b68
EW
1926
1927 my $url = tmp_config('--get', "$section.svnsync-url");
1928 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1929 die "doesn't look right - svn:sync-from-url is '$url'\n";
1930
1931 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1932 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1933 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1934
1935 $svnsync = { url => $url, uuid => $uuid }
62e349d2
EW
1936 };
1937 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1938 return $self->{svnsync} = $svnsync;
1939 }
1940
1941 my $err = "useSvnsyncProps set, but failed to read " .
1942 "svnsync property: svn:sync-from-";
1943 my $rp = $self->ra->rev_proplist(0);
1944
1945 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
98fa5b68 1946 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
62e349d2
EW
1947 die "doesn't look right - svn:sync-from-url is '$url'\n";
1948
1949 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
98fa5b68 1950 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
62e349d2
EW
1951 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1952
1953 my $section = "svn-remote.$self->{repo_id}";
1954 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1955 tmp_config('--add', "$section.svnsync-url", $url);
1956 return $self->{svnsync} = { url => $url, uuid => $uuid };
1957}
1958
26a62d57
EW
1959# this allows us to memoize our SVN::Ra UUID locally and avoid a
1960# remote lookup (useful for 'git svn log').
1961sub ra_uuid {
1962 my ($self) = @_;
1963 unless ($self->{ra_uuid}) {
1964 my $key = "svn-remote.$self->{repo_id}.uuid";
1965 my $uuid = eval { tmp_config('--get', $key) };
1966 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1967 $self->{ra_uuid} = $uuid;
1968 } else {
1969 die "ra_uuid called without URL\n" unless $self->{url};
1970 $self->{ra_uuid} = $self->ra->get_uuid;
1971 tmp_config('--add', $key, $self->{ra_uuid});
1972 }
1973 }
1974 $self->{ra_uuid};
1975}
1976
a5460eb7
EW
1977sub _set_repos_root {
1978 my ($self, $repos_root) = @_;
1979 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1980 $repos_root ||= $self->ra->{repos_root};
1981 tmp_config($k, $repos_root);
1982 $repos_root;
1983}
1984
1985sub repos_root {
1986 my ($self) = @_;
1987 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1988 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1989}
1990
9b981fc6
EW
1991sub ra {
1992 my ($self) = shift;
8a49ee97 1993 my $ra = Git::SVN::Ra->new($self->{url});
a5460eb7 1994 $self->_set_repos_root($ra->{repos_root});
91b03282
EW
1995 if ($self->use_svm_props && !$self->{svm}) {
1996 if ($self->no_metadata) {
97ae0911
EW
1997 die "Can't have both 'noMetadata' and ",
1998 "'useSvmProps' options set!\n";
62e349d2
EW
1999 } elsif ($self->use_svnsync_props) {
2000 die "Can't have both 'useSvnsyncProps' and ",
2001 "'useSvmProps' options set!\n";
91b03282 2002 }
26a62d57 2003 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
2004 $self->{-want_revprops} = 1;
2005 }
2006 $ra;
9b981fc6
EW
2007}
2008
15710b6f
EW
2009sub rel_path {
2010 my ($self) = @_;
2011 my $repos_root = $self->ra->{repos_root};
2012 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
2013 my $url = $self->{url} .
2014 (length $self->{path} ? "/$self->{path}" : $self->{path});
2015 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2016 $url;
15710b6f
EW
2017}
2018
01bdab84
BS
2019# prop_walk(PATH, REV, SUB)
2020# -------------------------
2021# Recursively traverse PATH at revision REV and invoke SUB for each
2022# directory that contains a SVN property. SUB will be invoked as
2023# follows: &SUB(gs, path, props); where `gs' is this instance of
2024# Git::SVN, `path' the path to the directory where the properties
2025# `props' were found. The `path' will be relative to point of checkout,
2026# that is, if url://repo/trunk is the current Git branch, and that
2027# directory contains a sub-directory `d', SUB will be invoked with `/d/'
2028# as `path' (note the trailing `/').
2029sub prop_walk {
2030 my ($self, $path, $rev, $sub) = @_;
2031
35cda061 2032 $path =~ s#^/##;
01bdab84
BS
2033 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2034 $path =~ s#^/*#/#g;
9b981fc6 2035 my $p = $path;
01bdab84
BS
2036 # Strip the irrelevant part of the path.
2037 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2038 # Ensure the path is terminated by a `/'.
2039 $p =~ s#/*$#/#;
2040
2041 # The properties contain all the internal SVN stuff nobody
2042 # (usually) cares about.
2043 my $interesting_props = 0;
2044 foreach (keys %{$props}) {
2045 # If it doesn't start with `svn:', it must be a
2046 # user-defined property.
2047 ++$interesting_props and next if $_ !~ /^svn:/;
2048 # FIXME: Fragile, if SVN adds new public properties,
2049 # this needs to be updated.
2050 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2051 |eol-style|mime-type
2052 |externals|needs-lock)$/x;
2053 }
2054 &$sub($self, $p, $props) if $interesting_props;
2055
9b981fc6 2056 foreach (sort keys %$dirent) {
0dc03d6a 2057 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
b7166cce 2058 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
9b981fc6
EW
2059 }
2060}
2061
3ebe8df7
EW
2062sub last_rev { ($_[0]->last_rev_commit)[0] }
2063sub last_commit { ($_[0]->last_rev_commit)[1] }
2064
9b981fc6
EW
2065# returns the newest SVN revision number and newest commit SHA1
2066sub last_rev_commit {
2067 my ($self) = @_;
2068 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2069 return ($self->{last_rev}, $self->{last_commit});
2070 }
d2866f9e 2071 my $c = ::verify_ref($self->refname.'^0');
91b03282 2072 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 2073 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
2074 if (defined $rev) {
2075 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2076 return ($rev, $c);
2077 }
2078 }
060610c5
EW
2079 my $map_path = $self->map_path;
2080 unless (-e $map_path) {
26a62d57
EW
2081 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2082 return (undef, undef);
2083 }
66ab84b9 2084 my ($rev, $commit) = $self->rev_map_max(1);
060610c5
EW
2085 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2086 return ($rev, $commit);
9b981fc6
EW
2087}
2088
3ebe8df7
EW
2089sub get_fetch_range {
2090 my ($self, $min, $max) = @_;
2091 $max ||= $self->ra->get_latest_revnum;
060610c5 2092 $min ||= $self->rev_map_max;
3ebe8df7 2093 (++$min, $max);
9b981fc6
EW
2094}
2095
8a49ee97 2096sub tmp_config {
93f2689c 2097 my (@args) = @_;
b7e5348c
EW
2098 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2099 my $config = "$ENV{GIT_DIR}/svn/.metadata";
38570a47 2100 if (! -f $config && -f $old_def_config) {
b7e5348c
EW
2101 rename $old_def_config, $config or
2102 die "Failed rename $old_def_config => $config: $!\n";
2103 }
8a49ee97 2104 my $old_config = $ENV{GIT_CONFIG};
93f2689c 2105 $ENV{GIT_CONFIG} = $config;
8a49ee97 2106 $@ = undef;
b4d57e5e
EW
2107 my @ret = eval {
2108 unless (-f $config) {
2109 mkfile($config);
2110 open my $fh, '>', $config or
2111 die "Can't open $config: $!\n";
2112 print $fh "; This file is used internally by ",
2113 "git-svn\n" or die
2114 "Couldn't write to $config: $!\n";
2115 print $fh "; You should not have to edit it\n" or
2116 die "Couldn't write to $config: $!\n";
2117 close $fh or die "Couldn't close $config: $!\n";
2118 }
2119 command('config', @args);
2120 };
8a49ee97
EW
2121 my $err = $@;
2122 if (defined $old_config) {
2123 $ENV{GIT_CONFIG} = $old_config;
2124 } else {
2125 delete $ENV{GIT_CONFIG};
2126 }
2127 die $err if $err;
2128 wantarray ? @ret : $ret[0];
2129}
2130
9b981fc6
EW
2131sub tmp_index_do {
2132 my ($self, $sub) = @_;
2133 my $old_index = $ENV{GIT_INDEX_FILE};
2134 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 2135 $@ = undef;
b4d57e5e
EW
2136 my @ret = eval {
2137 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2138 mkpath([$dir]) unless -d $dir;
2139 &$sub;
2140 };
8a49ee97
EW
2141 my $err = $@;
2142 if (defined $old_index) {
9b981fc6
EW
2143 $ENV{GIT_INDEX_FILE} = $old_index;
2144 } else {
2145 delete $ENV{GIT_INDEX_FILE};
2146 }
8a49ee97 2147 die $err if $err;
9b981fc6
EW
2148 wantarray ? @ret : $ret[0];
2149}
2150
2151sub assert_index_clean {
2152 my ($self, $treeish) = @_;
2153
2154 $self->tmp_index_do(sub {
2155 command_noisy('read-tree', $treeish) unless -e $self->{index};
2156 my $x = command_oneline('write-tree');
2157 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2158 /^tree ($::sha1)/mo);
e8d120bd
EW
2159 return if $y eq $x;
2160
2161 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2162 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2163 command_noisy('read-tree', $treeish);
9b981fc6
EW
2164 $x = command_oneline('write-tree');
2165 if ($y ne $x) {
2166 ::fatal "trees ($treeish) $y != $x\n",
207f1a75 2167 "Something is seriously wrong...";
9b981fc6
EW
2168 }
2169 });
2170}
2171
2172sub get_commit_parents {
0af9c9f9 2173 my ($self, $log_entry) = @_;
9b981fc6 2174 my (%seen, @ret, @tmp);
0af9c9f9
EW
2175 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2176 if (my $ip = $self->{inject_parents}) {
2177 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2178 push @tmp, $commit;
9b981fc6
EW
2179 }
2180 }
d2866f9e 2181 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
2182 push @tmp, $cur;
2183 }
733a65aa
EW
2184 if (my $ipd = $self->{inject_parents_dcommit}) {
2185 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2186 push @tmp, @$commit;
2187 }
2188 }
44320b9e 2189 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
2190 while (my $p = shift @tmp) {
2191 next if $seen{$p};
2192 $seen{$p} = 1;
2193 push @ret, $p;
2194 # MAXPARENT is defined to 16 in commit-tree.c:
2195 last if @ret >= 16;
2196 }
2197 if (@tmp) {
44320b9e 2198 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
2199 join("\n\t", @tmp), "\n";
2200 }
2201 @ret;
2202}
2203
aea736cc
EW
2204sub rewrite_root {
2205 my ($self) = @_;
2206 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2207 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2208 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2209 if ($rwr) {
2210 $rwr =~ s#/+$##;
2211 if ($rwr !~ m#^[a-z\+]+://#) {
2212 die "$rwr is not a valid URL (key: $k)\n";
2213 }
2214 }
2215 $self->{-rewrite_root} = $rwr;
2216}
2217
2218sub metadata_url {
2219 my ($self) = @_;
2220 ($self->rewrite_root || $self->{url}) .
2221 (length $self->{path} ? '/' . $self->{path} : '');
2222}
2223
706587fc 2224sub full_url {
9b981fc6 2225 my ($self) = @_;
5d3b7cd5 2226 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
2227}
2228
ad94802a
EW
2229
2230sub set_commit_header_env {
2231 my ($log_entry) = @_;
2232 my %env;
2233 foreach my $ned (qw/NAME EMAIL DATE/) {
2234 foreach my $ac (qw/AUTHOR COMMITTER/) {
2235 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2236 }
9b981fc6 2237 }
ad94802a 2238
70ae04e4
AW
2239 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2240 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
44320b9e 2241 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 2242
70ae04e4
AW
2243 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2244 ? $log_entry->{commit_name}
2245 : $log_entry->{name};
2246 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2247 ? $log_entry->{commit_email}
2248 : $log_entry->{email};
ad94802a
EW
2249 \%env;
2250}
70ae04e4 2251
ad94802a
EW
2252sub restore_commit_header_env {
2253 my ($env) = @_;
2254 foreach my $ned (qw/NAME EMAIL DATE/) {
2255 foreach my $ac (qw/AUTHOR COMMITTER/) {
2256 my $k = "GIT_${ac}_${ned}";
2257 if (defined $env->{$k}) {
2258 $ENV{$k} = $env->{$k};
2259 } else {
2260 delete $ENV{$k};
2261 }
2262 }
2263 }
2264}
2265
94bc914c
KW
2266sub gc {
2267 command_noisy('gc', '--auto');
2268};
2269
ad94802a
EW
2270sub do_git_commit {
2271 my ($self, $log_entry) = @_;
2272 my $lr = $self->last_rev;
2273 if (defined $lr && $lr >= $log_entry->{revision}) {
2274 die "Last fetched revision of ", $self->refname,
2275 " was r$lr, but we are about to fetch: ",
2276 "r$log_entry->{revision}!\n";
2277 }
2278 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2279 croak "$log_entry->{revision} = $c already exists! ",
2280 "Why are we refetching it?\n";
2281 }
2282 my $old_env = set_commit_header_env($log_entry);
44320b9e 2283 my $tree = $log_entry->{tree};
9b981fc6
EW
2284 if (!defined $tree) {
2285 $tree = $self->tmp_index_do(sub {
2286 command_oneline('write-tree') });
2287 }
2288 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2289
e855bfc0 2290 my @exec = ('git', 'commit-tree', $tree);
0af9c9f9 2291 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
2292 push @exec, '-p', $_;
2293 }
2294 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2295 or croak $!;
16fc08e2
EW
2296 binmode $msg_fh;
2297
2298 # we always get UTF-8 from SVN, but we may want our commits in
2299 # a different encoding.
2300 if (my $enc = Git::config('i18n.commitencoding')) {
2301 require Encode;
2302 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2303 }
44320b9e 2304 print $msg_fh $log_entry->{log} or croak $!;
ad94802a 2305 restore_commit_header_env($old_env);
91b03282 2306 unless ($self->no_metadata) {
8a49ee97
EW
2307 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2308 or croak $!;
9760adcc 2309 }
9b981fc6
EW
2310 $msg_fh->flush == 0 or croak $!;
2311 close $msg_fh or croak $!;
2312 chomp(my $commit = do { local $/; <$out_fh> });
2313 close $out_fh or croak $!;
2314 waitpid $pid, 0;
2315 croak $? if $?;
2316 if ($commit !~ /^$::sha1$/o) {
2317 die "Failed to commit, invalid sha1: $commit\n";
2318 }
2319
060610c5 2320 $self->rev_map_set($log_entry->{revision}, $commit, 1);
9b981fc6 2321
44320b9e 2322 $self->{last_rev} = $log_entry->{revision};
9b981fc6 2323 $self->{last_commit} = $commit;
8a49ee97
EW
2324 print "r$log_entry->{revision}";
2325 if (defined $log_entry->{svm_revision}) {
2326 print " (\@$log_entry->{svm_revision})";
060610c5 2327 $self->rev_map_set($log_entry->{svm_revision}, $commit,
26a62d57 2328 0, $self->svm_uuid);
8a49ee97
EW
2329 }
2330 print " = $commit ($self->{ref_id})\n";
94bc914c
KW
2331 if (--$_gc_nr == 0) {
2332 $_gc_nr = $_gc_period;
2333 gc();
2334 }
9b981fc6
EW
2335 return $commit;
2336}
2337
fbcc1737
EW
2338sub match_paths {
2339 my ($self, $paths, $r) = @_;
4e9f6cc7 2340 return 1 if $self->{path} eq '';
d542aedb
EW
2341 if (my $path = $paths->{"/$self->{path}"}) {
2342 return ($path->{action} eq 'D') ? 0 : 1;
2343 }
4e9f6cc7 2344 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
2345 if (grep /$self->{path_regex}/, keys %$paths) {
2346 return 1;
2347 }
2348 my $c = '';
2349 foreach (split m#/#, $self->{path}) {
2350 $c .= "/$_";
74a81227
EW
2351 next unless ($paths->{$c} &&
2352 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
2353 if ($self->ra->check_path($self->{path}, $r) ==
2354 $SVN::Node::dir) {
fbcc1737
EW
2355 return 1;
2356 }
2357 }
2358 return 0;
2359}
2360
15710b6f
EW
2361sub find_parent_branch {
2362 my ($self, $paths, $rev) = @_;
91b03282 2363 return undef unless $self->follow_parent;
e5a0b240 2364 unless (defined $paths) {
c7eba716
EW
2365 my $err_handler = $SVN::Error::handler;
2366 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
2367 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2368 $paths =
2369 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 2370 $SVN::Error::handler = $err_handler;
e5a0b240
EW
2371 }
2372 return undef unless defined $paths;
15710b6f
EW
2373
2374 # look for a parent from another branch:
7f578c55
EW
2375 my @b_path_components = split m#/#, $self->rel_path;
2376 my @a_path_components;
2377 my $i;
2378 while (@b_path_components) {
2379 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 2380 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
2381 unshift(@a_path_components, pop(@b_path_components));
2382 }
74a81227
EW
2383 return undef unless defined $i && defined $i->{copyfrom_path};
2384 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
2385 if (@a_path_components) {
2386 print STDERR "branch_from: $branch_from => ";
2387 $branch_from .= '/'.join('/', @a_path_components);
2388 print STDERR $branch_from, "\n";
2389 }
3ebe8df7 2390 my $r = $i->{copyfrom_rev};
15710b6f
EW
2391 my $repos_root = $self->ra->{repos_root};
2392 my $url = $self->ra->{url};
2393 my $new_url = $repos_root . $branch_from;
2394 print STDERR "Found possible branch point: ",
2395 "$new_url => ", $self->full_url, ", $r\n";
2396 $branch_from =~ s#^/##;
8e3f9b17
SV
2397 my $gs = $self->other_gs($new_url, $url, $repos_root,
2398 $branch_from, $r, $self->{ref_id});
15710b6f 2399 my ($r0, $parent) = $gs->find_rev_before($r, 1);
553589f7
DM
2400 {
2401 my ($base, $head);
2402 if (!defined $r0 || !defined $parent) {
2403 ($base, $head) = parse_revision_argument(0, $r);
2404 } else {
2405 if ($r0 < $r) {
2406 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2407 0, 1, sub { $base = $_[1] - 1 });
2408 }
2409 }
2410 if (defined $base && $base <= $r) {
d627de6b
EW
2411 $gs->fetch($base, $r);
2412 }
553589f7 2413 ($r0, $parent) = $gs->find_rev_before($r, 1);
15710b6f 2414 }
ef70de96 2415 if (defined $r0 && defined $parent) {
15710b6f 2416 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
2417 my $ed;
2418 if ($self->ra->can_do_switch) {
2e5e2480 2419 $self->assert_index_clean($parent);
8b8fc068 2420 print STDERR "Following parent with do_switch\n";
15710b6f 2421 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 2422 # is not included with SVN 1.4.3 (the latest version
15710b6f 2423 # at the moment), so we can't rely on it
83c2fcff 2424 $self->{last_rev} = $r0;
15710b6f 2425 $self->{last_commit} = $parent;
8841b37f 2426 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
8a603774 2427 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
2428 $self->full_url, $ed)
2429 or die "SVN connection failed somewhere...\n";
9ff74e95
SW
2430 } elsif ($self->ra->trees_match($new_url, $r0,
2431 $self->full_url, $rev)) {
2432 print STDERR "Trees match:\n",
2433 " $new_url\@$r0\n",
2434 " ${\$self->full_url}\@$rev\n",
2435 "Following parent with no changes\n";
2436 $self->tmp_index_do(sub {
2437 command_noisy('read-tree', $parent);
2438 });
2439 $self->{last_commit} = $parent;
15710b6f 2440 } else {
8b8fc068 2441 print STDERR "Following parent with do_update\n";
15710b6f 2442 $ed = SVN::Git::Fetcher->new($self);
8a603774 2443 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
2444 or die "SVN connection failed somewhere...\n";
2445 }
f7c3fc4a 2446 print STDERR "Successfully followed parent\n";
15710b6f
EW
2447 return $self->make_log_entry($rev, [$parent], $ed);
2448 }
15710b6f
EW
2449 return undef;
2450}
2451
9b981fc6 2452sub do_fetch {
706587fc 2453 my ($self, $paths, $rev) = @_;
15710b6f 2454 my $ed;
9b981fc6 2455 my ($last_rev, @parents);
b9dffd8c
EW
2456 if (my $lc = $self->last_commit) {
2457 # we can have a branch that was deleted, then re-added
2458 # under the same name but copied from another path, in
2459 # which case we'll have multiple parents (we don't
2460 # want to break the original ref, nor lose copypath info):
2461 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2462 push @{$log_entry->{parents}}, $lc;
2463 return $log_entry;
2464 }
15710b6f 2465 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2466 $last_rev = $self->{last_rev};
b9dffd8c
EW
2467 $ed->{c} = $lc;
2468 @parents = ($lc);
9b981fc6
EW
2469 } else {
2470 $last_rev = $rev;
15710b6f
EW
2471 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2472 return $log_entry;
2473 }
2474 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2475 }
8a603774 2476 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
2477 die "SVN connection failed somewhere...\n";
2478 }
2479 $self->make_log_entry($rev, \@parents, $ed);
2480}
2481
97f6987a
EW
2482sub get_untracked {
2483 my ($self, $ed) = @_;
2484 my @out;
2485 my $h = $ed->{empty};
9b981fc6
EW
2486 foreach (sort keys %$h) {
2487 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 2488 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
2489 warn "W: $act: $_\n";
2490 }
2491 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 2492 $h = $ed->{$t} or next;
9b981fc6
EW
2493 foreach my $path (sort keys %$h) {
2494 my $ppath = $path eq '' ? '.' : $path;
2495 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 2496 next if $SKIP_PROP{$prop};
9b981fc6 2497 my $v = $h->{$path}->{$prop};
97f6987a
EW
2498 my $t_ppath_prop = "$t: " .
2499 uri_encode($ppath) . ' ' .
2500 uri_encode($prop);
9b981fc6 2501 if (defined $v) {
97f6987a
EW
2502 push @out, " +$t_ppath_prop " .
2503 uri_encode($v);
9b981fc6 2504 } else {
97f6987a 2505 push @out, " -$t_ppath_prop";
9b981fc6
EW
2506 }
2507 }
2508 }
2509 }
2510 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 2511 $h = $ed->{$t} or next;
9b981fc6
EW
2512 foreach my $parent (sort keys %$h) {
2513 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
2514 push @out, " $t: " .
2515 uri_encode("$parent/$path");
9b981fc6
EW
2516 warn "W: $t: $parent/$path ",
2517 "Insufficient permissions?\n";
2518 }
2519 }
2520 }
97f6987a 2521 \@out;
9b981fc6
EW
2522}
2523
e82f0d73
PH
2524# parse_svn_date(DATE)
2525# --------------------
2526# Given a date (in UTC) from Subversion, return a string in the format
2527# "<TZ Offset> <local date/time>" that Git will use.
2528#
2529# By default the parsed date will be in UTC; if $Git::SVN::_localtime
2530# is true we'll convert it to the local timezone instead.
1c8443b0
EW
2531sub parse_svn_date {
2532 my $date = shift || return '+0000 1970-01-01 00:00:00';
2533 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
b94ead75 2534 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1c8443b0 2535 croak "Unable to parse date: $date\n";
e82f0d73
PH
2536 my $parsed_date; # Set next.
2537
2538 if ($Git::SVN::_localtime) {
2539 # Translate the Subversion datetime to an epoch time.
2540 # Begin by switching ourselves to $date's timezone, UTC.
2541 my $old_env_TZ = $ENV{TZ};
2542 $ENV{TZ} = 'UTC';
2543
2544 my $epoch_in_UTC =
2545 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2546
2547 # Determine our local timezone (including DST) at the
2548 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2549 # value of TZ, if any, at the time we were run.
2550 if (defined $Git::SVN::Log::TZ) {
2551 $ENV{TZ} = $Git::SVN::Log::TZ;
2552 } else {
2553 delete $ENV{TZ};
2554 }
2555
2556 my $our_TZ =
2557 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2558
2559 # This converts $epoch_in_UTC into our local timezone.
2560 my ($sec, $min, $hour, $mday, $mon, $year,
2561 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2562
2563 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2564 $our_TZ, $year + 1900, $mon + 1,
2565 $mday, $hour, $min, $sec);
2566
2567 # Reset us to the timezone in effect when we entered
2568 # this routine.
2569 if (defined $old_env_TZ) {
2570 $ENV{TZ} = $old_env_TZ;
2571 } else {
2572 delete $ENV{TZ};
2573 }
2574 } else {
2575 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2576 }
2577
2578 return $parsed_date;
1c8443b0
EW
2579}
2580
8e3f9b17
SV
2581sub other_gs {
2582 my ($self, $new_url, $url, $repos_root,
2583 $branch_from, $r, $old_ref_id) = @_;
2584 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2585 unless ($gs) {
2586 my $ref_id = $old_ref_id;
2587 $ref_id =~ s/\@\d+$//;
2588 $ref_id .= "\@$r";
2589 # just grow a tail if we're not unique enough :x
2590 $ref_id .= '-' while find_ref($ref_id);
2591 print STDERR "Initializing parent: $ref_id\n";
2592 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2593 if ($u =~ s#^\Q$url\E(/|$)##) {
2594 $p = $u;
2595 $u = $url;
2596 $repo_id = $self->{repo_id};
2597 }
2598 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2599 }
2600 $gs
2601}
2602
1c8443b0
EW
2603sub check_author {
2604 my ($author) = @_;
2605 if (!defined $author || length $author == 0) {
2606 $author = '(no author)';
9231f500 2607 } elsif (defined $::_authors && ! defined $::users{$author}) {
1c8443b0
EW
2608 die "Author: $author not defined in $::_authors file\n";
2609 }
2610 $author;
2611}
2612
9b981fc6 2613sub make_log_entry {
97f6987a
EW
2614 my ($self, $rev, $parents, $ed) = @_;
2615 my $untracked = $self->get_untracked($ed);
2616
9b981fc6 2617 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
2618 print $un "r$rev\n" or croak $!;
2619 print $un $_, "\n" foreach @$untracked;
2620 my %log_entry = ( parents => $parents || [], revision => $rev,
2621 log => '');
fbcc1737 2622
8a49ee97 2623 my $headrev;
fbcc1737 2624 my $logged = delete $self->{logged_rev_props};
8a49ee97 2625 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
2626 my $rp = $self->ra->rev_proplist($rev);
2627 foreach (sort keys %$rp) {
2628 my $v = $rp->{$_};
2629 if (/^svn:(author|date|log)$/) {
2630 $log_entry{$1} = $v;
8a49ee97
EW
2631 } elsif ($_ eq 'svm:headrev') {
2632 $headrev = $v;
fbcc1737
EW
2633 } else {
2634 print $un " rev_prop: ", uri_encode($_), ' ',
2635 uri_encode($v), "\n";
2636 }
9b981fc6 2637 }
fbcc1737
EW
2638 } else {
2639 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
2640 }
2641 close $un or croak $!;
97f6987a 2642
9b981fc6 2643 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 2644 $log_entry{log} .= "\n";
db03cd24
EW
2645 my $author = $log_entry{author} = check_author($log_entry{author});
2646 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
70ae04e4
AW
2647 : ($author, undef);
2648
2649 my ($commit_name, $commit_email) = ($name, $email);
2650 if ($_use_log_author) {
5ff6aae8
AW
2651 my $name_field;
2652 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2653 $name_field = $1;
2654 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2655 $name_field = $1;
2656 }
2657 if (!defined $name_field) {
abfa533d
SB
2658 if (!defined $email) {
2659 $email = $name;
2660 }
5ff6aae8 2661 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
70ae04e4 2662 ($name, $email) = ($1, $2);
5ff6aae8
AW
2663 } elsif ($name_field =~ /(.*)@/) {
2664 ($name, $email) = ($1, $name_field);
2665 } else {
abfa533d 2666 ($name, $email) = ($name_field, $name_field);
70ae04e4
AW
2667 }
2668 }
91b03282 2669 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
2670 if ($self->rewrite_root) {
2671 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2672 "options set!\n";
2673 }
8a49ee97 2674 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
2675 # we don't want "SVM: initializing mirror for junk" ...
2676 return undef if $r == 0;
2677 my $svm = $self->svm;
2678 if ($uuid ne $svm->{uuid}) {
8a49ee97 2679 die "UUID mismatch on SVM path:\n",
befc9adc 2680 "expected: $svm->{uuid}\n",
8a49ee97
EW
2681 " got: $uuid\n";
2682 }
befc9adc
EW
2683 my $full_url = $self->full_url;
2684 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2685 die "Failed to replace '$svm->{replace}' with ",
2686 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
2687 # throw away username for storing in records
2688 remove_username($full_url);
8a49ee97
EW
2689 $log_entry{metadata} = "$full_url\@$r $uuid";
2690 $log_entry{svm_revision} = $r;
70ae04e4
AW
2691 $email ||= "$author\@$uuid";
2692 $commit_email ||= "$author\@$uuid";
62e349d2
EW
2693 } elsif ($self->use_svnsync_props) {
2694 my $full_url = $self->svnsync->{url};
2695 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 2696 remove_username($full_url);
62e349d2
EW
2697 my $uuid = $self->svnsync->{uuid};
2698 $log_entry{metadata} = "$full_url\@$rev $uuid";
70ae04e4
AW
2699 $email ||= "$author\@$uuid";
2700 $commit_email ||= "$author\@$uuid";
8a49ee97 2701 } else {
ce118739
AR
2702 my $url = $self->metadata_url;
2703 remove_username($url);
2704 $log_entry{metadata} = "$url\@$rev " .
26a62d57 2705 $self->ra->get_uuid;
db03cd24 2706 $email ||= "$author\@" . $self->ra->get_uuid;
70ae04e4 2707 $commit_email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 2708 }
db03cd24
EW
2709 $log_entry{name} = $name;
2710 $log_entry{email} = $email;
70ae04e4
AW
2711 $log_entry{commit_name} = $commit_name;
2712 $log_entry{commit_email} = $commit_email;
9b981fc6
EW
2713 \%log_entry;
2714}
2715
2716sub fetch {
3ebe8df7 2717 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 2718 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 2719 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 2720 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
2721}
2722
2723sub set_tree_cb {
2724 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
2725 $self->{inject_parents} = { $rev => $tree };
2726 $self->fetch(undef, undef);
9b981fc6
EW
2727}
2728
2729sub set_tree {
2730 my ($self, $tree) = (shift, shift);
1ce255dc 2731 my $log_entry = ::get_commit_entry($tree);
9b981fc6 2732 unless ($self->{last_rev}) {
0a1a1c86 2733 ::fatal("Must have an existing revision to commit");
9b981fc6 2734 }
61395354
EW
2735 my %ed_opts = ( r => $self->{last_rev},
2736 log => $log_entry->{log},
2737 ra => $self->ra,
2738 tree_a => $self->{last_commit},
2739 tree_b => $tree,
2740 editor_cb => sub {
2741 $self->set_tree_cb($log_entry, $tree, @_) },
2742 svn_path => $self->{path} );
2743 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
2744 print "No changes\nr$self->{last_rev} = $tree\n";
2745 }
9b981fc6
EW
2746}
2747
060610c5
EW
2748sub rebuild_from_rev_db {
2749 my ($self, $path) = @_;
2750 my $r = -1;
2751 open my $fh, '<', $path or croak "open: $!";
4f7ec797 2752 binmode $fh or croak "binmode: $!";
060610c5
EW
2753 while (<$fh>) {
2754 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2755 chomp($_);
2756 ++$r;
2757 next if $_ eq ('0' x 40);
2758 $self->rev_map_set($r, $_);
2759 print "r$r = $_\n";
2760 }
2761 close $fh or croak "close: $!";
2762 unlink $path or croak "unlink: $!";
2763}
2764
f0ecca10
EW
2765sub rebuild {
2766 my ($self) = @_;
060610c5 2767 my $map_path = $self->map_path;
2beec897 2768 my $partial = (-e $map_path && ! -z $map_path);
d6d3346b 2769 return unless ::verify_ref($self->refname.'^0');
2beec897 2770 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
060610c5
EW
2771 my $rev_db = $self->rev_db_path;
2772 $self->rebuild_from_rev_db($rev_db);
2773 if ($self->use_svm_props) {
2774 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2775 $self->rebuild_from_rev_db($svm_rev_db);
2776 }
2777 $self->unlink_rev_db_symlink;
26a62d57
EW
2778 return;
2779 }
2beec897
DM
2780 print "Rebuilding $map_path ...\n" if (!$partial);
2781 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2782 (undef, undef));
060610c5
EW
2783 my ($log, $ctx) =
2784 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2beec897
DM
2785 ($head ? "$head.." : "") . $self->refname,
2786 '--');
74b1e123
JK
2787 my $metadata_url = $self->metadata_url;
2788 remove_username($metadata_url);
060610c5 2789 my $svn_uuid = $self->ra_uuid;
3dfab993
SV
2790 my $c;
2791 while (<$log>) {
2792 if ( m{^commit ($::sha1)$} ) {
2793 $c = $1;
2794 next;
2795 }
2796 next unless s{^\s*(git-svn-id:)}{$1};
2797 my ($url, $rev, $uuid) = ::extract_metadata($_);
18ea92bd 2798 remove_username($url);
f0ecca10
EW
2799
2800 # ignore merges (from set-tree)
2801 next if (!defined $rev || !$uuid);
2802
2803 # if we merged or otherwise started elsewhere, this is
2804 # how we break out of it
060610c5 2805 if (($uuid ne $svn_uuid) ||
74b1e123 2806 ($metadata_url && $url && ($url ne $metadata_url))) {
f0ecca10
EW
2807 next;
2808 }
2beec897
DM
2809 if ($partial && $head) {
2810 print "Partial-rebuilding $map_path ...\n";
2811 print "Currently at $base_rev = $head\n";
2812 $head = undef;
2813 }
f0ecca10 2814
060610c5 2815 $self->rev_map_set($rev, $c);
f0ecca10
EW
2816 print "r$rev = $c\n";
2817 }
3dfab993 2818 command_close_pipe($log, $ctx);
2beec897 2819 print "Done rebuilding $map_path\n" if (!$partial || !$head);
060610c5
EW
2820 my $rev_db_path = $self->rev_db_path;
2821 if (-f $self->rev_db_path) {
2822 unlink $self->rev_db_path or croak "unlink: $!";
2823 }
2824 $self->unlink_rev_db_symlink;
f0ecca10
EW
2825}
2826
060610c5 2827# rev_map:
9b981fc6
EW
2828# Tie::File seems to be prone to offset errors if revisions get sparse,
2829# it's not that fast, either. Tie::File is also not in Perl 5.6. So
2830# one of my favorite modules is out :< Next up would be one of the DBM
060610c5
EW
2831# modules, but I'm not sure which is most portable...
2832#
2833# This is the replacement for the rev_db format, which was too big
2834# and inefficient for large repositories with a lot of sparse history
2835# (mainly tags)
2836#
2837# The format is this:
2838# - 24 bytes for every record,
2839# * 4 bytes for the integer representing an SVN revision number
2840# * 20 bytes representing the sha1 of a git commit
2841# - No empty padding records like the old format
66ab84b9 2842# (except the last record, which can be overwritten)
060610c5
EW
2843# - new records are written append-only since SVN revision numbers
2844# increase monotonically
2845# - lookups on SVN revision number are done via a binary search
66ab84b9
EW
2846# - Piping the file to xxd -c24 is a good way of dumping it for
2847# viewing or editing (piped back through xxd -r), should the need
2848# ever arise.
2849# - The last record can be padding revision with an all-zero sha1
2850# This is used to optimize fetch performance when using multiple
2851# "fetch" directives in .git/config
060610c5 2852#
97ae0911 2853# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 2854
060610c5 2855sub _rev_map_set {
26a62d57 2856 my ($fh, $rev, $commit) = @_;
060610c5 2857
4f7ec797 2858 binmode $fh or croak "binmode: $!";
060610c5
EW
2859 my $size = (stat($fh))[7];
2860 ($size % 24) == 0 or croak "inconsistent size: $size";
2861
66ab84b9 2862 my $wr_offset = 0;
060610c5
EW
2863 if ($size > 0) {
2864 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2865 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2866 $read == 24 or croak "read only $read bytes (!= 24)";
2867 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
2868 if ($last_commit eq ('0' x40)) {
2869 if ($size >= 48) {
2870 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2871 $read = sysread($fh, $buf, 24) or
2872 croak "read: $!";
2873 $read == 24 or
2874 croak "read only $read bytes (!= 24)";
2875 ($last_rev, $last_commit) =
2876 unpack(rev_map_fmt, $buf);
2877 if ($last_commit eq ('0' x40)) {
2878 croak "inconsistent .rev_map\n";
2879 }
2880 }
2881 if ($last_rev >= $rev) {
2882 croak "last_rev is higher!: $last_rev >= $rev";
2883 }
2884 $wr_offset = -24;
26a62d57
EW
2885 }
2886 }
66ab84b9 2887 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
060610c5
EW
2888 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2889 croak "write: $!";
26a62d57
EW
2890}
2891
2892sub mkfile {
2893 my ($path) = @_;
2894 unless (-e $path) {
2895 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2896 mkpath([$dir]) unless -d $dir;
2897 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2898 close $fh or die "Couldn't close (create) $path: $!\n";
2899 }
2900}
2901
060610c5 2902sub rev_map_set {
26a62d57
EW
2903 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2904 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
060610c5 2905 my $db = $self->map_path($uuid);
26a62d57 2906 my $db_lock = "$db.lock";
373274f9
EW
2907 my $sig;
2908 if ($update_ref) {
2909 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2910 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2911 }
26a62d57
EW
2912 mkfile($db);
2913
373274f9 2914 $LOCKFILES{$db_lock} = 1;
97ae0911 2915 my $sync;
97ae0911
EW
2916 # both of these options make our .rev_db file very, very important
2917 # and we can't afford to lose it because rebuild() won't work
2918 if ($self->use_svm_props || $self->no_metadata) {
2919 $sync = 1;
060610c5 2920 copy($db, $db_lock) or die "rev_map_set(@_): ",
26a62d57 2921 "Failed to copy: ",
373274f9
EW
2922 "$db => $db_lock ($!)\n";
2923 } else {
060610c5 2924 rename $db, $db_lock or die "rev_map_set(@_): ",
26a62d57 2925 "Failed to rename: ",
373274f9
EW
2926 "$db => $db_lock ($!)\n";
2927 }
060610c5 2928
66ab84b9 2929 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
060610c5
EW
2930 or croak "Couldn't open $db_lock: $!\n";
2931 _rev_map_set($fh, $rev, $commit);
97ae0911
EW
2932 if ($sync) {
2933 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2934 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2935 }
9b981fc6 2936 close $fh or croak $!;
373274f9 2937 if ($update_ref) {
1e889ef3 2938 $_head = $self;
373274f9
EW
2939 command_noisy('update-ref', '-m', "r$rev",
2940 $self->refname, $commit);
2941 }
060610c5 2942 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
373274f9
EW
2943 "$db_lock => $db ($!)\n";
2944 delete $LOCKFILES{$db_lock};
2945 if ($update_ref) {
2946 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2947 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2948 kill $sig, $$ if defined $sig;
2949 }
9b981fc6
EW
2950}
2951
66ab84b9
EW
2952# If want_commit, this will return an array of (rev, commit) where
2953# commit _must_ be a valid commit in the archive.
2954# Otherwise, it'll return the max revision (whether or not the
2955# commit is valid or just a 0x40 placeholder).
060610c5 2956sub rev_map_max {
66ab84b9 2957 my ($self, $want_commit) = @_;
d6d3346b 2958 $self->rebuild;
2beec897
DM
2959 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
2960 $want_commit ? ($r, $c) : $r;
2961}
2962
2963sub rev_map_max_norebuild {
2964 my ($self, $want_commit) = @_;
060610c5 2965 my $map_path = $self->map_path;
66ab84b9 2966 stat $map_path or return $want_commit ? (0, undef) : 0;
060610c5 2967 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 2968 binmode $fh or croak "binmode: $!";
060610c5
EW
2969 my $size = (stat($fh))[7];
2970 ($size % 24) == 0 or croak "inconsistent size: $size";
2971
2972 if ($size == 0) {
2973 close $fh or croak "close: $!";
66ab84b9 2974 return $want_commit ? (0, undef) : 0;
060610c5
EW
2975 }
2976
66ab84b9 2977 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
060610c5 2978 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
060610c5 2979 my ($r, $c) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
2980 if ($want_commit && $c eq ('0' x40)) {
2981 if ($size < 48) {
2982 return $want_commit ? (0, undef) : 0;
2983 }
2984 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2985 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2986 ($r, $c) = unpack(rev_map_fmt, $buf);
2987 if ($c eq ('0'x40)) {
2988 croak "Penultimate record is all-zeroes in $map_path";
2989 }
2990 }
2991 close $fh or croak "close: $!";
2992 $want_commit ? ($r, $c) : $r;
9c93fee5
EW
2993}
2994
060610c5 2995sub rev_map_get {
26a62d57 2996 my ($self, $rev, $uuid) = @_;
060610c5
EW
2997 my $map_path = $self->map_path($uuid);
2998 return undef unless -e $map_path;
2999
3000 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 3001 binmode $fh or croak "binmode: $!";
060610c5
EW
3002 my $size = (stat($fh))[7];
3003 ($size % 24) == 0 or croak "inconsistent size: $size";
3004
3005 if ($size == 0) {
3006 close $fh or croak "close: $fh";
3007 return undef;
3008 }
3009
3010 my ($l, $u) = (0, $size - 24);
3011 my ($r, $c, $buf);
3012
3013 while ($l <= $u) {
3014 my $i = int(($l/24 + $u/24) / 2) * 24;
3015 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3016 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3017 my ($r, $c) = unpack('NH40', $buf);
3018
3019 if ($r < $rev) {
3020 $l = $i + 24;
3021 } elsif ($r > $rev) {
3022 $u = $i - 24;
3023 } else { # $r == $rev
3024 close($fh) or croak "close: $!";
66ab84b9 3025 return $c eq ('0' x 40) ? undef : $c;
060610c5 3026 }
9b981fc6 3027 }
060610c5
EW
3028 close($fh) or croak "close: $!";
3029 undef;
9b981fc6
EW
3030}
3031
111947ef
DK
3032# Finds the first svn revision that exists on (if $eq_ok is true) or
3033# before $rev for the current branch. It will not search any lower
3034# than $min_rev. Returns the git commit hash and svn revision number
3035# if found, else (undef, undef).
15710b6f 3036sub find_rev_before {
111947ef 3037 my ($self, $rev, $eq_ok, $min_rev) = @_;
15710b6f 3038 --$rev unless $eq_ok;
111947ef
DK
3039 $min_rev ||= 1;
3040 while ($rev >= $min_rev) {
060610c5 3041 if (my $c = $self->rev_map_get($rev)) {
15710b6f
EW
3042 return ($rev, $c);
3043 }
3044 --$rev;
3045 }
3046 return (undef, undef);
3047}
3048
111947ef
DK
3049# Finds the first svn revision that exists on (if $eq_ok is true) or
3050# after $rev for the current branch. It will not search any higher
3051# than $max_rev. Returns the git commit hash and svn revision number
3052# if found, else (undef, undef).
3053sub find_rev_after {
3054 my ($self, $rev, $eq_ok, $max_rev) = @_;
3055 ++$rev unless $eq_ok;
060610c5 3056 $max_rev ||= $self->rev_map_max;
111947ef 3057 while ($rev <= $max_rev) {
060610c5 3058 if (my $c = $self->rev_map_get($rev)) {
111947ef
DK
3059 return ($rev, $c);
3060 }
3061 ++$rev;
3062 }
3063 return (undef, undef);
3064}
3065
9b981fc6 3066sub _new {
706587fc
EW
3067 my ($class, $repo_id, $ref_id, $path) = @_;
3068 unless (defined $repo_id && length $repo_id) {
3069 $repo_id = $Git::SVN::default_repo_id;
3070 }
3071 unless (defined $ref_id && length $ref_id) {
8b8fc068 3072 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc 3073 }
7829f20f 3074 $_[1] = $repo_id;
706587fc
EW
3075 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3076 $_[3] = $path = '' unless (defined $path);
b4d57e5e 3077 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
3078 bless {
3079 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 3080 path => $path, config => "$ENV{GIT_DIR}/svn/config",
060610c5 3081 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
26a62d57
EW
3082}
3083
060610c5
EW
3084# for read-only access of old .rev_db formats
3085sub unlink_rev_db_symlink {
3086 my ($self) = @_;
3087 my $link = $self->rev_db_path;
3088 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3089 if (-l $link) {
3090 unlink $link or croak "unlink: $link failed!";
3091 }
3092}
3093
3094sub rev_db_path {
3095 my ($self, $uuid) = @_;
3096 my $db_path = $self->map_path($uuid);
3097 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3098 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3099 $db_path;
3100}
3101
3102# the new replacement for .rev_db
3103sub map_path {
26a62d57
EW
3104 my ($self, $uuid) = @_;
3105 $uuid ||= $self->ra_uuid;
060610c5 3106 "$self->{map_root}.$uuid";
9b981fc6
EW
3107}
3108
1c8443b0
EW
3109sub uri_encode {
3110 my ($f) = @_;
3111 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3112 $f
3113}
9b981fc6 3114
18ea92bd
SV
3115sub remove_username {
3116 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3117}
3118
d976acfd
EW
3119package Git::SVN::Prompt;
3120use strict;
3121use warnings;
3122require SVN::Core;
3123use vars qw/$_no_auth_cache $_username/;
3124
3125sub simple {
30d055aa
EW
3126 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3127 $may_save = undef if $_no_auth_cache;
3128 $default_username = $_username if defined $_username;
3129 if (defined $default_username && length $default_username) {
3130 if (defined $realm && length $realm) {
6f729591
EW
3131 print STDERR "Authentication realm: $realm\n";
3132 STDERR->flush;
30d055aa
EW
3133 }
3134 $cred->username($default_username);
3135 } else {
d976acfd 3136 username($cred, $realm, $may_save, $pool);
30d055aa
EW
3137 }
3138 $cred->password(_read_password("Password for '" .
3139 $cred->username . "': ", $realm));
3140 $cred->may_save($may_save);
3141 $SVN::_Core::SVN_NO_ERROR;
3142}
3143
d976acfd 3144sub ssl_server_trust {
30d055aa
EW
3145 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3146 $may_save = undef if $_no_auth_cache;
6f729591 3147 print STDERR "Error validating server certificate for '$realm':\n";
fd499bcc
ER
3148 {
3149 no warnings 'once';
3150 # All variables SVN::Auth::SSL::* are used only once,
3151 # so we're shutting up Perl warnings about this.
3152 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3153 print STDERR " - The certificate is not issued ",
3154 "by a trusted authority. Use the\n",
3155 " fingerprint to validate ",
3156 "the certificate manually!\n";
3157 }
3158 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3159 print STDERR " - The certificate hostname ",
3160 "does not match.\n";
3161 }
3162 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3163 print STDERR " - The certificate is not yet valid.\n";
3164 }
3165 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3166 print STDERR " - The certificate has expired.\n";
3167 }
3168 if ($failures & $SVN::Auth::SSL::OTHER) {
3169 print STDERR " - The certificate has ",
3170 "an unknown error.\n";
3171 }
3172 } # no warnings 'once'
6f729591
EW
3173 printf STDERR
3174 "Certificate information:\n".
30d055aa
EW
3175 " - Hostname: %s\n".
3176 " - Valid: from %s until %s\n".
3177 " - Issuer: %s\n".
3178 " - Fingerprint: %s\n",
3179 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 3180 issuer_dname fingerprint);
30d055aa
EW
3181 my $choice;
3182prompt:
6f729591 3183 print STDERR $may_save ?
30d055aa
EW
3184 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3185 "(R)eject or accept (t)emporarily? ";
6f729591 3186 STDERR->flush;
30d055aa
EW
3187 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3188 if ($choice =~ /^t$/i) {
3189 $cred->may_save(undef);
3190 } elsif ($choice =~ /^r$/i) {
3191 return -1;
3192 } elsif ($may_save && $choice =~ /^p$/i) {
3193 $cred->may_save($may_save);
3194 } else {
3195 goto prompt;
3196 }
3197 $cred->accepted_failures($failures);
3198 $SVN::_Core::SVN_NO_ERROR;
3199}
3200
d976acfd 3201sub ssl_client_cert {
30d055aa
EW
3202 my ($cred, $realm, $may_save, $pool) = @_;
3203 $may_save = undef if $_no_auth_cache;
6f729591
EW
3204 print STDERR "Client certificate filename: ";
3205 STDERR->flush;
30d055aa
EW
3206 chomp(my $filename = <STDIN>);
3207 $cred->cert_file($filename);
3208 $cred->may_save($may_save);
3209 $SVN::_Core::SVN_NO_ERROR;
3210}
3211
d976acfd 3212sub ssl_client_cert_pw {
30d055aa
EW
3213 my ($cred, $realm, $may_save, $pool) = @_;
3214 $may_save = undef if $_no_auth_cache;
3215 $cred->password(_read_password("Password: ", $realm));
3216 $cred->may_save($may_save);
3217 $SVN::_Core::SVN_NO_ERROR;
3218}
3219
d976acfd 3220sub username {
30d055aa
EW
3221 my ($cred, $realm, $may_save, $pool) = @_;
3222 $may_save = undef if $_no_auth_cache;
3223 if (defined $realm && length $realm) {
6f729591 3224 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
3225 }
3226 my $username;
3227 if (defined $_username) {
3228 $username = $_username;
3229 } else {
6f729591
EW
3230 print STDERR "Username: ";
3231 STDERR->flush;
30d055aa
EW
3232 chomp($username = <STDIN>);
3233 }
3234 $cred->username($username);
3235 $cred->may_save($may_save);
3236 $SVN::_Core::SVN_NO_ERROR;
3237}
3238
3239sub _read_password {
3240 my ($prompt, $realm) = @_;
6f729591
EW
3241 print STDERR $prompt;
3242 STDERR->flush;
30d055aa
EW
3243 require Term::ReadKey;
3244 Term::ReadKey::ReadMode('noecho');
3245 my $password = '';
3246 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3247 last if $key =~ /[\012\015]/; # \n\r
3248 $password .= $key;
3249 }
3250 Term::ReadKey::ReadMode('restore');
6f729591
EW
3251 print STDERR "\n";
3252 STDERR->flush;
30d055aa
EW
3253 $password;
3254}
3255
27a1a801
EW
3256package SVN::Git::Fetcher;
3257use vars qw/@ISA/;
3258use strict;
3259use warnings;
3260use Carp qw/croak/;
ffe256f9 3261use File::Temp qw/tempfile/;
27a1a801 3262use IO::File qw//;
edc662f9 3263use vars qw/$_ignore_regex/;
27a1a801
EW
3264
3265# file baton members: path, mode_a, mode_b, pool, fh, blob, base
3266sub new {
8841b37f 3267 my ($class, $git_svn, $switch_path) = @_;
27a1a801
EW
3268 my $self = SVN::Delta::Editor->new;
3269 bless $self, $class;
dbc6c74d
EW
3270 if (exists $git_svn->{last_commit}) {
3271 $self->{c} = $git_svn->{last_commit};
8841b37f
EW
3272 $self->{empty_symlinks} =
3273 _mark_empty_symlinks($git_svn, $switch_path);
dbc6c74d 3274 }
d2a9a87b
EW
3275 $self->{empty} = {};
3276 $self->{dir_prop} = {};
3277 $self->{file_prop} = {};
3278 $self->{absent_dir} = {};
3279 $self->{absent_file} = {};
ef3cfaad 3280 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
3281 $self;
3282}
3283
dbc6c74d
EW
3284# this uses the Ra object, so it must be called before do_{switch,update},
3285# not inside them (when the Git::SVN::Fetcher object is passed) to
3286# do_{switch,update}
3287sub _mark_empty_symlinks {
8841b37f 3288 my ($git_svn, $switch_path) = @_;
4c58a711
EW
3289 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3290 return {} if (defined($bool) && ! $bool);
3291
dbc6c74d
EW
3292 my %ret;
3293 my ($rev, $cmt) = $git_svn->last_rev_commit;
3294 return {} unless ($rev && $cmt);
3295
4c58a711
EW
3296 # allow the warning to be printed for each revision we fetch to
3297 # ensure the user sees it. The user can also disable the workaround
3298 # on the repository even while git svn is running and the next
3299 # revision fetched will skip this expensive function.
3300 my $printed_warning;
dbc6c74d
EW
3301 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3302 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3303 local $/ = "\0";
8841b37f 3304 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
dbc6c74d
EW
3305 $pfx .= '/' if length($pfx);
3306 while (<$ls>) {
3307 chomp;
3308 s/\A100644 blob $empty_blob\t//o or next;
4c58a711
EW
3309 unless ($printed_warning) {
3310 print STDERR "Scanning for empty symlinks, ",
3311 "this may take a while if you have ",
3312 "many empty files\n",
3313 "You may disable this with `",
3314 "git config svn.brokenSymlinkWorkaround ",
3315 "false'.\n",
3316 "This may be done in a different ",
3317 "terminal without restarting ",
3318 "git svn\n";
3319 $printed_warning = 1;
3320 }
dbc6c74d
EW
3321 my $path = $_;
3322 my (undef, $props) =
3323 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3324 if ($props->{'svn:special'}) {
3325 $ret{$path} = 1;
3326 }
3327 }
3328 command_close_pipe($ls, $ctx);
3329 \%ret;
3330}
3331
b03a71a6
EW
3332# returns true if a given path is inside a ".git" directory
3333sub in_dot_git {
3334 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3335}
3336
edc662f9
VS
3337# return value: 0 -- don't ignore, 1 -- ignore
3338sub is_path_ignored {
3339 my ($path) = @_;
3340 return 1 if in_dot_git($path);
3341 return 0 unless defined($_ignore_regex);
3342 return 1 if $path =~ m!$_ignore_regex!o;
3343 return 0;
3344}
3345
8b8fc068
EW
3346sub set_path_strip {
3347 my ($self, $path) = @_;
4e9f6cc7 3348 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
3349}
3350
d2a9a87b
EW
3351sub open_root {
3352 { path => '' };
3353}
3354
3355sub open_directory {
3356 my ($self, $path, $pb, $rev) = @_;
3357 { path => $path };
3358}
3359
706587fc
EW
3360sub git_path {
3361 my ($self, $path) = @_;
2b27f6c8
EW
3362 if ($self->{path_strip}) {
3363 $path =~ s!$self->{path_strip}!! or
3364 die "Failed to strip path '$path' ($self->{path_strip})\n";
3365 }
706587fc
EW
3366 $path;
3367}
3368
27a1a801
EW
3369sub delete_entry {
3370 my ($self, $path, $rev, $pb) = @_;
edc662f9 3371 return undef if is_path_ignored($path);
4a87db0e 3372
706587fc 3373 my $gpath = $self->git_path($path);
8a603774
EW
3374 return undef if ($gpath eq '');
3375
4a87db0e 3376 # remove entire directories.
706587fc 3377 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
3378 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3379 -r --name-only -z/,
706587fc 3380 $self->{c}, '--', $gpath);
4a87db0e
EW
3381 local $/ = "\0";
3382 while (<$ls>) {
ef3cfaad
EW
3383 chomp;
3384 $self->{gii}->remove($_);
9e3cdbd4 3385 print "\tD\t$_\n" unless $::_q;
4a87db0e 3386 }
9e3cdbd4 3387 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
3388 command_close_pipe($ls, $ctx);
3389 $self->{empty}->{$path} = 0
3390 } else {
ef3cfaad 3391 $self->{gii}->remove($gpath);
9e3cdbd4 3392 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 3393 }
27a1a801
EW
3394 undef;
3395}
3396
3397sub open_file {
3398 my ($self, $path, $pb, $rev) = @_;
b03a71a6
EW
3399 my ($mode, $blob);
3400
edc662f9 3401 goto out if is_path_ignored($path);
b03a71a6 3402
706587fc 3403 my $gpath = $self->git_path($path);
b03a71a6 3404 ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 3405 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
3406 unless (defined $mode && defined $blob) {
3407 die "$path was not found in commit $self->{c} (r$rev)\n";
3408 }
dbc6c74d
EW
3409 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3410 $mode = '120000';
3411 }
b03a71a6 3412out:
27a1a801 3413 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 3414 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
3415}
3416
3417sub add_file {
3418 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
b03a71a6
EW
3419 my $mode;
3420
edc662f9 3421 if (!is_path_ignored($path)) {
b03a71a6
EW
3422 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3423 delete $self->{empty}->{$dir};
3424 $mode = '100644';
3425 }
3426 { path => $path, mode_a => $mode, mode_b => $mode,
0864e3ba 3427 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
3428}
3429
d2a9a87b
EW
3430sub add_directory {
3431 my ($self, $path, $cp_path, $cp_rev) = @_;
edc662f9 3432 goto out if is_path_ignored($path);
12a6d752
EW
3433 my $gpath = $self->git_path($path);
3434 if ($gpath eq '') {
3435 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3436 -r --name-only -z/,
3437 $self->{c});
3438 local $/ = "\0";
3439 while (<$ls>) {
3440 chomp;
3441 $self->{gii}->remove($_);
3442 print "\tD\t$_\n" unless $::_q;
3443 }
3444 command_close_pipe($ls, $ctx);
3445 $self->{empty}->{$path} = 0;
3446 }
d2a9a87b
EW
3447 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3448 delete $self->{empty}->{$dir};
3449 $self->{empty}->{$path} = 1;
b03a71a6 3450out:
d2a9a87b
EW
3451 { path => $path };
3452}
3453
3454sub change_dir_prop {
3455 my ($self, $db, $prop, $value) = @_;
edc662f9 3456 return undef if is_path_ignored($db->{path});
d2a9a87b
EW
3457 $self->{dir_prop}->{$db->{path}} ||= {};
3458 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3459 undef;
3460}
3461
3462sub absent_directory {
3463 my ($self, $path, $pb) = @_;
edc662f9 3464 return undef if is_path_ignored($path);
d2a9a87b
EW
3465 $self->{absent_dir}->{$pb->{path}} ||= [];
3466 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3467 undef;
3468}
3469
3470sub absent_file {
3471 my ($self, $path, $pb) = @_;
edc662f9 3472 return undef if is_path_ignored($path);
d2a9a87b
EW
3473 $self->{absent_file}->{$pb->{path}} ||= [];
3474 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3475 undef;
3476}
3477
27a1a801
EW
3478sub change_file_prop {
3479 my ($self, $fb, $prop, $value) = @_;
edc662f9 3480 return undef if is_path_ignored($fb->{path});
27a1a801
EW
3481 if ($prop eq 'svn:executable') {
3482 if ($fb->{mode_b} != 120000) {
3483 $fb->{mode_b} = defined $value ? 100755 : 100644;
3484 }
3485 } elsif ($prop eq 'svn:special') {
3486 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
3487 } else {
3488 $self->{file_prop}->{$fb->{path}} ||= {};
3489 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
3490 }
3491 undef;
3492}
3493
3494sub apply_textdelta {
3495 my ($self, $fb, $exp) = @_;
edc662f9 3496 return undef if is_path_ignored($fb->{path});
1b3069a7 3497 my $fh = $::_repository->temp_acquire('svn_delta');
27a1a801
EW
3498 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3499 # (but $base does not,) so dup() it for reading in close_file
3500 open my $dup, '<&', $fh or croak $!;