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