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