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