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