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