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