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