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