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