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