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