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