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