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