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