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