Add 'git svn reset' to unwind 'git svn fetch'
[git/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,
9760adcc 66 $_message, $_file,
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
8f728fb9 95my ($_trunk, $_tags, $_branches, $_stdlayout);
0dfaf0a4 96my %icv;
dadc6d2a
EW
97my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
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,
144 'dry-run|n' => \$_dry_run,
145 'tag|t' => \$_tag } ],
146 tag => [ sub { $_tag = 1; cmd_branch(@_) },
147 'Create a tag in the SVN repository',
148 { 'message|m=s' => \$_message,
149 'dry-run|n' => \$_dry_run } ],
1ce255dc
EW
150 'set-tree' => [ \&cmd_set_tree,
151 "Set an SVN repository to a git tree-ish",
e84dc6df 152 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
d05ddec5
BS
153 'create-ignore' => [ \&cmd_create_ignore,
154 'Create a .gitignore per svn:ignore',
155 { 'revision|r=i' => \$_revision
156 } ],
15153451
BS
157 'propget' => [ \&cmd_propget,
158 'Print the value of a property on a file or directory',
159 { 'revision|r=i' => \$_revision } ],
51e057cf
BS
160 'proplist' => [ \&cmd_proplist,
161 'List all properties of a file or directory',
162 { 'revision|r=i' => \$_revision } ],
5969cbe1 163 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
4dbfe2e9 164 { 'revision|r=i' => \$_revision
05b4df31 165 } ],
2d879792
VK
166 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
167 { 'revision|r=i' => \$_revision
168 } ],
1c8443b0 169 'multi-fetch' => [ \&cmd_multi_fetch,
e98671e5
EW
170 "Deprecated alias for $0 fetch --all",
171 { 'revision|r=s' => \$_revision, %fc_opts } ],
706587fc
EW
172 'migrate' => [ sub { },
173 # no-op, we automatically run this anyways,
706587fc
EW
174 'Migrate configuration/metadata/layout from
175 previous versions of git-svn',
a836a0e1
EW
176 { 'minimize' => \$Git::SVN::Migration::_minimize,
177 %remote_opts } ],
f8c9d1d2
EW
178 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
179 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 180 'revision|r=s' => \$_revision,
f8c9d1d2
EW
181 'verbose|v' => \$Git::SVN::Log::verbose,
182 'incremental' => \$Git::SVN::Log::incremental,
183 'oneline' => \$Git::SVN::Log::oneline,
184 'show-commit' => \$Git::SVN::Log::show_commit,
185 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 186 'authors-file|A=s' => \$_authors,
f8c9d1d2 187 'color' => \$Git::SVN::Log::color,
4dbfe2e9 188 'pager=s' => \$Git::SVN::Log::pager
79bb8d88 189 } ],
222566e4
EW
190 'find-rev' => [ \&cmd_find_rev,
191 "Translate between SVN revision numbers and tree-ish",
4dbfe2e9 192 {} ],
905f8b7d
EW
193 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
194 { 'merge|m|M' => \$_merge,
195 'verbose|v' => \$_verbose,
196 'strategy|s=s' => \$_strategy,
dee41f3e 197 'local|l' => \$_local,
905f8b7d 198 'fetch-all|all' => \$_fetch_all,
7d45e146 199 'dry-run|n' => \$_dry_run,
905f8b7d 200 %fc_opts } ],
44320b9e
EW
201 'commit-diff' => [ \&cmd_commit_diff,
202 'Commit a diff between two trees',
27e9fb8d
EW
203 { 'message|m=s' => \$_message,
204 'file|F=s' => \$_file,
45bf473a 205 'revision|r=s' => \$_revision,
27e9fb8d 206 %cmt_opts } ],
e6fefa92
DK
207 'info' => [ \&cmd_info,
208 "Show info about the latest SVN revision
209 on the current branch",
8b014d71 210 { 'url' => \$_url, } ],
6fb5375e
TS
211 'blame' => [ \&Git::SVN::Log::cmd_blame,
212 "Show what revision and author last modified each line of a file",
4be40381 213 { 'git-format' => \$_git_format } ],
195643f2
BJ
214 'reset' => [ \&cmd_reset,
215 "Undo fetches back to the specified SVN revision",
216 { 'revision|r=s' => \$_revision,
217 'parent|p' => \$_fetch_parent } ],
3397f9df 218);
9d55b41a 219
3397f9df
EW
220my $cmd;
221for (my $i = 0; $i < @ARGV; $i++) {
222 if (defined $cmd{$ARGV[$i]}) {
223 $cmd = $ARGV[$i];
224 splice @ARGV, $i, 1;
225 last;
9a8c92ac
BJ
226 } elsif ($ARGV[$i] eq 'help') {
227 $cmd = $ARGV[$i+1];
228 usage(0);
3397f9df
EW
229 }
230};
231
540424b2
EW
232# make sure we're always running at the top-level working directory
233unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
5253dc33
EW
234 unless (-d $ENV{GIT_DIR}) {
235 if ($git_dir_user_set) {
236 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
237 "but it is not a directory\n";
238 }
239 my $git_dir = delete $ENV{GIT_DIR};
fe4003f6
DM
240 my $cdup = undef;
241 git_cmd_try {
242 $cdup = command_oneline(qw/rev-parse --show-cdup/);
243 $git_dir = '.' unless ($cdup);
244 chomp $cdup if ($cdup);
245 $cdup = "." unless ($cdup && length $cdup);
246 } "Already at toplevel, but $git_dir not found\n";
5253dc33
EW
247 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
248 unless (-d $git_dir) {
249 die "$git_dir still not found after going to ",
250 "'$cdup'\n";
251 }
252 $ENV{GIT_DIR} = $git_dir;
253 }
ffe256f9 254 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
5253dc33 255}
f4dd334b
GH
256
257my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
258
259read_repo_config(\%opts);
222566e4
EW
260if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
261 Getopt::Long::Configure('pass_through');
262}
f4dd334b
GH
263my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
264 'minimize-connections' => \$Git::SVN::Migration::_minimize,
265 'id|i=s' => \$Git::SVN::default_ref_id,
266 'svn-remote|remote|R=s' => sub {
267 $Git::SVN::no_reuse_existing = 1;
268 $Git::SVN::default_repo_id = $_[1] });
269exit 1 if (!$rv && $cmd && $cmd ne 'log');
270
271usage(0) if $_help;
272version() if $_version;
273usage(1) unless defined $cmd;
274load_authors() if $_authors;
36db1edd
ML
275if (defined $_authors_prog) {
276 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
277}
f4dd334b 278
0425ea90 279unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
706587fc
EW
280 Git::SVN::Migration::migration_check();
281}
ecc712dd 282Git::SVN::init_vars();
b805b44a
EW
283eval {
284 Git::SVN::verify_remotes_sanity();
285 $cmd{$cmd}->[0]->(@ARGV);
286};
287fatal $@ if $@;
1e889ef3 288post_fetch_checkout();
3397f9df
EW
289exit 0;
290
291####################### primary functions ######################
292sub usage {
293 my $exit = shift || 0;
294 my $fd = $exit ? \*STDERR : \*STDOUT;
295 print $fd <<"";
296git-svn - bidirectional operations between a single Subversion tree and git
1b1dd23f 297Usage: git svn <command> [options] [arguments]\n
448c81b4
EW
298
299 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
300
301 foreach (sort keys %cmd) {
448c81b4 302 next if $cmd && $cmd ne $_;
a836a0e1 303 next if /^multi-/; # don't show deprecated commands
b203b769 304 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
aa807bc2 305 foreach (sort keys %{$cmd{$_}->[2]}) {
512b620b
EW
306 # mixed-case options are for .git/config only
307 next if /[A-Z]/ && /^[a-z]+$/i;
448c81b4 308 # prints out arguments as they should be passed:
b8c92cad 309 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 310 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
311 "--$_" : "-$_" }
312 split /\|/,$_)," $x\n";
313 }
3397f9df
EW
314 }
315 print $fd <<"";
448c81b4
EW
316\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
317arbitrary identifier if you're tracking multiple SVN branches/repositories in
318one git repository and want to keep them separate. See git-svn(1) for more
319information.
3397f9df
EW
320
321 exit $exit;
322}
323
551ce28f 324sub version {
7d60ab2c 325 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
326 exit 0;
327}
328
8164b652
EW
329sub do_git_init_db {
330 unless (-d $ENV{GIT_DIR}) {
331 my @init_db = ('init');
332 push @init_db, "--template=$_template" if defined $_template;
dadc6d2a
EW
333 if (defined $_shared) {
334 if ($_shared =~ /[a-z]/) {
335 push @init_db, "--shared=$_shared";
336 } else {
337 push @init_db, "--shared";
338 }
339 }
8164b652 340 command_noisy(@init_db);
ffe256f9 341 $_repository = Git->repository(Repository => ".git");
8164b652 342 }
d3c9634e 343 command_noisy('config', 'core.autocrlf', 'false');
0dfaf0a4
EW
344 my $set;
345 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
346 foreach my $i (keys %icv) {
347 die "'$set' and '$i' cannot both be set\n" if $set;
348 next unless defined $icv{$i};
349 command_noisy('config', "$pfx.$i", $icv{$i});
350 $set = $i;
351 }
88ec2054
BJ
352 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
353 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
354 if defined $$ignore_regex;
8164b652
EW
355}
356
dadc6d2a
EW
357sub init_subdir {
358 my $repo_path = shift or return;
359 mkpath([$repo_path]) unless -d $repo_path;
360 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
f30603fc 361 $ENV{GIT_DIR} = '.git';
ffe256f9 362 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
dadc6d2a
EW
363}
364
0425ea90
EW
365sub cmd_clone {
366 my ($url, $path) = @_;
367 if (!defined $path &&
8f728fb9 368 (defined $_trunk || defined $_branches || defined $_tags ||
369 defined $_stdlayout) &&
0425ea90
EW
370 $url !~ m#^[a-z\+]+://#) {
371 $path = $url;
372 }
0425ea90 373 $path = basename($url) if !defined $path || !length $path;
f30603fc 374 cmd_init($url, $path);
0425ea90 375 Git::SVN::fetch_all($Git::SVN::default_repo_id);
42a5da18 376 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
0425ea90
EW
377}
378
d2866f9e 379sub cmd_init {
8f728fb9 380 if (defined $_stdlayout) {
381 $_trunk = 'trunk' if (!defined $_trunk);
382 $_tags = 'tags' if (!defined $_tags);
383 $_branches = 'branches' if (!defined $_branches);
384 }
dadc6d2a
EW
385 if (defined $_trunk || defined $_branches || defined $_tags) {
386 return cmd_multi_init(@_);
03e0ea87 387 }
dadc6d2a
EW
388 my $url = shift or die "SVN repository location required ",
389 "as a command-line argument\n";
390 init_subdir(@_);
8164b652 391 do_git_init_db();
03e0ea87 392
706587fc 393 Git::SVN->init($url);
3397f9df
EW
394}
395
2a3240be 396sub cmd_fetch {
e98671e5
EW
397 if (grep /^\d+=./, @_) {
398 die "'<rev>=<commit>' fetch arguments are ",
399 "no longer supported.\n";
07a1c950 400 }
e98671e5
EW
401 my ($remote) = @_;
402 if (@_ > 1) {
c2abd83f 403 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
e98671e5 404 }
c2abd83f
JM
405 if ($_fetch_parent) {
406 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
407 unless ($gs) {
408 die "Unable to determine upstream SVN information from ",
409 "working tree history\n";
410 }
411 # just fetch, don't checkout.
412 $_no_checkout = 'true';
413 $_fetch_all ? $gs->fetch_all : $gs->fetch;
414 } elsif ($_fetch_all) {
e98671e5
EW
415 cmd_multi_fetch();
416 } else {
c2abd83f 417 $remote ||= $Git::SVN::default_repo_id;
e98671e5 418 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
1c8443b0 419 }
2a3240be
EW
420}
421
1ce255dc 422sub cmd_set_tree {
3397f9df
EW
423 my (@commits) = @_;
424 if ($_stdin || !@commits) {
425 print "Reading from stdin...\n";
426 @commits = ();
427 while (<STDIN>) {
1ca72aef 428 if (/\b($sha1_short)\b/o) {
3397f9df
EW
429 unshift @commits, $1;
430 }
431 }
432 }
433 my @revs;
8de010ad 434 foreach my $c (@commits) {
aef4e921 435 my @tmp = command('rev-parse',$c);
8de010ad
EW
436 if (scalar @tmp == 1) {
437 push @revs, $tmp[0];
438 } elsif (scalar @tmp > 1) {
aef4e921 439 push @revs, reverse(command('rev-list',@tmp));
8de010ad 440 } else {
207f1a75 441 fatal "Failed to rev-parse $c";
8de010ad 442 }
3397f9df 443 }
1ce255dc
EW
444 my $gs = Git::SVN->new;
445 my ($r_last, $cmt_last) = $gs->last_rev_commit;
446 $gs->fetch;
97f6987a 447 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
448 fatal "There are new revisions that were fetched ",
449 "and need to be merged (or acknowledged) ",
450 "before committing.\nlast rev: $r_last\n",
207f1a75 451 " current: $gs->{last_rev}";
a5e0cedc 452 }
1ce255dc
EW
453 $gs->set_tree($_) foreach @revs;
454 print "Done committing ",scalar @revs," revisions to SVN\n";
3157dd9e 455 unlink $gs->{index};
a5e0cedc 456}
8f22562c 457
d7ad3bed
EW
458sub cmd_dcommit {
459 my $head = shift;
c8cfa3e4 460 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
826a9339 461 'Cannot dcommit with a dirty index. Commit your changes first, '
c8cfa3e4 462 . "or stash them with `git stash'.\n";
d7ad3bed 463 $head ||= 'HEAD';
5eec27e3
TR
464
465 my $old_head;
466 if ($head ne 'HEAD') {
467 $old_head = eval {
468 command_oneline([qw/symbolic-ref -q HEAD/])
469 };
470 if ($old_head) {
471 $old_head =~ s{^refs/heads/}{};
472 } else {
473 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
474 }
475 command(['checkout', $head], STDERR => 0);
476 }
477
a8ae2623 478 my @refs;
5eec27e3 479 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
2cb61105
TR
480 unless ($gs) {
481 die "Unable to determine upstream SVN information from ",
482 "$head history.\nPerhaps the repository is empty.";
483 }
0df84059
PO
484
485 if (defined $_commit_url) {
486 $url = $_commit_url;
487 } else {
488 $url = eval { command_oneline('config', '--get',
489 "svn-remote.$gs->{repo_id}.commiturl") };
490 if (!$url) {
491 $url = $gs->full_url
492 }
493 }
494
ba24e745 495 my $last_rev = $_revision if defined $_revision;
59b0c24d
MM
496 if ($url) {
497 print "Committing to $url ...\n";
498 }
733a65aa 499 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
751eb395
EW
500 if ($_no_rebase && scalar(@$linear_refs) > 1) {
501 warn "Attempting to commit more than one change while ",
502 "--no-rebase is enabled.\n",
503 "If these changes depend on each other, re-running ",
7dfa16b9 504 "without --no-rebase may be required."
751eb395 505 }
711521e2
EW
506 my $expect_url = $url;
507 Git::SVN::remove_username($expect_url);
c74d9acf
EW
508 while (1) {
509 my $d = shift @$linear_refs or last;
45bf473a
EW
510 unless (defined $last_rev) {
511 (undef, $last_rev, undef) = cmt_metadata("$d~1");
512 unless (defined $last_rev) {
d7ad3bed 513 fatal "Unable to extract revision information ",
207f1a75 514 "from commit $d~1";
45bf473a
EW
515 }
516 }
b22d4497
EW
517 if ($_dry_run) {
518 print "diff-tree $d~1 $d\n";
519 } else {
751eb395 520 my $cmt_rev;
d7ad3bed 521 my %ed_opts = ( r => $last_rev,
61395354 522 log => get_commit_entry($d)->{log},
ba24e745 523 ra => Git::SVN::Ra->new($url),
3caf320b
KA
524 config => SVN::Core::config_get_config(
525 $Git::SVN::Ra::config_dir
526 ),
61395354
EW
527 tree_a => "$d~1",
528 tree_b => $d,
529 editor_cb => sub {
530 print "Committed r$_[0]\n";
751eb395
EW
531 $cmt_rev = $_[0];
532 },
a8ae2623 533 svn_path => '');
61395354 534 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed 535 print "No changes\n$d~1 == $d\n";
733a65aa 536 } elsif ($parents->{$d} && @{$parents->{$d}}) {
751eb395 537 $gs->{inject_parents_dcommit}->{$cmt_rev} =
733a65aa 538 $parents->{$d};
d7ad3bed 539 }
751eb395 540 $_fetch_all ? $gs->fetch_all : $gs->fetch;
7dfa16b9 541 $last_rev = $cmt_rev;
751eb395
EW
542 next if $_no_rebase;
543
544 # we always want to rebase against the current HEAD,
545 # not any head that was passed to us
c74d9acf 546 my @diff = command('diff-tree', $d,
751eb395
EW
547 $gs->refname, '--');
548 my @finish;
549 if (@diff) {
550 @finish = rebase_cmd();
c74d9acf 551 print STDERR "W: $d and ", $gs->refname,
751eb395 552 " differ, using @finish:\n",
c74d9acf 553 join("\n", @diff), "\n";
751eb395
EW
554 } else {
555 print "No changes between current HEAD and ",
556 $gs->refname,
557 "\nResetting to the latest ",
558 $gs->refname, "\n";
559 @finish = qw/reset --mixed/;
560 }
561 command_noisy(@finish, $gs->refname);
c74d9acf
EW
562 if (@diff) {
563 @refs = ();
564 my ($url_, $rev_, $uuid_, $gs_) =
5eec27e3 565 working_head_info('HEAD', \@refs);
c74d9acf
EW
566 my ($linear_refs_, $parents_) =
567 linearize_history($gs_, \@refs);
568 if (scalar(@$linear_refs) !=
569 scalar(@$linear_refs_)) {
570 fatal "# of revisions changed ",
571 "\nbefore:\n",
572 join("\n", @$linear_refs),
573 "\n\nafter:\n",
574 join("\n", @$linear_refs_), "\n",
575 'If you are attempting to commit ',
576 "merges, try running:\n\t",
577 'git rebase --interactive',
578 '--preserve-merges ',
579 $gs->refname,
580 "\nBefore dcommitting";
581 }
711521e2 582 if ($url_ ne $expect_url) {
c74d9acf 583 fatal "URL mismatch after rebase: ",
711521e2 584 "$url_ != $expect_url";
c74d9acf
EW
585 }
586 if ($uuid_ ne $uuid) {
587 fatal "uuid mismatch after rebase: ",
588 "$uuid_ != $uuid";
589 }
590 # remap parents
591 my (%p, @l, $i);
592 for ($i = 0; $i < scalar @$linear_refs; $i++) {
593 my $new = $linear_refs_->[$i] or next;
594 $p{$new} =
595 $parents->{$linear_refs->[$i]};
596 push @l, $new;
597 }
598 $parents = \%p;
599 $linear_refs = \@l;
600 }
b22d4497
EW
601 }
602 }
5eec27e3
TR
603
604 if ($old_head) {
605 my $new_head = command_oneline(qw/rev-parse HEAD/);
606 my $new_is_symbolic = eval {
607 command_oneline(qw/symbolic-ref -q HEAD/);
608 };
609 if ($new_is_symbolic) {
610 print "dcommitted the branch ", $head, "\n";
611 } else {
612 print "dcommitted on a detached HEAD because you gave ",
613 "a revision argument.\n",
614 "The rewritten commit is: ", $new_head, "\n";
615 }
616 command(['checkout', $old_head], STDERR => 0);
617 }
618
3157dd9e 619 unlink $gs->{index};
b22d4497
EW
620}
621
5de70efb
FR
622sub cmd_branch {
623 my ($branch_name, $head) = @_;
624
625 unless (defined $branch_name && length $branch_name) {
626 die(($_tag ? "tag" : "branch") . " name required\n");
627 }
628 $head ||= 'HEAD';
629
630 my ($src, $rev, undef, $gs) = working_head_info($head);
631
a0fbc87c 632 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
5de70efb
FR
633 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
634 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
635 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
636
637 my $ctx = SVN::Client->new(
638 auth => Git::SVN::Ra::_auth_providers(),
639 log_msg => sub {
640 ${ $_[0] } = defined $_message
641 ? $_message
642 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
643 . $branch_name;
644 },
645 );
646
647 eval {
648 $ctx->ls($dst, 'HEAD', 0);
649 } and die "branch ${branch_name} already exists\n";
650
651 print "Copying ${src} at r${rev} to ${dst}...\n";
652 $ctx->copy($src, $rev, $dst)
653 unless $_dry_run;
654
655 $gs->fetch_all;
656}
657
26e60160 658sub cmd_find_rev {
ea14e6c5
MAL
659 my $revision_or_hash = shift or die "SVN or git revision required ",
660 "as a command-line argument\n";
26e60160
AR
661 my $result;
662 if ($revision_or_hash =~ /^r\d+$/) {
b3cb7e45
AR
663 my $head = shift;
664 $head ||= 'HEAD';
665 my @refs;
63c56022 666 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
b3cb7e45
AR
667 unless ($gs) {
668 die "Unable to determine upstream SVN information from ",
669 "$head history\n";
26e60160 670 }
b3cb7e45 671 my $desired_revision = substr($revision_or_hash, 1);
63c56022 672 $result = $gs->rev_map_get($desired_revision, $uuid);
26e60160
AR
673 } else {
674 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
675 $result = $rev;
676 }
677 print "$result\n" if $result;
678}
679
905f8b7d
EW
680sub cmd_rebase {
681 command_noisy(qw/update-index --refresh/);
13c823fb
EW
682 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
683 unless ($gs) {
905f8b7d
EW
684 die "Unable to determine upstream SVN information from ",
685 "working tree history\n";
686 }
7d45e146
SF
687 if ($_dry_run) {
688 print "Remote Branch: " . $gs->refname . "\n";
689 print "SVN URL: " . $url . "\n";
690 return;
691 }
905f8b7d
EW
692 if (command(qw/diff-index HEAD --/)) {
693 print STDERR "Cannot rebase with uncommited changes:\n";
694 command_noisy('status');
695 exit 1;
696 }
dee41f3e 697 unless ($_local) {
cec0d5a3
SG
698 # rebase will checkout for us, so no need to do it explicitly
699 $_no_checkout = 'true';
dee41f3e
EW
700 $_fetch_all ? $gs->fetch_all : $gs->fetch;
701 }
905f8b7d
EW
702 command_noisy(rebase_cmd(), $gs->refname);
703}
704
5969cbe1 705sub cmd_show_ignore {
13c823fb
EW
706 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
707 $gs ||= Git::SVN->new;
5969cbe1 708 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
01bdab84
BS
709 $gs->prop_walk($gs->{path}, $r, sub {
710 my ($gs, $path, $props) = @_;
711 print STDOUT "\n# $path\n";
712 my $s = $props->{'svn:ignore'} or return;
713 $s =~ s/[\r\n]+/\n/g;
714 chomp $s;
715 $s =~ s#^#$path#gm;
716 print STDOUT "$s\n";
717 });
a5e0cedc
EW
718}
719
2d879792
VK
720sub cmd_show_externals {
721 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
722 $gs ||= Git::SVN->new;
723 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
724 $gs->prop_walk($gs->{path}, $r, sub {
725 my ($gs, $path, $props) = @_;
726 print STDOUT "\n# $path\n";
727 my $s = $props->{'svn:externals'} or return;
728 $s =~ s/[\r\n]+/\n/g;
729 chomp $s;
730 $s =~ s#^#$path#gm;
731 print STDOUT "$s\n";
732 });
733}
734
d05ddec5
BS
735sub cmd_create_ignore {
736 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
737 $gs ||= Git::SVN->new;
738 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
739 $gs->prop_walk($gs->{path}, $r, sub {
740 my ($gs, $path, $props) = @_;
741 # $path is of the form /path/to/dir/
7d9fd459
BG
742 $path = '.' . $path;
743 # SVN can have attributes on empty directories,
744 # which git won't track
745 mkpath([$path]) unless -d $path;
746 my $ignore = $path . '.gitignore';
d05ddec5
BS
747 my $s = $props->{'svn:ignore'} or return;
748 open(GITIGNORE, '>', $ignore)
207f1a75 749 or fatal("Failed to open `$ignore' for writing: $!");
d05ddec5
BS
750 $s =~ s/[\r\n]+/\n/g;
751 chomp $s;
752 # Prefix all patterns so that the ignore doesn't apply
753 # to sub-directories.
754 $s =~ s#^#/#gm;
755 print GITIGNORE "$s\n";
756 close(GITIGNORE)
207f1a75 757 or fatal("Failed to close `$ignore': $!");
c4c66b26 758 command_noisy('add', '-f', $ignore);
d05ddec5
BS
759 });
760}
761
b2b3ada7
DK
762sub canonicalize_path {
763 my ($path) = @_;
e6fefa92
DK
764 my $dot_slash_added = 0;
765 if (substr($path, 0, 1) ne "/") {
766 $path = "./" . $path;
767 $dot_slash_added = 1;
768 }
b2b3ada7
DK
769 # File::Spec->canonpath doesn't collapse x/../y into y (for a
770 # good reason), so let's do this manually.
771 $path =~ s#/+#/#g;
772 $path =~ s#/\.(?:/|$)#/#g;
773 $path =~ s#/[^/]+/\.\.##g;
774 $path =~ s#/$##g;
e6fefa92 775 $path =~ s#^\./## if $dot_slash_added;
2fe403e7
GP
776 $path =~ s#^/##;
777 $path =~ s#^\.$##;
b2b3ada7
DK
778 return $path;
779}
780
15153451
BS
781# get_svnprops(PATH)
782# ------------------
51e057cf 783# Helper for cmd_propget and cmd_proplist below.
15153451
BS
784sub get_svnprops {
785 my $path = shift;
786 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
787 $gs ||= Git::SVN->new;
788
789 # prefix THE PATH by the sub-directory from which the user
790 # invoked us.
791 $path = $cmd_dir_prefix . $path;
207f1a75 792 fatal("No such file or directory: $path") unless -e $path;
15153451
BS
793 my $is_dir = -d $path ? 1 : 0;
794 $path = $gs->{path} . '/' . $path;
795
796 # canonicalize the path (otherwise libsvn will abort or fail to
797 # find the file)
b2b3ada7 798 $path = canonicalize_path($path);
15153451
BS
799
800 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
801 my $props;
802 if ($is_dir) {
803 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
804 }
805 else {
806 (undef, $props) = $gs->ra->get_file($path, $r, undef);
807 }
808 return $props;
809}
810
811# cmd_propget (PROP, PATH)
812# ------------------------
813# Print the SVN property PROP for PATH.
814sub cmd_propget {
815 my ($prop, $path) = @_;
816 $path = '.' if not defined $path;
817 usage(1) if not defined $prop;
818 my $props = get_svnprops($path);
819 if (not defined $props->{$prop}) {
207f1a75 820 fatal("`$path' does not have a `$prop' SVN property.");
15153451
BS
821 }
822 print $props->{$prop} . "\n";
823}
824
51e057cf
BS
825# cmd_proplist (PATH)
826# -------------------
827# Print the list of SVN properties for PATH.
828sub cmd_proplist {
829 my $path = shift;
830 $path = '.' if not defined $path;
831 my $props = get_svnprops($path);
832 print "Properties on '$path':\n";
833 foreach (sort keys %{$props}) {
834 print " $_\n";
835 }
836}
837
8164b652 838sub cmd_multi_init {
9d55b41a 839 my $url = shift;
98327e58
EW
840 unless (defined $_trunk || defined $_branches || defined $_tags) {
841 usage(1);
9d55b41a 842 }
dc431666
EW
843
844 # there are currently some bugs that prevent multi-init/multi-fetch
845 # setups from working well without this.
846 $Git::SVN::_minimize_url = 1;
847
8164b652 848 $_prefix = '' unless defined $_prefix;
dadc6d2a
EW
849 if (defined $url) {
850 $url =~ s#/+$##;
851 init_subdir(@_);
852 }
f30603fc 853 do_git_init_db();
98327e58 854 if (defined $_trunk) {
706587fc
EW
855 my $trunk_ref = $_prefix . 'trunk';
856 # try both old-style and new-style lookups:
857 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 858 unless ($gs_trunk) {
706587fc
EW
859 my ($trunk_url, $trunk_path) =
860 complete_svn_url($url, $_trunk);
861 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
862 undef, $trunk_ref);
98327e58 863 }
c35b96e7 864 }
706587fc 865 return unless defined $_branches || defined $_tags;
e7db67e6
EW
866 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
867 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
868 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
869}
870
1c8443b0 871sub cmd_multi_fetch {
0af9c9f9
EW
872 my $remotes = Git::SVN::read_all_remotes();
873 foreach my $repo_id (sort keys %$remotes) {
db03cd24 874 if ($remotes->{$repo_id}->{url}) {
4bb9ed04
EW
875 Git::SVN::fetch_all($repo_id, $remotes);
876 }
9d55b41a 877 }
9d55b41a
EW
878}
879
44320b9e
EW
880# this command is special because it requires no metadata
881sub cmd_commit_diff {
882 my ($ta, $tb, $url) = @_;
883 my $usage = "Usage: $0 commit-diff -r<revision> ".
207f1a75 884 "<tree-ish> <tree-ish> [<URL>]";
44320b9e 885 fatal($usage) if (!defined $ta || !defined $tb);
d72ab8c8 886 my $svn_path = '';
44320b9e
EW
887 if (!defined $url) {
888 my $gs = eval { Git::SVN->new };
889 if (!$gs) {
890 fatal("Needed URL or usable git-svn --id in ",
891 "the command-line\n", $usage);
892 }
893 $url = $gs->{url};
d3a840dc 894 $svn_path = $gs->{path};
44320b9e
EW
895 }
896 unless (defined $_revision) {
897 fatal("-r|--revision is a required argument\n", $usage);
898 }
899 if (defined $_message && defined $_file) {
900 fatal("Both --message/-m and --file/-F specified ",
901 "for the commit message.\n",
207f1a75 902 "I have no idea what you mean");
44320b9e
EW
903 }
904 if (defined $_file) {
905 $_message = file_to_s($_file);
906 } else {
907 $_message ||= get_commit_entry($tb)->{log};
908 }
909 my $ra ||= Git::SVN::Ra->new($url);
910 my $r = $_revision;
911 if ($r eq 'HEAD') {
912 $r = $ra->get_latest_revnum;
913 } elsif ($r !~ /^\d+$/) {
914 die "revision argument: $r not understood by git-svn\n";
915 }
61395354
EW
916 my %ed_opts = ( r => $r,
917 log => $_message,
918 ra => $ra,
919 tree_a => $ta,
920 tree_b => $tb,
921 editor_cb => sub { print "Committed r$_[0]\n" },
922 svn_path => $svn_path );
923 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
924 print "No changes\n$ta == $tb\n";
925 }
44320b9e
EW
926}
927
05427b91
TR
928sub escape_uri_only {
929 my ($uri) = @_;
930 my @tmp;
931 foreach (split m{/}, $uri) {
6a004d3f 932 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
05427b91
TR
933 push @tmp, $_;
934 }
935 join('/', @tmp);
936}
937
938sub escape_url {
939 my ($url) = @_;
940 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
941 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
942 $url = "$scheme://$domain$uri";
943 }
944 $url;
945}
946
e6fefa92 947sub cmd_info {
bd2d4f96 948 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
edde9112 949 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
bd2d4f96 950 if (exists $_[1]) {
e6fefa92
DK
951 die "Too many arguments specified\n";
952 }
953
954 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
955
956 if (!$file_type && !$diff_status) {
2cf3e3ac
TR
957 print STDERR "svn: '$path' is not under version control\n";
958 exit 1;
e6fefa92
DK
959 }
960
961 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
962 unless ($gs) {
963 die "Unable to determine upstream SVN information from ",
964 "working tree history\n";
965 }
bd2d4f96
EW
966
967 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
968 $path = "." if $path eq "";
969
edde9112 970 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
e6fefa92 971
8b014d71 972 if ($_url) {
05427b91 973 print escape_url($full_url), "\n";
8b014d71
DK
974 return;
975 }
976
e6fefa92
DK
977 my $result = "Path: $path\n";
978 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
05427b91 979 $result .= "URL: " . escape_url($full_url) . "\n";
e6fefa92 980
a5460eb7
EW
981 eval {
982 my $repos_root = $gs->repos_root;
983 Git::SVN::remove_username($repos_root);
05427b91 984 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
a5460eb7
EW
985 };
986 if ($@) {
987 $result .= "Repository Root: (offline)\n";
988 }
22ba47f5
MK
989 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
990 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
e6fefa92
DK
991 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
992
993 $result .= "Node Kind: " .
994 ($file_type eq "dir" ? "directory" : "file") . "\n";
995
996 my $schedule = $diff_status eq "A"
997 ? "add"
998 : ($diff_status eq "D" ? "delete" : "normal");
999 $result .= "Schedule: $schedule\n";
1000
1001 if ($diff_status eq "A") {
1002 print $result, "\n";
1003 return;
1004 }
1005
1006 my ($lc_author, $lc_rev, $lc_date_utc);
edde9112 1007 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
e6fefa92
DK
1008 my $log = command_output_pipe(@args);
1009 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1010 while (<$log>) {
1011 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1012 $lc_author = $1;
1013 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1014 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1015 (undef, $lc_rev, undef) = ::extract_metadata($1);
1016 }
1017 }
1018 close $log;
1019
1020 Git::SVN::Log::set_local_timezone();
1021
1022 $result .= "Last Changed Author: $lc_author\n";
1023 $result .= "Last Changed Rev: $lc_rev\n";
1024 $result .= "Last Changed Date: " .
1025 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1026
1027 if ($file_type ne "dir") {
1028 my $text_last_updated_date =
1029 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1030 $result .=
1031 "Text Last Updated: " .
1032 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1033 "\n";
1034 my $checksum;
1035 if ($diff_status eq "D") {
1036 my ($fh, $ctx) =
1037 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1038 if ($file_type eq "link") {
1039 my $file_name = <$fh>;
8d7c4fad 1040 $checksum = md5sum("link $file_name");
e6fefa92 1041 } else {
8d7c4fad 1042 $checksum = md5sum($fh);
e6fefa92
DK
1043 }
1044 command_close_pipe($fh, $ctx);
1045 } elsif ($file_type eq "link") {
1046 my $file_name =
1047 command(qw(cat-file blob), "HEAD:$path");
1048 $checksum =
8d7c4fad 1049 md5sum("link " . $file_name);
e6fefa92
DK
1050 } else {
1051 open FILE, "<", $path or die $!;
8d7c4fad 1052 $checksum = md5sum(\*FILE);
e6fefa92
DK
1053 close FILE or die $!;
1054 }
1055 $result .= "Checksum: " . $checksum . "\n";
1056 }
1057
1058 print $result, "\n";
1059}
1060
195643f2
BJ
1061sub cmd_reset {
1062 my $target = shift || $_revision or die "SVN revision required\n";
1063 $target = $1 if $target =~ /^r(\d+)$/;
1064 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1065 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1066 unless ($gs) {
1067 die "Unable to determine upstream SVN information from ".
1068 "history\n";
1069 }
1070 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1071 $gs->rev_map_set($r, $c, 'reset', $uuid);
1072 print "r$r = $c ($gs->{ref_id})\n";
1073}
1074
3397f9df
EW
1075########################### utility functions #########################
1076
905f8b7d
EW
1077sub rebase_cmd {
1078 my @cmd = qw/rebase/;
1079 push @cmd, '-v' if $_verbose;
1080 push @cmd, qw/--merge/ if $_merge;
1081 push @cmd, "--strategy=$_strategy" if $_strategy;
1082 @cmd;
1083}
1084
1e889ef3
EW
1085sub post_fetch_checkout {
1086 return if $_no_checkout;
1087 my $gs = $Git::SVN::_head or return;
1088 return if verify_ref('refs/heads/master^0');
1089
1090 my $valid_head = verify_ref('HEAD^0');
1091 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1092 return if ($valid_head || !verify_ref('HEAD^0'));
1093
1094 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1095 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1096 return if -f $index;
1097
7ae3df8c 1098 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1e889ef3
EW
1099 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1100 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1101 print STDERR "Checked out HEAD:\n ",
1102 $gs->full_url, " r", $gs->last_rev, "\n";
1103}
1104
98327e58
EW
1105sub complete_svn_url {
1106 my ($url, $path) = @_;
1107 $path =~ s#/+$##;
98327e58 1108 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
1109 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1110 fatal("E: '$path' is not a complete URL ",
207f1a75 1111 "and a separate URL is not specified");
98327e58 1112 }
706587fc 1113 return ($url, $path);
98327e58 1114 }
706587fc 1115 return ($path, '');
98327e58
EW
1116}
1117
9d55b41a 1118sub complete_url_ls_init {
706587fc
EW
1119 my ($ra, $repo_path, $switch, $pfx) = @_;
1120 unless ($repo_path) {
9d55b41a
EW
1121 print STDERR "W: $switch not specified\n";
1122 return;
1123 }
706587fc
EW
1124 $repo_path =~ s#/+$##;
1125 if ($repo_path =~ m#^[a-z\+]+://#) {
1126 $ra = Git::SVN::Ra->new($repo_path);
1127 $repo_path = '';
e7db67e6 1128 } else {
706587fc 1129 $repo_path =~ s#^/+##;
e7db67e6 1130 unless ($ra) {
706587fc 1131 fatal("E: '$repo_path' is not a complete URL ",
207f1a75 1132 "and a separate URL is not specified");
8164b652 1133 }
e7db67e6 1134 }
706587fc 1135 my $url = $ra->{url};
b4d57e5e
EW
1136 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1137 my $k = "svn-remote.$gs->{repo_id}.url";
1138 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1139 if ($orig_url && ($orig_url ne $gs->{url})) {
1140 die "$k already set: $orig_url\n",
1141 "wanted to set to: $gs->{url}\n";
88cf4107 1142 }
b4d57e5e 1143 command_oneline('config', $k, $gs->{url}) unless $orig_url;
ed0b9d43 1144 my $remote_path = "$ra->{svn_path}/$repo_path";
b4d57e5e
EW
1145 $remote_path =~ s#/+#/#g;
1146 $remote_path =~ s#^/##g;
ed0b9d43 1147 $remote_path .= "/*" if $remote_path !~ /\*/;
b4d57e5e
EW
1148 my ($n) = ($switch =~ /^--(\w+)/);
1149 if (length $pfx && $pfx !~ m#/$#) {
1150 die "--prefix='$pfx' must have a trailing slash '/'\n";
9d55b41a 1151 }
570d35c2
MG
1152 command_noisy('config',
1153 "svn-remote.$gs->{repo_id}.$n",
1154 "$remote_path:refs/remotes/$pfx*" .
1155 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
9d55b41a
EW
1156}
1157
aef4e921
EW
1158sub verify_ref {
1159 my ($ref) = @_;
2c5c1d53
EW
1160 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1161 { STDERR => 0 }); };
aef4e921
EW
1162}
1163
a5e0cedc 1164sub get_tree_from_treeish {
cf52b8f0 1165 my ($treeish) = @_;
44320b9e 1166 # $treeish can be a symbolic ref, too:
aef4e921 1167 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
1168 my $expected;
1169 while ($type eq 'tag') {
aef4e921 1170 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
1171 }
1172 if ($type eq 'commit') {
aef4e921
EW
1173 $expected = (grep /^tree /, command(qw/cat-file commit/,
1174 $treeish))[0];
44320b9e 1175 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
1176 die "Unable to get tree from $treeish\n" unless $expected;
1177 } elsif ($type eq 'tree') {
1178 $expected = $treeish;
1179 } else {
1180 die "$treeish is a $type, expected tree, tag or commit\n";
1181 }
a5e0cedc
EW
1182 return $expected;
1183}
1184
44320b9e
EW
1185sub get_commit_entry {
1186 my ($treeish) = shift;
1187 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1188 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1189 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1190 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 1191
44320b9e 1192 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 1193 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 1194 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 1195 $type, $treeish);
3397f9df 1196 my $in_msg = 0;
6aa9ba14
AP
1197 my $author;
1198 my $saw_from = 0;
328eb9b3 1199 my $msgbuf = "";
3397f9df
EW
1200 while (<$msg_fh>) {
1201 if (!$in_msg) {
1202 $in_msg = 1 if (/^\s*$/);
6aa9ba14 1203 $author = $1 if (/^author (.*>)/);
df746c5a 1204 } elsif (/^git-svn-id: /) {
44320b9e
EW
1205 # skip this for now, we regenerate the
1206 # correct one on re-fetch anyways
1207 # TODO: set *:merge properties or like...
3397f9df 1208 } else {
6aa9ba14
AP
1209 if (/^From:/ || /^Signed-off-by:/) {
1210 $saw_from = 1;
1211 }
328eb9b3 1212 $msgbuf .= $_;
3397f9df
EW
1213 }
1214 }
328eb9b3 1215 $msgbuf =~ s/\s+$//s;
6aa9ba14
AP
1216 if ($Git::SVN::_add_author_from && defined($author)
1217 && !$saw_from) {
328eb9b3 1218 $msgbuf .= "\n\nFrom: $author";
6aa9ba14 1219 }
328eb9b3 1220 print $log_fh $msgbuf or croak $!;
aef4e921 1221 command_close_pipe($msg_fh, $ctx);
3397f9df 1222 }
44320b9e 1223 close $log_fh or croak $!;
3397f9df
EW
1224
1225 if ($_edit || ($type eq 'tree')) {
1226 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
1227 # TODO: strip out spaces, comments, like git-commit.sh
1228 system($editor, $commit_editmsg);
3397f9df 1229 }
44320b9e 1230 rename $commit_editmsg, $commit_msg or croak $!;
16fc08e2 1231 {
b510df8a 1232 require Encode;
16fc08e2
EW
1233 # SVN requires messages to be UTF-8 when entering the repo
1234 local $/;
1235 open $log_fh, '<', $commit_msg or croak $!;
1236 binmode $log_fh;
1237 chomp($log_entry{log} = <$log_fh>);
1238
b510df8a
EW
1239 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1240 my $msg = $log_entry{log};
1241
1242 eval { $msg = Encode::decode($enc, $msg, 1) };
1243 if ($@) {
1244 die "Could not decode as $enc:\n", $msg,
1245 "\nPerhaps you need to set i18n.commitencoding\n";
16fc08e2 1246 }
b510df8a
EW
1247
1248 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1249 die "Could not encode as UTF-8:\n$msg\n" if $@;
1250
1251 $log_entry{log} = $msg;
1252
16fc08e2
EW
1253 close $log_fh or croak $!;
1254 }
44320b9e
EW
1255 unlink $commit_msg;
1256 \%log_entry;
a5e0cedc
EW
1257}
1258
3397f9df
EW
1259sub s_to_file {
1260 my ($str, $file, $mode) = @_;
1261 open my $fd,'>',$file or croak $!;
1262 print $fd $str,"\n" or croak $!;
1263 close $fd or croak $!;
1264 chmod ($mode &~ umask, $file) if (defined $mode);
1265}
1266
1267sub file_to_s {
1268 my $file = shift;
1269 open my $fd,'<',$file or croak "$!: file: $file\n";
1270 local $/;
1271 my $ret = <$fd>;
1272 close $fd or croak $!;
1273 $ret =~ s/\s*$//s;
1274 return $ret;
1275}
1276
eeb0abe0
EW
1277# '<svn username> = real-name <email address>' mapping based on git-svnimport:
1278sub load_authors {
1279 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 1280 my $log = $cmd eq 'log';
eeb0abe0
EW
1281 while (<$authors>) {
1282 chomp;
575d025c 1283 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 1284 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
1285 if ($log) {
1286 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1287 } else {
1288 $users{$user} = [$name, $email];
1289 }
79bb8d88
EW
1290 }
1291 close $authors or croak $!;
1292}
1293
e0d10e1c 1294# convert GetOpt::Long specs for use by git-config
b8c92cad 1295sub read_repo_config {
706587fc 1296 return unless -d $ENV{GIT_DIR};
b8c92cad 1297 my $opts = shift;
97ae0911 1298 my @config_only;
b8c92cad 1299 foreach my $o (keys %$opts) {
97ae0911
EW
1300 # if we have mixedCase and a long option-only, then
1301 # it's a config-only variable that we don't need for
1302 # the command-line.
1303 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
b8c92cad 1304 my $v = $opts->{$o};
97ae0911 1305 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
b8c92cad 1306 $key =~ s/-//g;
225f1d0c 1307 my $arg = 'git config';
b8c92cad
EW
1308 $arg .= ' --int' if ($o =~ /[:=]i$/);
1309 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1310 if (ref $v eq 'ARRAY') {
1311 chomp(my @tmp = `$arg --get-all svn.$key`);
1312 @$v = @tmp if @tmp;
1313 } else {
1314 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 1315 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
1316 $$v = $tmp;
1317 }
1318 }
1319 }
97ae0911 1320 delete @$opts{@config_only} if @config_only;
b8c92cad
EW
1321}
1322
79bb8d88 1323sub extract_metadata {
c1927a85 1324 my $id = shift or return (undef, undef, undef);
3dfab993 1325 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
79bb8d88 1326 \s([a-f\d\-]+)$/x);
e70dc780 1327 if (!defined $rev || !$uuid || !$url) {
79bb8d88 1328 # some of the original repositories I made had
82e5a82f 1329 # identifiers like this:
3dfab993 1330 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
79bb8d88
EW
1331 }
1332 return ($url, $rev, $uuid);
1333}
1334
c1927a85
EW
1335sub cmt_metadata {
1336 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 1337 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
1338}
1339
6ea42032
BB
1340sub cmt_sha2rev_batch {
1341 my %s2r;
1342 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1343 my $list = shift;
1344
1345 foreach my $sha (@{$list}) {
1346 my $first = 1;
1347 my $size = 0;
1348 print $out $sha, "\n";
1349
1350 while (my $line = <$in>) {
1351 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1352 last;
1353 } elsif ($first &&
1354 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1355 $first = 0;
1356 $size = $1;
1357 next;
1358 } elsif ($line =~ /^(git-svn-id: )/) {
1359 my (undef, $rev, undef) =
1360 extract_metadata($line);
1361 $s2r{$sha} = $rev;
1362 }
1363
1364 $size -= length($line);
1365 last if ($size == 0);
1366 }
1367 }
1368
1369 command_close_bidi_pipe($pid, $in, $out, $ctx);
1370
1371 return \%s2r;
1372}
1373
905f8b7d
EW
1374sub working_head_info {
1375 my ($head, $refs) = @_;
b6309ac2 1376 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
05b4df31 1377 my ($fh, $ctx) = command_output_pipe(@args, $head);
3dfab993 1378 my $hash;
40cb8f8f 1379 my %max;
3dfab993
SV
1380 while (<$fh>) {
1381 if ( m{^commit ($::sha1)$} ) {
1382 unshift @$refs, $hash if $hash and $refs;
1383 $hash = $1;
1384 next;
1385 }
1386 next unless s{^\s*(git-svn-id:)}{$1};
1387 my ($url, $rev, $uuid) = extract_metadata($_);
13c823fb 1388 if (defined $url && defined $rev) {
40cb8f8f 1389 next if $max{$url} and $max{$url} < $rev;
13c823fb 1390 if (my $gs = Git::SVN->find_by_url($url)) {
63c56022 1391 my $c = $gs->rev_map_get($rev, $uuid);
b03c7a63 1392 if ($c && $c eq $hash) {
13c823fb
EW
1393 close $fh; # break the pipe
1394 return ($url, $rev, $uuid, $gs);
40cb8f8f 1395 } else {
060610c5 1396 $max{$url} ||= $gs->rev_map_max;
13c823fb
EW
1397 }
1398 }
1399 }
905f8b7d 1400 }
13c823fb
EW
1401 command_close_pipe($fh, $ctx);
1402 (undef, undef, undef, undef);
905f8b7d
EW
1403}
1404
733a65aa
EW
1405sub read_commit_parents {
1406 my ($parents, $c) = @_;
7b02b85a
EW
1407 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1408 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1409 @{$parents->{$c}} = split(/ /, $p);
733a65aa
EW
1410}
1411
1412sub linearize_history {
1413 my ($gs, $refs) = @_;
1414 my %parents;
1415 foreach my $c (@$refs) {
1416 read_commit_parents(\%parents, $c);
1417 }
1418
1419 my @linear_refs;
1420 my %skip = ();
1421 my $last_svn_commit = $gs->last_commit;
1422 foreach my $c (reverse @$refs) {
1423 next if $c eq $last_svn_commit;
1424 last if $skip{$c};
1425
1426 unshift @linear_refs, $c;
1427 $skip{$c} = 1;
1428
1429 # we only want the first parent to diff against for linear
1430 # history, we save the rest to inject when we finalize the
1431 # svn commit
1432 my $fp_a = verify_ref("$c~1");
1433 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1434 if (!$fp_a || !$fp_b) {
1435 die "Commit $c\n",
1436 "has no parent commit, and therefore ",
1437 "nothing to diff against.\n",
1438 "You should be working from a repository ",
1439 "originally created by git-svn\n";
1440 }
1441 if ($fp_a ne $fp_b) {
1442 die "$c~1 = $fp_a, however parsing commit $c ",
1443 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1444 }
1445
1446 foreach my $p (@{$parents{$c}}) {
1447 $skip{$p} = 1;
1448 }
1449 }
1450 (\@linear_refs, \%parents);
1451}
1452
e6fefa92
DK
1453sub find_file_type_and_diff_status {
1454 my ($path) = @_;
107cee50 1455 return ('dir', '') if $path eq '';
e6fefa92
DK
1456
1457 my $diff_output =
1458 command_oneline(qw(diff --cached --name-status --), $path) || "";
1459 my $diff_status = (split(' ', $diff_output))[0] || "";
1460
1461 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1462
1463 return (undef, undef) if !$diff_status && !$ls_tree;
1464
1465 if ($diff_status eq "A") {
1466 return ("link", $diff_status) if -l $path;
1467 return ("dir", $diff_status) if -d $path;
1468 return ("file", $diff_status);
1469 }
1470
1471 my $mode = (split(' ', $ls_tree))[0] || "";
1472
1473 return ("link", $diff_status) if $mode eq "120000";
1474 return ("dir", $diff_status) if $mode eq "040000";
1475 return ("file", $diff_status);
1476}
1477
b2b3ada7
DK
1478sub md5sum {
1479 my $arg = shift;
1480 my $ref = ref $arg;
1481 my $md5 = Digest::MD5->new();
0b19138b 1482 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
b2b3ada7
DK
1483 $md5->addfile($arg) or croak $!;
1484 } elsif ($ref eq 'SCALAR') {
1485 $md5->add($$arg) or croak $!;
1486 } elsif (!$ref) {
1487 $md5->add($arg) or croak $!;
1488 } else {
1489 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1490 }
1491 return $md5->hexdigest();
1492}
1493
9b981fc6
EW
1494package Git::SVN;
1495use strict;
1496use warnings;
060610c5
EW
1497use Fcntl qw/:DEFAULT :seek/;
1498use constant rev_map_fmt => 'NH40';
ecc712dd 1499use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
62e349d2 1500 $_repack $_repack_flags $_use_svm_props $_head
70ae04e4 1501 $_use_svnsync_props $no_reuse_existing $_minimize_url
e82f0d73 1502 $_use_log_author $_add_author_from $_localtime/;
9b981fc6
EW
1503use Carp qw/croak/;
1504use File::Path qw/mkpath/;
373274f9 1505use File::Copy qw/copy/;
9b981fc6
EW
1506use IPC::Open3;
1507
94bc914c
KW
1508my ($_gc_nr, $_gc_period);
1509
9b981fc6
EW
1510# properties that we do not log:
1511my %SKIP_PROP;
1512BEGIN {
1513 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1514 svn:special svn:executable
1515 svn:entry:committed-rev
1516 svn:entry:last-author
1517 svn:entry:uuid
1518 svn:entry:committed-date/;
91b03282
EW
1519
1520 # some options are read globally, but can be overridden locally
1521 # per [svn-remote "..."] section. Command-line options will *NOT*
1522 # override options set in an [svn-remote "..."] section
c5f71ad0
SV
1523 no strict 'refs';
1524 for my $option (qw/follow_parent no_metadata use_svm_props
1525 use_svnsync_props/) {
1526 my $key = $option;
91b03282 1527 $key =~ tr/_//d;
c5f71ad0
SV
1528 my $prop = "-$option";
1529 *$option = sub {
1530 my ($self) = @_;
1531 return $self->{$prop} if exists $self->{$prop};
1532 my $k = "svn-remote.$self->{repo_id}.$key";
1533 eval { command_oneline(qw/config --get/, $k) };
1534 if ($@) {
1535 $self->{$prop} = ${"Git::SVN::_$option"};
91b03282 1536 } else {
c5f71ad0
SV
1537 my $v = command_oneline(qw/config --bool/,$k);
1538 $self->{$prop} = $v eq 'false' ? 0 : 1;
91b03282 1539 }
c5f71ad0
SV
1540 return $self->{$prop};
1541 }
91b03282 1542 }
9b981fc6
EW
1543}
1544
0b19138b 1545
321b1842
EW
1546my (%LOCKFILES, %INDEX_FILES);
1547END {
1548 unlink keys %LOCKFILES if %LOCKFILES;
1549 unlink keys %INDEX_FILES if %INDEX_FILES;
1550}
373274f9 1551
4bb9ed04
EW
1552sub resolve_local_globs {
1553 my ($url, $fetch, $glob_spec) = @_;
1554 return unless defined $glob_spec;
1555 my $ref = $glob_spec->{ref};
1556 my $path = $glob_spec->{path};
1557 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1558 next unless m#^refs/remotes/$ref->{regex}$#;
1559 my $p = $1;
bf655fd7
RE
1560 my $pathname = desanitize_refname($path->full_path($p));
1561 my $refname = desanitize_refname($ref->full_path($p));
4bb9ed04
EW
1562 if (my $existing = $fetch->{$pathname}) {
1563 if ($existing ne $refname) {
1564 die "Refspec conflict:\n",
1565 "existing: refs/remotes/$existing\n",
1566 " globbed: refs/remotes/$refname\n";
1567 }
1568 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 1569 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
1570 "refs/remotes/$refname: '$url' not found in '$u'\n";
1571 if ($pathname ne $u) {
1572 warn "W: Refspec glob conflict ",
1573 "(ref: refs/remotes/$refname):\n",
1574 "expected path: $pathname\n",
1575 " real path: $u\n",
1576 "Continuing ahead with $u\n";
1577 next;
1578 }
1579 } else {
4bb9ed04
EW
1580 $fetch->{$pathname} = $refname;
1581 }
1582 }
1583}
1584
e98671e5
EW
1585sub parse_revision_argument {
1586 my ($base, $head) = @_;
1587 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1588 return ($base, $head);
1589 }
1590 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1591 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1592 return ($head, $head) if ($::_revision eq 'HEAD');
1593 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1594 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1595 die "revision argument: $::_revision not understood by git-svn\n";
1596}
1597
0af9c9f9 1598sub fetch_all {
4bb9ed04 1599 my ($repo_id, $remotes) = @_;
905f8b7d
EW
1600 if (ref $repo_id) {
1601 my $gs = $repo_id;
1602 $repo_id = undef;
1603 $repo_id = $gs->{repo_id};
1604 }
1605 $remotes ||= read_all_remotes();
7447b4bc
EW
1606 my $remote = $remotes->{$repo_id} or
1607 die "[svn-remote \"$repo_id\"] unknown\n";
e518192f 1608 my $fetch = $remote->{fetch};
7447b4bc 1609 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
e518192f 1610 my (@gs, @globs);
0af9c9f9 1611 my $ra = Git::SVN::Ra->new($url);
26a62d57 1612 my $uuid = $ra->get_uuid;
0af9c9f9 1613 my $head = $ra->get_latest_revnum;
28710f74 1614 my $base = defined $fetch ? $head : 0;
e518192f
EW
1615
1616 # read the max revs for wildcard expansion (branches/*, tags/*)
1617 foreach my $t (qw/branches tags/) {
1618 defined $remote->{$t} or next;
1619 push @globs, $remote->{$t};
93f2689c
EW
1620 my $max_rev = eval { tmp_config(qw/--int --get/,
1621 "svn-remote.$repo_id.${t}-maxRev") };
1622 if (defined $max_rev && ($max_rev < $base)) {
1623 $base = $max_rev;
d6d3346b
EW
1624 } elsif (!defined $max_rev) {
1625 $base = 0;
e518192f
EW
1626 }
1627 }
1628
db03cd24
EW
1629 if ($fetch) {
1630 foreach my $p (sort keys %$fetch) {
1631 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
060610c5 1632 my $lr = $gs->rev_map_max;
db03cd24
EW
1633 if (defined $lr) {
1634 $base = $lr if ($lr < $base);
1635 }
1636 push @gs, $gs;
0af9c9f9 1637 }
0af9c9f9 1638 }
e98671e5
EW
1639
1640 ($base, $head) = parse_revision_argument($base, $head);
e518192f 1641 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
1642}
1643
47e39c55
EW
1644sub read_all_remotes {
1645 my $r = {};
63c56022
JA
1646 my $use_svm_props = eval { command_oneline(qw/config --bool
1647 svn.useSvmProps/) };
1648 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
8b8fc068 1649 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
61192165
AP
1650 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1651 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1652 die("svn-remote.$remote: remote ref '$_remote_ref' "
1653 . "must start with 'refs/remotes/'\n")
1654 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1655 my $remote_ref = $1;
46cf98ba
EW
1656 $local_ref =~ s{^/}{};
1657 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
63c56022
JA
1658 $r->{$remote}->{svm} = {} if $use_svm_props;
1659 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1660 $r->{$1}->{svm} = {};
47e39c55
EW
1661 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1662 $r->{$1}->{url} = $2;
4bb9ed04
EW
1663 } elsif (m!^(.+)\.(branches|tags)=
1664 (.*):refs/remotes/(.+)\s*$/!x) {
1665 my ($p, $g) = ($3, $4);
1666 my $rs = $r->{$1}->{$2} = {
e518192f 1667 t => $2,
93f2689c 1668 remote => $1,
4bb9ed04
EW
1669 path => Git::SVN::GlobSpec->new($p),
1670 ref => Git::SVN::GlobSpec->new($g) };
1671 if (length($rs->{ref}->{right}) != 0) {
1672 die "The '*' glob character must be the last ",
1673 "character of '$g'\n";
1674 }
47e39c55
EW
1675 }
1676 }
63c56022
JA
1677
1678 map {
1679 if (defined $r->{$_}->{svm}) {
1680 my $svm;
1681 eval {
1682 my $section = "svn-remote.$_";
1683 $svm = {
1684 source => tmp_config('--get',
1685 "$section.svm-source"),
1686 replace => tmp_config('--get',
1687 "$section.svm-replace"),
1688 }
1689 };
1690 $r->{$_}->{svm} = $svm;
1691 }
1692 } keys %$r;
1693
47e39c55
EW
1694 $r;
1695}
1696
ecc712dd 1697sub init_vars {
94bc914c 1698 $_gc_nr = $_gc_period = 1000;
af788a6e
KW
1699 if (defined $_repack || defined $_repack_flags) {
1700 warn "Repack options are obsolete; they have no effect.\n";
1701 }
ecc712dd
EW
1702}
1703
b805b44a 1704sub verify_remotes_sanity {
536c4b09 1705 return unless -d $ENV{GIT_DIR};
b805b44a
EW
1706 my %seen;
1707 foreach (command(qw/config -l/)) {
1708 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1709 if ($seen{$1}) {
1710 die "Remote ref refs/remote/$1 is tracked by",
1711 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1712 "Please resolve this ambiguity in ",
1713 "your git configuration file before ",
1714 "continuing\n";
1715 }
1716 $seen{$1} = $_;
1717 }
1718 }
1719}
1720
e6434f87
EW
1721sub find_existing_remote {
1722 my ($url, $remotes) = @_;
befc9adc 1723 return undef if $no_reuse_existing;
e6434f87
EW
1724 my $existing;
1725 foreach my $repo_id (keys %$remotes) {
1726 my $u = $remotes->{$repo_id}->{url} or next;
1727 next if $u ne $url;
1728 $existing = $repo_id;
1729 last;
1730 }
1731 $existing;
1732}
b805b44a 1733
e6434f87 1734sub init_remote_config {
d8115c51 1735 my ($self, $url, $no_write) = @_;
e6434f87
EW
1736 $url =~ s!/+$!!; # strip trailing slash
1737 my $r = read_all_remotes();
1738 my $existing = find_existing_remote($url, $r);
1739 if ($existing) {
e518192f
EW
1740 unless ($no_write) {
1741 print STDERR "Using existing ",
1742 "[svn-remote \"$existing\"]\n";
1743 }
e6434f87 1744 $self->{repo_id} = $existing;
4a1bb4c3 1745 } elsif ($_minimize_url) {
e6434f87
EW
1746 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1747 $existing = find_existing_remote($min_url, $r);
1748 if ($existing) {
e518192f
EW
1749 unless ($no_write) {
1750 print STDERR "Using existing ",
1751 "[svn-remote \"$existing\"]\n";
1752 }
e6434f87
EW
1753 $self->{repo_id} = $existing;
1754 }
1755 if ($min_url ne $url) {
e518192f
EW
1756 unless ($no_write) {
1757 print STDERR "Using higher level of URL: ",
1758 "$url => $min_url\n";
1759 }
e6434f87
EW
1760 my $old_path = $self->{path};
1761 $self->{path} = $url;
4e9f6cc7 1762 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
1763 if (length $old_path) {
1764 $self->{path} .= "/$old_path";
1765 }
1766 $url = $min_url;
1767 }
1768 }
1769 my $orig_url;
1770 if (!$existing) {
b805b44a 1771 # verify that we aren't overwriting anything:
e6434f87 1772 $orig_url = eval {
706587fc 1773 command_oneline('config', '--get',
e6434f87 1774 "svn-remote.$self->{repo_id}.url")
706587fc 1775 };
b805b44a 1776 if ($orig_url && ($orig_url ne $url)) {
e6434f87 1777 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
1778 "$orig_url\nwanted to set to: $url\n";
1779 }
9b981fc6 1780 }
e6434f87
EW
1781 my ($xrepo_id, $xpath) = find_ref($self->refname);
1782 if (defined $xpath) {
1783 die "svn-remote.$xrepo_id.fetch already set to track ",
1784 "$xpath:refs/remotes/", $self->refname, "\n";
1785 }
d8115c51
EW
1786 unless ($no_write) {
1787 command_noisy('config',
1788 "svn-remote.$self->{repo_id}.url", $url);
46cf98ba 1789 $self->{path} =~ s{^/}{};
d8115c51
EW
1790 command_noisy('config', '--add',
1791 "svn-remote.$self->{repo_id}.fetch",
1792 "$self->{path}:".$self->refname);
1793 }
9b981fc6 1794 $self->{url} = $url;
e6434f87
EW
1795}
1796
a8ae2623
EW
1797sub find_by_url { # repos_root and, path are optional
1798 my ($class, $full_url, $repos_root, $path) = @_;
56973d20 1799
1a97a506 1800 return undef unless defined $full_url;
56973d20
AR
1801 remove_username($full_url);
1802 remove_username($repos_root) if defined $repos_root;
a8ae2623
EW
1803 my $remotes = read_all_remotes();
1804 if (defined $full_url && defined $repos_root && !defined $path) {
1805 $path = $full_url;
1806 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1807 }
1808 foreach my $repo_id (keys %$remotes) {
1809 my $u = $remotes->{$repo_id}->{url} or next;
56973d20 1810 remove_username($u);
a8ae2623
EW
1811 next if defined $repos_root && $repos_root ne $u;
1812
1813 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1814 foreach (qw/branches tags/) {
1815 resolve_local_globs($u, $fetch,
1816 $remotes->{$repo_id}->{$_});
1817 }
1818 my $p = $path;
0bb91d9a 1819 my $rwr = rewrite_root({repo_id => $repo_id});
63c56022
JA
1820 my $svm = $remotes->{$repo_id}->{svm}
1821 if defined $remotes->{$repo_id}->{svm};
a8ae2623
EW
1822 unless (defined $p) {
1823 $p = $full_url;
0bb91d9a 1824 my $z = $u;
63c56022 1825 my $prefix = '';
0bb91d9a
JG
1826 if ($rwr) {
1827 $z = $rwr;
1b7e543a 1828 remove_username($z);
63c56022
JA
1829 } elsif (defined $svm) {
1830 $z = $svm->{source};
1831 $prefix = $svm->{replace};
1832 $prefix =~ s#^\Q$u\E(?:/|$)##;
1833 $prefix =~ s#/$##;
0bb91d9a 1834 }
63c56022 1835 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
a8ae2623
EW
1836 }
1837 foreach my $f (keys %$fetch) {
1838 next if $f ne $p;
1839 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1840 }
1841 }
1842 undef;
1843}
1844
e6434f87 1845sub init {
d8115c51 1846 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
1847 my $self = _new($class, $repo_id, $ref_id, $path);
1848 if (defined $url) {
d8115c51 1849 $self->init_remote_config($url, $no_write);
e6434f87 1850 }
9b981fc6
EW
1851 $self;
1852}
1853
706587fc
EW
1854sub find_ref {
1855 my ($ref_id) = @_;
1856 foreach (command(qw/config -l/)) {
1857 next unless m!^svn-remote\.(.+)\.fetch=
1858 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1859 my ($repo_id, $path, $ref) = ($1, $2, $3);
1860 if ($ref eq $ref_id) {
1861 $path = '' if ($path =~ m#^\./?#);
1862 return ($repo_id, $path);
1863 }
1864 }
1865 (undef, undef, undef);
1866}
1867
9b981fc6 1868sub new {
706587fc
EW
1869 my ($class, $ref_id, $repo_id, $path) = @_;
1870 if (defined $ref_id && !defined $repo_id && !defined $path) {
1871 ($repo_id, $path) = find_ref($ref_id);
1872 if (!defined $repo_id) {
1873 die "Could not find a \"svn-remote.*.fetch\" key ",
1874 "in the repository configuration matching: ",
1875 "refs/remotes/$ref_id\n";
1876 }
1877 }
1878 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
1879 if (!defined $self->{path} || !length $self->{path}) {
1880 my $fetch = command_oneline('config', '--get',
1881 "svn-remote.$repo_id.fetch",
1882 ":refs/remotes/$ref_id\$") or
1883 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1884 "\":refs/remotes/$ref_id\$\" in config\n";
1885 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1886 }
706587fc
EW
1887 $self->{url} = command_oneline('config', '--get',
1888 "svn-remote.$repo_id.url") or
1889 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
d6d3346b 1890 $self->rebuild;
9b981fc6
EW
1891 $self;
1892}
1893
bf655fd7
RE
1894sub refname {
1895 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1896
1897 # It cannot end with a slash /, we'll throw up on this because
1898 # SVN can't have directories with a slash in their name, either:
1899 if ($refname =~ m{/$}) {
1900 die "ref: '$refname' ends with a trailing slash, this is ",
1901 "not permitted by git nor Subversion\n";
1902 }
1903
1904 # It cannot have ASCII control character space, tilde ~, caret ^,
1905 # colon :, question-mark ?, asterisk *, space, or open bracket [
1906 # anywhere.
1907 #
1908 # Additionally, % must be escaped because it is used for escaping
1909 # and we want our escaped refname to be reversible
1910 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1911
1912 # no slash-separated component can begin with a dot .
1913 # /.* becomes /%2E*
1914 $refname =~ s{/\.}{/%2E}g;
1915
1916 # It cannot have two consecutive dots .. anywhere
1917 # .. becomes %2E%2E
1918 $refname =~ s{\.\.}{%2E%2E}g;
1919
1920 return $refname;
1921}
1922
1923sub desanitize_refname {
1924 my ($refname) = @_;
1925 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1926 return $refname;
1927}
9b981fc6 1928
26a62d57
EW
1929sub svm_uuid {
1930 my ($self) = @_;
1931 return $self->{svm}->{uuid} if $self->svm;
1932 $self->ra;
1933 unless ($self->{svm}) {
1934 die "SVM UUID not cached, and reading remotely failed\n";
1935 }
1936 $self->{svm}->{uuid};
1937}
8a49ee97 1938
26a62d57
EW
1939sub svm {
1940 my ($self) = @_;
1941 return $self->{svm} if $self->{svm};
1942 my $svm;
8a49ee97
EW
1943 # see if we have it in our config, first:
1944 eval {
26a62d57
EW
1945 my $section = "svn-remote.$self->{repo_id}";
1946 $svm = {
93f2689c
EW
1947 source => tmp_config('--get', "$section.svm-source"),
1948 uuid => tmp_config('--get', "$section.svm-uuid"),
befc9adc 1949 replace => tmp_config('--get', "$section.svm-replace"),
8a49ee97
EW
1950 }
1951 };
befc9adc
EW
1952 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1953 $self->{svm} = $svm;
1954 }
26a62d57
EW
1955 $self->{svm};
1956}
1957
1958sub _set_svm_vars {
1959 my ($self, $ra) = @_;
db03cd24
EW
1960 return $ra if $self->svm;
1961
1962 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
befc9adc 1963 "(svm:source, svm:uuid) ",
db03cd24
EW
1964 "from the following URLs:\n" );
1965 sub read_svm_props {
befc9adc
EW
1966 my ($self, $ra, $path, $r) = @_;
1967 my $props = ($ra->get_dir($path, $r))[2];
db03cd24 1968 my $src = $props->{'svm:source'};
db03cd24 1969 my $uuid = $props->{'svm:uuid'};
befc9adc 1970 return undef if (!$src || !$uuid);
26a62d57 1971
befc9adc 1972 chomp($src, $uuid);
26a62d57 1973
db03cd24
EW
1974 $uuid =~ m{^[0-9a-f\-]{30,}$}
1975 or die "doesn't look right - svm:uuid is '$uuid'\n";
befc9adc
EW
1976
1977 # the '!' is used to mark the repos_root!/relative/path
1978 $src =~ s{/?!/?}{/};
db03cd24 1979 $src =~ s{/+$}{}; # no trailing slashes please
befc9adc 1980 # username is of no interest
8a49ee97 1981 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
8a49ee97 1982
befc9adc
EW
1983 my $replace = $ra->{url};
1984 $replace .= "/$path" if length $path;
1985
db03cd24 1986 my $section = "svn-remote.$self->{repo_id}";
befc9adc
EW
1987 tmp_config("$section.svm-source", $src);
1988 tmp_config("$section.svm-replace", $replace);
1989 tmp_config("$section.svm-uuid", $uuid);
1990 $self->{svm} = {
1991 source => $src,
1992 uuid => $uuid,
1993 replace => $replace
1994 };
db03cd24
EW
1995 }
1996
1997 my $r = $ra->get_latest_revnum;
1998 my $path = $self->{path};
befc9adc 1999 my %tried;
db03cd24 2000 while (length $path) {
befc9adc
EW
2001 unless ($tried{"$self->{url}/$path"}) {
2002 return $ra if $self->read_svm_props($ra, $path, $r);
2003 $tried{"$self->{url}/$path"} = 1;
db03cd24 2004 }
befc9adc 2005 $path =~ s#/?[^/]+$##;
8a49ee97 2006 }
befc9adc
EW
2007 die "Path: '$path' should be ''\n" if $path ne '';
2008 return $ra if $self->read_svm_props($ra, $path, $r);
2009 $tried{"$self->{url}/$path"} = 1;
db03cd24
EW
2010
2011 if ($ra->{repos_root} eq $self->{url}) {
befc9adc 2012 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
2013 }
2014
2015 # nope, make sure we're connected to the repository root:
2016 my $ok;
2017 my @tried_b;
2018 $path = $ra->{svn_path};
db03cd24
EW
2019 $ra = Git::SVN::Ra->new($ra->{repos_root});
2020 while (length $path) {
befc9adc
EW
2021 unless ($tried{"$ra->{url}/$path"}) {
2022 $ok = $self->read_svm_props($ra, $path, $r);
2023 last if $ok;
2024 $tried{"$ra->{url}/$path"} = 1;
2025 }
2026 $path =~ s#/?[^/]+$##;
db03cd24 2027 }
befc9adc
EW
2028 die "Path: '$path' should be ''\n" if $path ne '';
2029 $ok ||= $self->read_svm_props($ra, $path, $r);
2030 $tried{"$ra->{url}/$path"} = 1;
db03cd24 2031 if (!$ok) {
befc9adc 2032 die @err, (map { " $_\n" } keys %tried), "\n";
db03cd24
EW
2033 }
2034 Git::SVN::Ra->new($self->{url});
8a49ee97
EW
2035}
2036
62e349d2
EW
2037sub svnsync {
2038 my ($self) = @_;
2039 return $self->{svnsync} if $self->{svnsync};
2040
2041 if ($self->no_metadata) {
2042 die "Can't have both 'noMetadata' and ",
2043 "'useSvnsyncProps' options set!\n";
2044 }
2045 if ($self->rewrite_root) {
2046 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2047 "options set!\n";
2048 }
2049
2050 my $svnsync;
2051 # see if we have it in our config, first:
2052 eval {
2053 my $section = "svn-remote.$self->{repo_id}";
98fa5b68
EW
2054
2055 my $url = tmp_config('--get', "$section.svnsync-url");
2056 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2057 die "doesn't look right - svn:sync-from-url is '$url'\n";
2058
2059 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2060 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2061 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2062
2063 $svnsync = { url => $url, uuid => $uuid }
62e349d2
EW
2064 };
2065 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2066 return $self->{svnsync} = $svnsync;
2067 }
2068
2069 my $err = "useSvnsyncProps set, but failed to read " .
2070 "svnsync property: svn:sync-from-";
2071 my $rp = $self->ra->rev_proplist(0);
2072
2073 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
98fa5b68 2074 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
62e349d2
EW
2075 die "doesn't look right - svn:sync-from-url is '$url'\n";
2076
2077 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
98fa5b68 2078 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
62e349d2
EW
2079 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2080
2081 my $section = "svn-remote.$self->{repo_id}";
2082 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2083 tmp_config('--add', "$section.svnsync-url", $url);
2084 return $self->{svnsync} = { url => $url, uuid => $uuid };
2085}
2086
26a62d57
EW
2087# this allows us to memoize our SVN::Ra UUID locally and avoid a
2088# remote lookup (useful for 'git svn log').
2089sub ra_uuid {
2090 my ($self) = @_;
2091 unless ($self->{ra_uuid}) {
2092 my $key = "svn-remote.$self->{repo_id}.uuid";
2093 my $uuid = eval { tmp_config('--get', $key) };
2094 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2095 $self->{ra_uuid} = $uuid;
2096 } else {
2097 die "ra_uuid called without URL\n" unless $self->{url};
2098 $self->{ra_uuid} = $self->ra->get_uuid;
2099 tmp_config('--add', $key, $self->{ra_uuid});
2100 }
2101 }
2102 $self->{ra_uuid};
2103}
2104
a5460eb7
EW
2105sub _set_repos_root {
2106 my ($self, $repos_root) = @_;
2107 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2108 $repos_root ||= $self->ra->{repos_root};
2109 tmp_config($k, $repos_root);
2110 $repos_root;
2111}
2112
2113sub repos_root {
2114 my ($self) = @_;
2115 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2116 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2117}
2118
9b981fc6
EW
2119sub ra {
2120 my ($self) = shift;
8a49ee97 2121 my $ra = Git::SVN::Ra->new($self->{url});
a5460eb7 2122 $self->_set_repos_root($ra->{repos_root});
91b03282
EW
2123 if ($self->use_svm_props && !$self->{svm}) {
2124 if ($self->no_metadata) {
97ae0911
EW
2125 die "Can't have both 'noMetadata' and ",
2126 "'useSvmProps' options set!\n";
62e349d2
EW
2127 } elsif ($self->use_svnsync_props) {
2128 die "Can't have both 'useSvnsyncProps' and ",
2129 "'useSvmProps' options set!\n";
91b03282 2130 }
26a62d57 2131 $ra = $self->_set_svm_vars($ra);
8a49ee97
EW
2132 $self->{-want_revprops} = 1;
2133 }
2134 $ra;
9b981fc6
EW
2135}
2136
15710b6f
EW
2137sub rel_path {
2138 my ($self) = @_;
2139 my $repos_root = $self->ra->{repos_root};
2140 return $self->{path} if ($self->{url} eq $repos_root);
0b59451c
EW
2141 my $url = $self->{url} .
2142 (length $self->{path} ? "/$self->{path}" : $self->{path});
2143 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2144 $url;
15710b6f
EW
2145}
2146
01bdab84
BS
2147# prop_walk(PATH, REV, SUB)
2148# -------------------------
2149# Recursively traverse PATH at revision REV and invoke SUB for each
2150# directory that contains a SVN property. SUB will be invoked as
2151# follows: &SUB(gs, path, props); where `gs' is this instance of
2152# Git::SVN, `path' the path to the directory where the properties
2153# `props' were found. The `path' will be relative to point of checkout,
2154# that is, if url://repo/trunk is the current Git branch, and that
2155# directory contains a sub-directory `d', SUB will be invoked with `/d/'
2156# as `path' (note the trailing `/').
2157sub prop_walk {
2158 my ($self, $path, $rev, $sub) = @_;
2159
35cda061 2160 $path =~ s#^/##;
01bdab84
BS
2161 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2162 $path =~ s#^/*#/#g;
9b981fc6 2163 my $p = $path;
01bdab84
BS
2164 # Strip the irrelevant part of the path.
2165 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2166 # Ensure the path is terminated by a `/'.
2167 $p =~ s#/*$#/#;
2168
2169 # The properties contain all the internal SVN stuff nobody
2170 # (usually) cares about.
2171 my $interesting_props = 0;
2172 foreach (keys %{$props}) {
2173 # If it doesn't start with `svn:', it must be a
2174 # user-defined property.
2175 ++$interesting_props and next if $_ !~ /^svn:/;
2176 # FIXME: Fragile, if SVN adds new public properties,
2177 # this needs to be updated.
2178 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2179 |eol-style|mime-type
2180 |externals|needs-lock)$/x;
2181 }
2182 &$sub($self, $p, $props) if $interesting_props;
2183
9b981fc6 2184 foreach (sort keys %$dirent) {
0dc03d6a 2185 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
b7166cce 2186 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
9b981fc6
EW
2187 }
2188}
2189
3ebe8df7
EW
2190sub last_rev { ($_[0]->last_rev_commit)[0] }
2191sub last_commit { ($_[0]->last_rev_commit)[1] }
2192
9b981fc6
EW
2193# returns the newest SVN revision number and newest commit SHA1
2194sub last_rev_commit {
2195 my ($self) = @_;
2196 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2197 return ($self->{last_rev}, $self->{last_commit});
2198 }
d2866f9e 2199 my $c = ::verify_ref($self->refname.'^0');
91b03282 2200 if ($c && !$self->use_svm_props && !$self->no_metadata) {
d2866f9e 2201 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
2202 if (defined $rev) {
2203 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2204 return ($rev, $c);
2205 }
2206 }
060610c5
EW
2207 my $map_path = $self->map_path;
2208 unless (-e $map_path) {
26a62d57
EW
2209 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2210 return (undef, undef);
2211 }
66ab84b9 2212 my ($rev, $commit) = $self->rev_map_max(1);
060610c5
EW
2213 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2214 return ($rev, $commit);
9b981fc6
EW
2215}
2216
3ebe8df7
EW
2217sub get_fetch_range {
2218 my ($self, $min, $max) = @_;
2219 $max ||= $self->ra->get_latest_revnum;
060610c5 2220 $min ||= $self->rev_map_max;
3ebe8df7 2221 (++$min, $max);
9b981fc6
EW
2222}
2223
8a49ee97 2224sub tmp_config {
93f2689c 2225 my (@args) = @_;
b7e5348c
EW
2226 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2227 my $config = "$ENV{GIT_DIR}/svn/.metadata";
38570a47 2228 if (! -f $config && -f $old_def_config) {
b7e5348c
EW
2229 rename $old_def_config, $config or
2230 die "Failed rename $old_def_config => $config: $!\n";
2231 }
8a49ee97 2232 my $old_config = $ENV{GIT_CONFIG};
93f2689c 2233 $ENV{GIT_CONFIG} = $config;
8a49ee97 2234 $@ = undef;
b4d57e5e
EW
2235 my @ret = eval {
2236 unless (-f $config) {
2237 mkfile($config);
2238 open my $fh, '>', $config or
2239 die "Can't open $config: $!\n";
2240 print $fh "; This file is used internally by ",
2241 "git-svn\n" or die
2242 "Couldn't write to $config: $!\n";
2243 print $fh "; You should not have to edit it\n" or
2244 die "Couldn't write to $config: $!\n";
2245 close $fh or die "Couldn't close $config: $!\n";
2246 }
2247 command('config', @args);
2248 };
8a49ee97
EW
2249 my $err = $@;
2250 if (defined $old_config) {
2251 $ENV{GIT_CONFIG} = $old_config;
2252 } else {
2253 delete $ENV{GIT_CONFIG};
2254 }
2255 die $err if $err;
2256 wantarray ? @ret : $ret[0];
2257}
2258
9b981fc6
EW
2259sub tmp_index_do {
2260 my ($self, $sub) = @_;
2261 my $old_index = $ENV{GIT_INDEX_FILE};
2262 $ENV{GIT_INDEX_FILE} = $self->{index};
8a49ee97 2263 $@ = undef;
b4d57e5e
EW
2264 my @ret = eval {
2265 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2266 mkpath([$dir]) unless -d $dir;
2267 &$sub;
2268 };
8a49ee97
EW
2269 my $err = $@;
2270 if (defined $old_index) {
9b981fc6
EW
2271 $ENV{GIT_INDEX_FILE} = $old_index;
2272 } else {
2273 delete $ENV{GIT_INDEX_FILE};
2274 }
8a49ee97 2275 die $err if $err;
9b981fc6
EW
2276 wantarray ? @ret : $ret[0];
2277}
2278
2279sub assert_index_clean {
2280 my ($self, $treeish) = @_;
2281
2282 $self->tmp_index_do(sub {
2283 command_noisy('read-tree', $treeish) unless -e $self->{index};
2284 my $x = command_oneline('write-tree');
2285 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2286 /^tree ($::sha1)/mo);
e8d120bd
EW
2287 return if $y eq $x;
2288
2289 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2290 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2291 command_noisy('read-tree', $treeish);
9b981fc6
EW
2292 $x = command_oneline('write-tree');
2293 if ($y ne $x) {
2294 ::fatal "trees ($treeish) $y != $x\n",
207f1a75 2295 "Something is seriously wrong...";
9b981fc6
EW
2296 }
2297 });
2298}
2299
2300sub get_commit_parents {
0af9c9f9 2301 my ($self, $log_entry) = @_;
9b981fc6 2302 my (%seen, @ret, @tmp);
0af9c9f9
EW
2303 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2304 if (my $ip = $self->{inject_parents}) {
2305 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2306 push @tmp, $commit;
9b981fc6
EW
2307 }
2308 }
d2866f9e 2309 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
2310 push @tmp, $cur;
2311 }
733a65aa
EW
2312 if (my $ipd = $self->{inject_parents_dcommit}) {
2313 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2314 push @tmp, @$commit;
2315 }
2316 }
44320b9e 2317 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
2318 while (my $p = shift @tmp) {
2319 next if $seen{$p};
2320 $seen{$p} = 1;
2321 push @ret, $p;
2322 # MAXPARENT is defined to 16 in commit-tree.c:
2323 last if @ret >= 16;
2324 }
2325 if (@tmp) {
44320b9e 2326 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
2327 join("\n\t", @tmp), "\n";
2328 }
2329 @ret;
2330}
2331
aea736cc
EW
2332sub rewrite_root {
2333 my ($self) = @_;
2334 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2335 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2336 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2337 if ($rwr) {
2338 $rwr =~ s#/+$##;
2339 if ($rwr !~ m#^[a-z\+]+://#) {
2340 die "$rwr is not a valid URL (key: $k)\n";
2341 }
2342 }
2343 $self->{-rewrite_root} = $rwr;
2344}
2345
2346sub metadata_url {
2347 my ($self) = @_;
2348 ($self->rewrite_root || $self->{url}) .
2349 (length $self->{path} ? '/' . $self->{path} : '');
2350}
2351
706587fc 2352sub full_url {
9b981fc6 2353 my ($self) = @_;
5d3b7cd5 2354 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
2355}
2356
ad94802a
EW
2357
2358sub set_commit_header_env {
2359 my ($log_entry) = @_;
2360 my %env;
2361 foreach my $ned (qw/NAME EMAIL DATE/) {
2362 foreach my $ac (qw/AUTHOR COMMITTER/) {
2363 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2364 }
9b981fc6 2365 }
ad94802a 2366
70ae04e4
AW
2367 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2368 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
44320b9e 2369 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 2370
70ae04e4
AW
2371 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2372 ? $log_entry->{commit_name}
2373 : $log_entry->{name};
2374 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2375 ? $log_entry->{commit_email}
2376 : $log_entry->{email};
ad94802a
EW
2377 \%env;
2378}
70ae04e4 2379
ad94802a
EW
2380sub restore_commit_header_env {
2381 my ($env) = @_;
2382 foreach my $ned (qw/NAME EMAIL DATE/) {
2383 foreach my $ac (qw/AUTHOR COMMITTER/) {
2384 my $k = "GIT_${ac}_${ned}";
2385 if (defined $env->{$k}) {
2386 $ENV{$k} = $env->{$k};
2387 } else {
2388 delete $ENV{$k};
2389 }
2390 }
2391 }
2392}
2393
94bc914c
KW
2394sub gc {
2395 command_noisy('gc', '--auto');
2396};
2397
ad94802a
EW
2398sub do_git_commit {
2399 my ($self, $log_entry) = @_;
2400 my $lr = $self->last_rev;
2401 if (defined $lr && $lr >= $log_entry->{revision}) {
2402 die "Last fetched revision of ", $self->refname,
2403 " was r$lr, but we are about to fetch: ",
2404 "r$log_entry->{revision}!\n";
2405 }
2406 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2407 croak "$log_entry->{revision} = $c already exists! ",
2408 "Why are we refetching it?\n";
2409 }
2410 my $old_env = set_commit_header_env($log_entry);
44320b9e 2411 my $tree = $log_entry->{tree};
9b981fc6
EW
2412 if (!defined $tree) {
2413 $tree = $self->tmp_index_do(sub {
2414 command_oneline('write-tree') });
2415 }
2416 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2417
e855bfc0 2418 my @exec = ('git', 'commit-tree', $tree);
0af9c9f9 2419 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
2420 push @exec, '-p', $_;
2421 }
2422 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2423 or croak $!;
16fc08e2
EW
2424 binmode $msg_fh;
2425
2426 # we always get UTF-8 from SVN, but we may want our commits in
2427 # a different encoding.
2428 if (my $enc = Git::config('i18n.commitencoding')) {
2429 require Encode;
2430 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2431 }
44320b9e 2432 print $msg_fh $log_entry->{log} or croak $!;
ad94802a 2433 restore_commit_header_env($old_env);
91b03282 2434 unless ($self->no_metadata) {
8a49ee97
EW
2435 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2436 or croak $!;
9760adcc 2437 }
9b981fc6
EW
2438 $msg_fh->flush == 0 or croak $!;
2439 close $msg_fh or croak $!;
2440 chomp(my $commit = do { local $/; <$out_fh> });
2441 close $out_fh or croak $!;
2442 waitpid $pid, 0;
2443 croak $? if $?;
2444 if ($commit !~ /^$::sha1$/o) {
2445 die "Failed to commit, invalid sha1: $commit\n";
2446 }
2447
060610c5 2448 $self->rev_map_set($log_entry->{revision}, $commit, 1);
9b981fc6 2449
44320b9e 2450 $self->{last_rev} = $log_entry->{revision};
9b981fc6 2451 $self->{last_commit} = $commit;
49750f30 2452 print "r$log_entry->{revision}" unless $::_q > 1;
8a49ee97 2453 if (defined $log_entry->{svm_revision}) {
49750f30 2454 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
060610c5 2455 $self->rev_map_set($log_entry->{svm_revision}, $commit,
26a62d57 2456 0, $self->svm_uuid);
8a49ee97 2457 }
49750f30 2458 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
94bc914c
KW
2459 if (--$_gc_nr == 0) {
2460 $_gc_nr = $_gc_period;
2461 gc();
2462 }
9b981fc6
EW
2463 return $commit;
2464}
2465
fbcc1737
EW
2466sub match_paths {
2467 my ($self, $paths, $r) = @_;
4e9f6cc7 2468 return 1 if $self->{path} eq '';
d542aedb
EW
2469 if (my $path = $paths->{"/$self->{path}"}) {
2470 return ($path->{action} eq 'D') ? 0 : 1;
2471 }
9162b864
ML
2472 my $repos_root = $self->ra->{repos_root};
2473 my $extended_path = $self->{url} . '/' . $self->{path};
2474 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2475 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
fbcc1737
EW
2476 if (grep /$self->{path_regex}/, keys %$paths) {
2477 return 1;
2478 }
2479 my $c = '';
2480 foreach (split m#/#, $self->{path}) {
2481 $c .= "/$_";
74a81227
EW
2482 next unless ($paths->{$c} &&
2483 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
2484 if ($self->ra->check_path($self->{path}, $r) ==
2485 $SVN::Node::dir) {
fbcc1737
EW
2486 return 1;
2487 }
2488 }
2489 return 0;
2490}
2491
15710b6f
EW
2492sub find_parent_branch {
2493 my ($self, $paths, $rev) = @_;
91b03282 2494 return undef unless $self->follow_parent;
e5a0b240 2495 unless (defined $paths) {
c7eba716
EW
2496 my $err_handler = $SVN::Error::handler;
2497 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
2498 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2499 $paths =
2500 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 2501 $SVN::Error::handler = $err_handler;
e5a0b240
EW
2502 }
2503 return undef unless defined $paths;
15710b6f
EW
2504
2505 # look for a parent from another branch:
7f578c55
EW
2506 my @b_path_components = split m#/#, $self->rel_path;
2507 my @a_path_components;
2508 my $i;
2509 while (@b_path_components) {
2510 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 2511 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
2512 unshift(@a_path_components, pop(@b_path_components));
2513 }
74a81227
EW
2514 return undef unless defined $i && defined $i->{copyfrom_path};
2515 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
2516 if (@a_path_components) {
2517 print STDERR "branch_from: $branch_from => ";
2518 $branch_from .= '/'.join('/', @a_path_components);
2519 print STDERR $branch_from, "\n";
2520 }
3ebe8df7 2521 my $r = $i->{copyfrom_rev};
15710b6f
EW
2522 my $repos_root = $self->ra->{repos_root};
2523 my $url = $self->ra->{url};
2524 my $new_url = $repos_root . $branch_from;
2525 print STDERR "Found possible branch point: ",
2526 "$new_url => ", $self->full_url, ", $r\n";
2527 $branch_from =~ s#^/##;
8e3f9b17
SV
2528 my $gs = $self->other_gs($new_url, $url, $repos_root,
2529 $branch_from, $r, $self->{ref_id});
15710b6f 2530 my ($r0, $parent) = $gs->find_rev_before($r, 1);
553589f7
DM
2531 {
2532 my ($base, $head);
2533 if (!defined $r0 || !defined $parent) {
2534 ($base, $head) = parse_revision_argument(0, $r);
2535 } else {
2536 if ($r0 < $r) {
2537 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2538 0, 1, sub { $base = $_[1] - 1 });
2539 }
2540 }
2541 if (defined $base && $base <= $r) {
d627de6b
EW
2542 $gs->fetch($base, $r);
2543 }
553589f7 2544 ($r0, $parent) = $gs->find_rev_before($r, 1);
15710b6f 2545 }
ef70de96 2546 if (defined $r0 && defined $parent) {
15710b6f 2547 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
15710b6f
EW
2548 my $ed;
2549 if ($self->ra->can_do_switch) {
2e5e2480 2550 $self->assert_index_clean($parent);
8b8fc068 2551 print STDERR "Following parent with do_switch\n";
15710b6f 2552 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 2553 # is not included with SVN 1.4.3 (the latest version
15710b6f 2554 # at the moment), so we can't rely on it
83c2fcff 2555 $self->{last_rev} = $r0;
15710b6f 2556 $self->{last_commit} = $parent;
8841b37f 2557 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
8a603774 2558 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
2559 $self->full_url, $ed)
2560 or die "SVN connection failed somewhere...\n";
9ff74e95
SW
2561 } elsif ($self->ra->trees_match($new_url, $r0,
2562 $self->full_url, $rev)) {
2563 print STDERR "Trees match:\n",
2564 " $new_url\@$r0\n",
2565 " ${\$self->full_url}\@$rev\n",
2566 "Following parent with no changes\n";
2567 $self->tmp_index_do(sub {
2568 command_noisy('read-tree', $parent);
2569 });
2570 $self->{last_commit} = $parent;
15710b6f 2571 } else {
8b8fc068 2572 print STDERR "Following parent with do_update\n";
15710b6f 2573 $ed = SVN::Git::Fetcher->new($self);
8a603774 2574 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
2575 or die "SVN connection failed somewhere...\n";
2576 }
f7c3fc4a 2577 print STDERR "Successfully followed parent\n";
15710b6f
EW
2578 return $self->make_log_entry($rev, [$parent], $ed);
2579 }
15710b6f
EW
2580 return undef;
2581}
2582
9b981fc6 2583sub do_fetch {
706587fc 2584 my ($self, $paths, $rev) = @_;
15710b6f 2585 my $ed;
9b981fc6 2586 my ($last_rev, @parents);
b9dffd8c
EW
2587 if (my $lc = $self->last_commit) {
2588 # we can have a branch that was deleted, then re-added
2589 # under the same name but copied from another path, in
2590 # which case we'll have multiple parents (we don't
2591 # want to break the original ref, nor lose copypath info):
2592 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2593 push @{$log_entry->{parents}}, $lc;
2594 return $log_entry;
2595 }
15710b6f 2596 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2597 $last_rev = $self->{last_rev};
b9dffd8c
EW
2598 $ed->{c} = $lc;
2599 @parents = ($lc);
9b981fc6
EW
2600 } else {
2601 $last_rev = $rev;
15710b6f
EW
2602 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2603 return $log_entry;
2604 }
2605 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 2606 }
8a603774 2607 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
2608 die "SVN connection failed somewhere...\n";
2609 }
2610 $self->make_log_entry($rev, \@parents, $ed);
2611}
2612
97f6987a
EW
2613sub get_untracked {
2614 my ($self, $ed) = @_;
2615 my @out;
2616 my $h = $ed->{empty};
9b981fc6
EW
2617 foreach (sort keys %$h) {
2618 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 2619 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
2620 warn "W: $act: $_\n";
2621 }
2622 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 2623 $h = $ed->{$t} or next;
9b981fc6
EW
2624 foreach my $path (sort keys %$h) {
2625 my $ppath = $path eq '' ? '.' : $path;
2626 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 2627 next if $SKIP_PROP{$prop};
9b981fc6 2628 my $v = $h->{$path}->{$prop};
97f6987a
EW
2629 my $t_ppath_prop = "$t: " .
2630 uri_encode($ppath) . ' ' .
2631 uri_encode($prop);
9b981fc6 2632 if (defined $v) {
97f6987a
EW
2633 push @out, " +$t_ppath_prop " .
2634 uri_encode($v);
9b981fc6 2635 } else {
97f6987a 2636 push @out, " -$t_ppath_prop";
9b981fc6
EW
2637 }
2638 }
2639 }
2640 }
2641 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 2642 $h = $ed->{$t} or next;
9b981fc6
EW
2643 foreach my $parent (sort keys %$h) {
2644 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
2645 push @out, " $t: " .
2646 uri_encode("$parent/$path");
9b981fc6
EW
2647 warn "W: $t: $parent/$path ",
2648 "Insufficient permissions?\n";
2649 }
2650 }
2651 }
97f6987a 2652 \@out;
9b981fc6
EW
2653}
2654
e82f0d73
PH
2655# parse_svn_date(DATE)
2656# --------------------
2657# Given a date (in UTC) from Subversion, return a string in the format
2658# "<TZ Offset> <local date/time>" that Git will use.
2659#
2660# By default the parsed date will be in UTC; if $Git::SVN::_localtime
2661# is true we'll convert it to the local timezone instead.
1c8443b0
EW
2662sub parse_svn_date {
2663 my $date = shift || return '+0000 1970-01-01 00:00:00';
2664 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
b94ead75 2665 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
1c8443b0 2666 croak "Unable to parse date: $date\n";
e82f0d73
PH
2667 my $parsed_date; # Set next.
2668
2669 if ($Git::SVN::_localtime) {
2670 # Translate the Subversion datetime to an epoch time.
2671 # Begin by switching ourselves to $date's timezone, UTC.
2672 my $old_env_TZ = $ENV{TZ};
2673 $ENV{TZ} = 'UTC';
2674
2675 my $epoch_in_UTC =
2676 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2677
2678 # Determine our local timezone (including DST) at the
2679 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2680 # value of TZ, if any, at the time we were run.
2681 if (defined $Git::SVN::Log::TZ) {
2682 $ENV{TZ} = $Git::SVN::Log::TZ;
2683 } else {
2684 delete $ENV{TZ};
2685 }
2686
2687 my $our_TZ =
2688 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2689
2690 # This converts $epoch_in_UTC into our local timezone.
2691 my ($sec, $min, $hour, $mday, $mon, $year,
2692 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2693
2694 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2695 $our_TZ, $year + 1900, $mon + 1,
2696 $mday, $hour, $min, $sec);
2697
2698 # Reset us to the timezone in effect when we entered
2699 # this routine.
2700 if (defined $old_env_TZ) {
2701 $ENV{TZ} = $old_env_TZ;
2702 } else {
2703 delete $ENV{TZ};
2704 }
2705 } else {
2706 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2707 }
2708
2709 return $parsed_date;
1c8443b0
EW
2710}
2711
8e3f9b17
SV
2712sub other_gs {
2713 my ($self, $new_url, $url, $repos_root,
2714 $branch_from, $r, $old_ref_id) = @_;
2715 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2716 unless ($gs) {
2717 my $ref_id = $old_ref_id;
2718 $ref_id =~ s/\@\d+$//;
2719 $ref_id .= "\@$r";
2720 # just grow a tail if we're not unique enough :x
2721 $ref_id .= '-' while find_ref($ref_id);
2722 print STDERR "Initializing parent: $ref_id\n";
2723 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2724 if ($u =~ s#^\Q$url\E(/|$)##) {
2725 $p = $u;
2726 $u = $url;
2727 $repo_id = $self->{repo_id};
2728 }
2729 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2730 }
2731 $gs
2732}
2733
36db1edd
ML
2734sub call_authors_prog {
2735 my ($orig_author) = @_;
2736 my $author = `$::_authors_prog $orig_author`;
2737 if ($? != 0) {
2738 die "$::_authors_prog failed with exit code $?\n"
2739 }
2740 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2741 my ($name, $email) = ($1, $2);
2742 $email = undef if length $2 == 0;
2743 return [$name, $email];
2744 } else {
2745 die "Author: $orig_author: $::_authors_prog returned "
2746 . "invalid author format: $author\n";
2747 }
2748}
2749
1c8443b0
EW
2750sub check_author {
2751 my ($author) = @_;
2752 if (!defined $author || length $author == 0) {
2753 $author = '(no author)';
36db1edd
ML
2754 }
2755 if (!defined $::users{$author}) {
2756 if (defined $::_authors_prog) {
2757 $::users{$author} = call_authors_prog($author);
2758 } elsif (defined $::_authors) {
2759 die "Author: $author not defined in $::_authors file\n";
2760 }
1c8443b0
EW
2761 }
2762 $author;
2763}
2764
9b981fc6 2765sub make_log_entry {
97f6987a
EW
2766 my ($self, $rev, $parents, $ed) = @_;
2767 my $untracked = $self->get_untracked($ed);
2768
9b981fc6 2769 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
2770 print $un "r$rev\n" or croak $!;
2771 print $un $_, "\n" foreach @$untracked;
2772 my %log_entry = ( parents => $parents || [], revision => $rev,
2773 log => '');
fbcc1737 2774
8a49ee97 2775 my $headrev;
fbcc1737 2776 my $logged = delete $self->{logged_rev_props};
8a49ee97 2777 if (!$logged || $self->{-want_revprops}) {
fbcc1737
EW
2778 my $rp = $self->ra->rev_proplist($rev);
2779 foreach (sort keys %$rp) {
2780 my $v = $rp->{$_};
2781 if (/^svn:(author|date|log)$/) {
2782 $log_entry{$1} = $v;
8a49ee97
EW
2783 } elsif ($_ eq 'svm:headrev') {
2784 $headrev = $v;
fbcc1737
EW
2785 } else {
2786 print $un " rev_prop: ", uri_encode($_), ' ',
2787 uri_encode($v), "\n";
2788 }
9b981fc6 2789 }
fbcc1737
EW
2790 } else {
2791 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
2792 }
2793 close $un or croak $!;
97f6987a 2794
9b981fc6 2795 $log_entry{date} = parse_svn_date($log_entry{date});
9b981fc6 2796 $log_entry{log} .= "\n";
db03cd24
EW
2797 my $author = $log_entry{author} = check_author($log_entry{author});
2798 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
70ae04e4
AW
2799 : ($author, undef);
2800
2801 my ($commit_name, $commit_email) = ($name, $email);
2802 if ($_use_log_author) {
5ff6aae8
AW
2803 my $name_field;
2804 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2805 $name_field = $1;
2806 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2807 $name_field = $1;
2808 }
2809 if (!defined $name_field) {
abfa533d
SB
2810 if (!defined $email) {
2811 $email = $name;
2812 }
5ff6aae8 2813 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
70ae04e4 2814 ($name, $email) = ($1, $2);
5ff6aae8
AW
2815 } elsif ($name_field =~ /(.*)@/) {
2816 ($name, $email) = ($1, $name_field);
2817 } else {
abfa533d 2818 ($name, $email) = ($name_field, $name_field);
70ae04e4
AW
2819 }
2820 }
91b03282 2821 if (defined $headrev && $self->use_svm_props) {
aea736cc
EW
2822 if ($self->rewrite_root) {
2823 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2824 "options set!\n";
2825 }
8a49ee97 2826 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
befc9adc
EW
2827 # we don't want "SVM: initializing mirror for junk" ...
2828 return undef if $r == 0;
2829 my $svm = $self->svm;
2830 if ($uuid ne $svm->{uuid}) {
8a49ee97 2831 die "UUID mismatch on SVM path:\n",
befc9adc 2832 "expected: $svm->{uuid}\n",
8a49ee97
EW
2833 " got: $uuid\n";
2834 }
befc9adc
EW
2835 my $full_url = $self->full_url;
2836 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2837 die "Failed to replace '$svm->{replace}' with ",
2838 "'$svm->{source}' in $full_url\n";
18ea92bd
SV
2839 # throw away username for storing in records
2840 remove_username($full_url);
8a49ee97
EW
2841 $log_entry{metadata} = "$full_url\@$r $uuid";
2842 $log_entry{svm_revision} = $r;
70ae04e4
AW
2843 $email ||= "$author\@$uuid";
2844 $commit_email ||= "$author\@$uuid";
62e349d2
EW
2845 } elsif ($self->use_svnsync_props) {
2846 my $full_url = $self->svnsync->{url};
2847 $full_url .= "/$self->{path}" if length $self->{path};
ce118739 2848 remove_username($full_url);
62e349d2
EW
2849 my $uuid = $self->svnsync->{uuid};
2850 $log_entry{metadata} = "$full_url\@$rev $uuid";
70ae04e4
AW
2851 $email ||= "$author\@$uuid";
2852 $commit_email ||= "$author\@$uuid";
8a49ee97 2853 } else {
ce118739
AR
2854 my $url = $self->metadata_url;
2855 remove_username($url);
2856 $log_entry{metadata} = "$url\@$rev " .
26a62d57 2857 $self->ra->get_uuid;
db03cd24 2858 $email ||= "$author\@" . $self->ra->get_uuid;
70ae04e4 2859 $commit_email ||= "$author\@" . $self->ra->get_uuid;
8a49ee97 2860 }
db03cd24
EW
2861 $log_entry{name} = $name;
2862 $log_entry{email} = $email;
70ae04e4
AW
2863 $log_entry{commit_name} = $commit_name;
2864 $log_entry{commit_email} = $commit_email;
9b981fc6
EW
2865 \%log_entry;
2866}
2867
2868sub fetch {
3ebe8df7 2869 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 2870 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 2871 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 2872 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
2873}
2874
2875sub set_tree_cb {
2876 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
490f49ea
EW
2877 $self->{inject_parents} = { $rev => $tree };
2878 $self->fetch(undef, undef);
9b981fc6
EW
2879}
2880
2881sub set_tree {
2882 my ($self, $tree) = (shift, shift);
1ce255dc 2883 my $log_entry = ::get_commit_entry($tree);
9b981fc6 2884 unless ($self->{last_rev}) {
0a1a1c86 2885 ::fatal("Must have an existing revision to commit");
9b981fc6 2886 }
61395354
EW
2887 my %ed_opts = ( r => $self->{last_rev},
2888 log => $log_entry->{log},
2889 ra => $self->ra,
2890 tree_a => $self->{last_commit},
2891 tree_b => $tree,
2892 editor_cb => sub {
2893 $self->set_tree_cb($log_entry, $tree, @_) },
2894 svn_path => $self->{path} );
2895 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
2896 print "No changes\nr$self->{last_rev} = $tree\n";
2897 }
9b981fc6
EW
2898}
2899
060610c5
EW
2900sub rebuild_from_rev_db {
2901 my ($self, $path) = @_;
2902 my $r = -1;
2903 open my $fh, '<', $path or croak "open: $!";
4f7ec797 2904 binmode $fh or croak "binmode: $!";
060610c5
EW
2905 while (<$fh>) {
2906 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2907 chomp($_);
2908 ++$r;
2909 next if $_ eq ('0' x 40);
2910 $self->rev_map_set($r, $_);
2911 print "r$r = $_\n";
2912 }
2913 close $fh or croak "close: $!";
2914 unlink $path or croak "unlink: $!";
2915}
2916
f0ecca10
EW
2917sub rebuild {
2918 my ($self) = @_;
060610c5 2919 my $map_path = $self->map_path;
2beec897 2920 my $partial = (-e $map_path && ! -z $map_path);
d6d3346b 2921 return unless ::verify_ref($self->refname.'^0');
2beec897 2922 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
060610c5
EW
2923 my $rev_db = $self->rev_db_path;
2924 $self->rebuild_from_rev_db($rev_db);
2925 if ($self->use_svm_props) {
2926 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2927 $self->rebuild_from_rev_db($svm_rev_db);
2928 }
2929 $self->unlink_rev_db_symlink;
26a62d57
EW
2930 return;
2931 }
2beec897
DM
2932 print "Rebuilding $map_path ...\n" if (!$partial);
2933 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2934 (undef, undef));
060610c5
EW
2935 my ($log, $ctx) =
2936 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2beec897
DM
2937 ($head ? "$head.." : "") . $self->refname,
2938 '--');
74b1e123
JK
2939 my $metadata_url = $self->metadata_url;
2940 remove_username($metadata_url);
060610c5 2941 my $svn_uuid = $self->ra_uuid;
3dfab993
SV
2942 my $c;
2943 while (<$log>) {
2944 if ( m{^commit ($::sha1)$} ) {
2945 $c = $1;
2946 next;
2947 }
2948 next unless s{^\s*(git-svn-id:)}{$1};
2949 my ($url, $rev, $uuid) = ::extract_metadata($_);
18ea92bd 2950 remove_username($url);
f0ecca10
EW
2951
2952 # ignore merges (from set-tree)
2953 next if (!defined $rev || !$uuid);
2954
2955 # if we merged or otherwise started elsewhere, this is
2956 # how we break out of it
060610c5 2957 if (($uuid ne $svn_uuid) ||
74b1e123 2958 ($metadata_url && $url && ($url ne $metadata_url))) {
f0ecca10
EW
2959 next;
2960 }
2beec897
DM
2961 if ($partial && $head) {
2962 print "Partial-rebuilding $map_path ...\n";
2963 print "Currently at $base_rev = $head\n";
2964 $head = undef;
2965 }
f0ecca10 2966
060610c5 2967 $self->rev_map_set($rev, $c);
f0ecca10
EW
2968 print "r$rev = $c\n";
2969 }
3dfab993 2970 command_close_pipe($log, $ctx);
2beec897 2971 print "Done rebuilding $map_path\n" if (!$partial || !$head);
060610c5
EW
2972 my $rev_db_path = $self->rev_db_path;
2973 if (-f $self->rev_db_path) {
2974 unlink $self->rev_db_path or croak "unlink: $!";
2975 }
2976 $self->unlink_rev_db_symlink;
f0ecca10
EW
2977}
2978
060610c5 2979# rev_map:
9b981fc6
EW
2980# Tie::File seems to be prone to offset errors if revisions get sparse,
2981# it's not that fast, either. Tie::File is also not in Perl 5.6. So
2982# one of my favorite modules is out :< Next up would be one of the DBM
060610c5
EW
2983# modules, but I'm not sure which is most portable...
2984#
2985# This is the replacement for the rev_db format, which was too big
2986# and inefficient for large repositories with a lot of sparse history
2987# (mainly tags)
2988#
2989# The format is this:
2990# - 24 bytes for every record,
2991# * 4 bytes for the integer representing an SVN revision number
2992# * 20 bytes representing the sha1 of a git commit
2993# - No empty padding records like the old format
66ab84b9 2994# (except the last record, which can be overwritten)
060610c5
EW
2995# - new records are written append-only since SVN revision numbers
2996# increase monotonically
2997# - lookups on SVN revision number are done via a binary search
66ab84b9
EW
2998# - Piping the file to xxd -c24 is a good way of dumping it for
2999# viewing or editing (piped back through xxd -r), should the need
3000# ever arise.
3001# - The last record can be padding revision with an all-zero sha1
3002# This is used to optimize fetch performance when using multiple
3003# "fetch" directives in .git/config
060610c5 3004#
97ae0911 3005# These files are disposable unless noMetadata or useSvmProps is set
9b981fc6 3006
060610c5 3007sub _rev_map_set {
26a62d57 3008 my ($fh, $rev, $commit) = @_;
060610c5 3009
4f7ec797 3010 binmode $fh or croak "binmode: $!";
060610c5
EW
3011 my $size = (stat($fh))[7];
3012 ($size % 24) == 0 or croak "inconsistent size: $size";
3013
66ab84b9 3014 my $wr_offset = 0;
060610c5
EW
3015 if ($size > 0) {
3016 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3017 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3018 $read == 24 or croak "read only $read bytes (!= 24)";
3019 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
3020 if ($last_commit eq ('0' x40)) {
3021 if ($size >= 48) {
3022 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3023 $read = sysread($fh, $buf, 24) or
3024 croak "read: $!";
3025 $read == 24 or
3026 croak "read only $read bytes (!= 24)";
3027 ($last_rev, $last_commit) =
3028 unpack(rev_map_fmt, $buf);
3029 if ($last_commit eq ('0' x40)) {
3030 croak "inconsistent .rev_map\n";
3031 }
3032 }
3033 if ($last_rev >= $rev) {
3034 croak "last_rev is higher!: $last_rev >= $rev";
3035 }
3036 $wr_offset = -24;
26a62d57
EW
3037 }
3038 }
66ab84b9 3039 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
060610c5
EW
3040 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3041 croak "write: $!";
26a62d57
EW
3042}
3043
195643f2
BJ
3044sub _rev_map_reset {
3045 my ($fh, $rev, $commit) = @_;
3046 my $c = _rev_map_get($fh, $rev);
3047 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3048 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3049 truncate $fh, $offset or croak "truncate: $!";
3050}
3051
26a62d57
EW
3052sub mkfile {
3053 my ($path) = @_;
3054 unless (-e $path) {
3055 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3056 mkpath([$dir]) unless -d $dir;
3057 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3058 close $fh or die "Couldn't close (create) $path: $!\n";
3059 }
3060}
3061
060610c5 3062sub rev_map_set {
26a62d57
EW
3063 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3064 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
060610c5 3065 my $db = $self->map_path($uuid);
26a62d57 3066 my $db_lock = "$db.lock";
373274f9 3067 my $sig;
195643f2 3068 $update_ref ||= 0;
373274f9
EW
3069 if ($update_ref) {
3070 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3071 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3072 }
26a62d57
EW
3073 mkfile($db);
3074
373274f9 3075 $LOCKFILES{$db_lock} = 1;
97ae0911 3076 my $sync;
97ae0911
EW
3077 # both of these options make our .rev_db file very, very important
3078 # and we can't afford to lose it because rebuild() won't work
3079 if ($self->use_svm_props || $self->no_metadata) {
3080 $sync = 1;
060610c5 3081 copy($db, $db_lock) or die "rev_map_set(@_): ",
26a62d57 3082 "Failed to copy: ",
373274f9
EW
3083 "$db => $db_lock ($!)\n";
3084 } else {
060610c5 3085 rename $db, $db_lock or die "rev_map_set(@_): ",
26a62d57 3086 "Failed to rename: ",
373274f9
EW
3087 "$db => $db_lock ($!)\n";
3088 }
060610c5 3089
66ab84b9 3090 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
060610c5 3091 or croak "Couldn't open $db_lock: $!\n";
195643f2
BJ
3092 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3093 _rev_map_set($fh, $rev, $commit);
97ae0911
EW
3094 if ($sync) {
3095 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3096 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3097 }
9b981fc6 3098 close $fh or croak $!;
373274f9 3099 if ($update_ref) {
1e889ef3 3100 $_head = $self;
195643f2
BJ
3101 my $note = "";
3102 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3103 command_noisy('update-ref', '-m', "r$rev$note",
373274f9
EW
3104 $self->refname, $commit);
3105 }
060610c5 3106 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
373274f9
EW
3107 "$db_lock => $db ($!)\n";
3108 delete $LOCKFILES{$db_lock};
3109 if ($update_ref) {
3110 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3111 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3112 kill $sig, $$ if defined $sig;
3113 }
9b981fc6
EW
3114}
3115
66ab84b9
EW
3116# If want_commit, this will return an array of (rev, commit) where
3117# commit _must_ be a valid commit in the archive.
3118# Otherwise, it'll return the max revision (whether or not the
3119# commit is valid or just a 0x40 placeholder).
060610c5 3120sub rev_map_max {
66ab84b9 3121 my ($self, $want_commit) = @_;
d6d3346b 3122 $self->rebuild;
2beec897
DM
3123 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3124 $want_commit ? ($r, $c) : $r;
3125}
3126
3127sub rev_map_max_norebuild {
3128 my ($self, $want_commit) = @_;
060610c5 3129 my $map_path = $self->map_path;
66ab84b9 3130 stat $map_path or return $want_commit ? (0, undef) : 0;
060610c5 3131 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
4f7ec797 3132 binmode $fh or croak "binmode: $!";
060610c5
EW
3133 my $size = (stat($fh))[7];
3134 ($size % 24) == 0 or croak "inconsistent size: $size";
3135
3136 if ($size == 0) {
3137 close $fh or croak "close: $!";
66ab84b9 3138 return $want_commit ? (0, undef) : 0;
060610c5
EW
3139 }
3140
66ab84b9 3141 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
060610c5 3142 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
060610c5 3143 my ($r, $c) = unpack(rev_map_fmt, $buf);
66ab84b9
EW
3144 if ($want_commit && $c eq ('0' x40)) {
3145 if ($size < 48) {
3146 return $want_commit ? (0, undef) : 0;
3147 }
3148 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3149 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3150 ($r, $c) = unpack(rev_map_fmt, $buf);
3151 if ($c eq ('0'x40)) {
3152 croak "Penultimate record is all-zeroes in $map_path";
3153 }
3154 }
3155 close $fh or croak "close: $!";
3156 $want_commit ? ($r, $c) : $r;
9c93fee5
EW
3157}
3158
060610c5 3159sub rev_map_get {
26a62d57 3160 my ($self, $rev, $uuid) = @_;
060610c5
EW
3161 my $map_path = $self->map_path($uuid);
3162 return undef unless -e $map_path;
3163
3164 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
195643f2
BJ
3165 my $c = _rev_map_get($fh, $rev);
3166 close($fh) or croak "close: $!";
3167 $c
3168}
3169
3170sub _rev_map_get {
3171 my ($fh, $rev) = @_;
3172
4f7ec797 3173 binmode $fh or croak "binmode: $!";
060610c5
EW
3174 my $size = (stat($fh))[7];
3175 ($size % 24) == 0 or croak "inconsistent size: $size";
3176
3177 if ($size == 0) {
060610c5
EW
3178 return undef;
3179 }
3180
3181 my ($l, $u) = (0, $size - 24);
3182 my ($r, $c, $buf);
3183
3184 while ($l <= $u) {
3185 my $i = int(($l/24 + $u/24) / 2) * 24;
3186 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3187 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3188 my ($r, $c) = unpack('NH40', $buf);
3189
3190 if ($r < $rev) {
3191 $l = $i + 24;
3192 } elsif ($r > $rev) {
3193 $u = $i - 24;
3194 } else { # $r == $rev
66ab84b9 3195 return $c eq ('0' x 40) ? undef : $c;
060610c5 3196 }
9b981fc6 3197 }
060610c5 3198 undef;
9b981fc6
EW
3199}
3200
111947ef
DK
3201# Finds the first svn revision that exists on (if $eq_ok is true) or
3202# before $rev for the current branch. It will not search any lower
3203# than $min_rev. Returns the git commit hash and svn revision number
3204# if found, else (undef, undef).
15710b6f 3205sub find_rev_before {
111947ef 3206 my ($self, $rev, $eq_ok, $min_rev) = @_;
15710b6f 3207 --$rev unless $eq_ok;
111947ef 3208 $min_rev ||= 1;
ca5e880e
BJ
3209 my $max_rev = $self->rev_map_max;
3210 $rev = $max_rev if ($rev > $max_rev);
111947ef 3211 while ($rev >= $min_rev) {
060610c5 3212 if (my $c = $self->rev_map_get($rev)) {
15710b6f
EW
3213 return ($rev, $c);
3214 }
3215 --$rev;
3216 }
3217 return (undef, undef);
3218}
3219
111947ef
DK
3220# Finds the first svn revision that exists on (if $eq_ok is true) or
3221# after $rev for the current branch. It will not search any higher
3222# than $max_rev. Returns the git commit hash and svn revision number
3223# if found, else (undef, undef).
3224sub find_rev_after {
3225 my ($self, $rev, $eq_ok, $max_rev) = @_;
3226 ++$rev unless $eq_ok;
060610c5 3227 $max_rev ||= $self->rev_map_max;
111947ef 3228 while ($rev <= $max_rev) {
060610c5 3229 if (my $c = $self->rev_map_get($rev)) {
111947ef
DK
3230 return ($rev, $c);
3231 }
3232 ++$rev;
3233 }
3234 return (undef, undef);
3235}
3236
9b981fc6 3237sub _new {
706587fc
EW
3238 my ($class, $repo_id, $ref_id, $path) = @_;
3239 unless (defined $repo_id && length $repo_id) {
3240 $repo_id = $Git::SVN::default_repo_id;
3241 }
3242 unless (defined $ref_id && length $ref_id) {
8b8fc068 3243 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc 3244 }
7829f20f 3245 $_[1] = $repo_id;
706587fc
EW
3246 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3247 $_[3] = $path = '' unless (defined $path);
b4d57e5e 3248 mkpath(["$ENV{GIT_DIR}/svn"]);
26a62d57
EW
3249 bless {
3250 ref_id => $ref_id, dir => $dir, index => "$dir/index",
8a49ee97 3251 path => $path, config => "$ENV{GIT_DIR}/svn/config",
060610c5 3252 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
26a62d57
EW
3253}
3254
060610c5
EW
3255# for read-only access of old .rev_db formats
3256sub unlink_rev_db_symlink {
3257 my ($self) = @_;
3258 my $link = $self->rev_db_path;
3259 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3260 if (-l $link) {
3261 unlink $link or croak "unlink: $link failed!";
3262 }
3263}
3264
3265sub rev_db_path {
3266 my ($self, $uuid) = @_;
3267 my $db_path = $self->map_path($uuid);
3268 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3269 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3270 $db_path;
3271}
3272
3273# the new replacement for .rev_db
3274sub map_path {
26a62d57
EW
3275 my ($self, $uuid) = @_;
3276 $uuid ||= $self->ra_uuid;
060610c5 3277 "$self->{map_root}.$uuid";
9b981fc6
EW
3278}
3279
1c8443b0
EW
3280sub uri_encode {
3281 my ($f) = @_;
3282 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3283 $f
3284}
9b981fc6 3285
18ea92bd
SV
3286sub remove_username {
3287 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3288}
3289
d976acfd
EW
3290package Git::SVN::Prompt;
3291use strict;
3292use warnings;
3293require SVN::Core;
3294use vars qw/$_no_auth_cache $_username/;
3295
3296sub simple {
30d055aa
EW
3297 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3298 $may_save = undef if $_no_auth_cache;
3299 $default_username = $_username if defined $_username;
3300 if (defined $default_username && length $default_username) {
3301 if (defined $realm && length $realm) {
6f729591
EW
3302 print STDERR "Authentication realm: $realm\n";
3303 STDERR->flush;
30d055aa
EW
3304 }
3305 $cred->username($default_username);
3306 } else {
d976acfd 3307 username($cred, $realm, $may_save, $pool);
30d055aa
EW
3308 }
3309 $cred->password(_read_password("Password for '" .
3310 $cred->username . "': ", $realm));
3311 $cred->may_save($may_save);
3312 $SVN::_Core::SVN_NO_ERROR;
3313}
3314
d976acfd 3315sub ssl_server_trust {
30d055aa
EW
3316 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3317 $may_save = undef if $_no_auth_cache;
6f729591 3318 print STDERR "Error validating server certificate for '$realm':\n";
fd499bcc
ER
3319 {
3320 no warnings 'once';
3321 # All variables SVN::Auth::SSL::* are used only once,
3322 # so we're shutting up Perl warnings about this.
3323 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3324 print STDERR " - The certificate is not issued ",
3325 "by a trusted authority. Use the\n",
3326 " fingerprint to validate ",
3327 "the certificate manually!\n";
3328 }
3329 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3330 print STDERR " - The certificate hostname ",
3331 "does not match.\n";
3332 }
3333 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3334 print STDERR " - The certificate is not yet valid.\n";
3335 }
3336 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3337 print STDERR " - The certificate has expired.\n";
3338 }
3339 if ($failures & $SVN::Auth::SSL::OTHER) {
3340 print STDERR " - The certificate has ",
3341 "an unknown error.\n";
3342 }
3343 } # no warnings 'once'
6f729591
EW
3344 printf STDERR
3345 "Certificate information:\n".
30d055aa
EW
3346 " - Hostname: %s\n".
3347 " - Valid: from %s until %s\n".
3348 " - Issuer: %s\n".
3349 " - Fingerprint: %s\n",
3350 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 3351 issuer_dname fingerprint);
30d055aa
EW
3352 my $choice;
3353prompt:
6f729591 3354 print STDERR $may_save ?
30d055aa
EW
3355 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3356 "(R)eject or accept (t)emporarily? ";
6f729591 3357 STDERR->flush;
30d055aa
EW
3358 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3359 if ($choice =~ /^t$/i) {
3360 $cred->may_save(undef);
3361 } elsif ($choice =~ /^r$/i) {
3362 return -1;
3363 } elsif ($may_save && $choice =~ /^p$/i) {
3364 $cred->may_save($may_save);
3365 } else {
3366 goto prompt;
3367 }
3368 $cred->accepted_failures($failures);
3369 $SVN::_Core::SVN_NO_ERROR;
3370}
3371
d976acfd 3372sub ssl_client_cert {
30d055aa
EW
3373 my ($cred, $realm, $may_save, $pool) = @_;
3374 $may_save = undef if $_no_auth_cache;
6f729591
EW
3375 print STDERR "Client certificate filename: ";
3376 STDERR->flush;
30d055aa
EW
3377 chomp(my $filename = <STDIN>);
3378 $cred->cert_file($filename);
3379 $cred->may_save($may_save);
3380 $SVN::_Core::SVN_NO_ERROR;
3381}
3382
d976acfd 3383sub ssl_client_cert_pw {
30d055aa
EW
3384 my ($cred, $realm, $may_save, $pool) = @_;
3385 $may_save = undef if $_no_auth_cache;
3386 $cred->password(_read_password("Password: ", $realm));
3387 $cred->may_save($may_save);
3388 $SVN::_Core::SVN_NO_ERROR;
3389}
3390
d976acfd 3391sub username {
30d055aa
EW
3392 my ($cred, $realm, $may_save, $pool) = @_;
3393 $may_save = undef if $_no_auth_cache;
3394 if (defined $realm && length $realm) {
6f729591 3395 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
3396 }
3397 my $username;
3398 if (defined $_username) {
3399 $username = $_username;
3400 } else {
6f729591
EW
3401 print STDERR "Username: ";
3402 STDERR->flush;
30d055aa
EW
3403 chomp($username = <STDIN>);
3404 }
3405 $cred->username($username);
3406 $cred->may_save($may_save);
3407 $SVN::_Core::SVN_NO_ERROR;
3408}
3409
3410sub _read_password {
3411 my ($prompt, $realm) = @_;
6f729591
EW
3412 print STDERR $prompt;
3413 STDERR->flush;
30d055aa
EW
3414 require Term::ReadKey;
3415 Term::ReadKey::ReadMode('noecho');
3416 my $password = '';
3417 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3418 last if $key =~ /[\012\015]/; # \n\r
3419 $password .= $key;
3420 }
3421 Term::ReadKey::ReadMode('restore');
6f729591
EW
3422 print STDERR "\n";
3423 STDERR->flush;
30d055aa
EW
3424 $password;
3425}
3426
27a1a801
EW
3427package SVN::Git::Fetcher;
3428use vars qw/@ISA/;
3429use strict;
3430use warnings;
3431use Carp qw/croak/;
ffe256f9 3432use File::Temp qw/tempfile/;
27a1a801 3433use IO::File qw//;
edc662f9 3434use vars qw/$_ignore_regex/;
27a1a801
EW
3435
3436# file baton members: path, mode_a, mode_b, pool, fh, blob, base
3437sub new {
8841b37f 3438 my ($class, $git_svn, $switch_path) = @_;
27a1a801
EW
3439 my $self = SVN::Delta::Editor->new;
3440 bless $self, $class;
dbc6c74d
EW
3441 if (exists $git_svn->{last_commit}) {
3442 $self->{c} = $git_svn->{last_commit};
8841b37f
EW
3443 $self->{empty_symlinks} =
3444 _mark_empty_symlinks($git_svn, $switch_path);
dbc6c74d 3445 }
0d8bee71
BJ
3446 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3447 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
d2a9a87b
EW
3448 $self->{empty} = {};
3449 $self->{dir_prop} = {};
3450 $self->{file_prop} = {};
3451 $self->{absent_dir} = {};
3452 $self->{absent_file} = {};
ef3cfaad 3453 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
3454 $self;
3455}
3456
dbc6c74d
EW
3457# this uses the Ra object, so it must be called before do_{switch,update},
3458# not inside them (when the Git::SVN::Fetcher object is passed) to
3459# do_{switch,update}
3460sub _mark_empty_symlinks {
8841b37f 3461 my ($git_svn, $switch_path) = @_;
4c58a711 3462 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
48679e5c 3463 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4c58a711 3464
dbc6c74d
EW
3465 my %ret;
3466 my ($rev, $cmt) = $git_svn->last_rev_commit;
3467 return {} unless ($rev && $cmt);
3468
4c58a711
EW
3469 # allow the warning to be printed for each revision we fetch to
3470 # ensure the user sees it. The user can also disable the workaround
3471 # on the repository even while git svn is running and the next
3472 # revision fetched will skip this expensive function.
3473 my $printed_warning;
dbc6c74d
EW
3474 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3475 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3476 local $/ = "\0";
8841b37f 3477 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
dbc6c74d
EW
3478 $pfx .= '/' if length($pfx);
3479 while (<$ls>) {
3480 chomp;
3481 s/\A100644 blob $empty_blob\t//o or next;
4c58a711
EW
3482 unless ($printed_warning) {
3483 print STDERR "Scanning for empty symlinks, ",
3484 "this may take a while if you have ",
3485 "many empty files\n",
3486 "You may disable this with `",
3487 "git config svn.brokenSymlinkWorkaround ",
3488 "false'.\n",
3489 "This may be done in a different ",
3490 "terminal without restarting ",
3491 "git svn\n";
3492 $printed_warning = 1;
3493 }
dbc6c74d
EW
3494 my $path = $_;
3495 my (undef, $props) =
3496 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3497 if ($props->{'svn:special'}) {
3498 $ret{$path} = 1;
3499 }
3500 }
3501 command_close_pipe($ls, $ctx);
3502 \%ret;
3503}
3504
b03a71a6
EW
3505# returns true if a given path is inside a ".git" directory
3506sub in_dot_git {
3507 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3508}
3509
edc662f9
VS
3510# return value: 0 -- don't ignore, 1 -- ignore