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