]> git.ipfire.org Git - thirdparty/git.git/blame - git-svn.perl
Add 'git svn reset' to unwind 'git svn fetch'
[thirdparty/git.git] / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
ffe256f9 7 $sha1 $sha1_short $_revision $_repository
36db1edd 8 $_q $_authors $_authors_prog %users/;
3397f9df 9$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 10$VERSION = '@@GIT_VERSION@@';
13ccd6d4 11
15153451
BS
12# From which subdir have we been invoked?
13my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15} || '';
16
5253dc33 17my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
706587fc 18$ENV{GIT_DIR} ||= '.git';
9fa00b65 19$Git::SVN::default_repo_id = 'svn';
8b8fc068 20$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
6af1db44 21$Git::SVN::Ra::_log_window_size = 100;
13ccd6d4 22
f8c9d1d2 23$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 24$ENV{TZ} = 'UTC';
a00439ac 25$| = 1; # unbuffer STDOUT
3397f9df 26
207f1a75 27sub fatal (@) { print STDERR "@_\n"; exit 1 }
b9c85187
EW
28require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29require SVN::Ra;
30require SVN::Delta;
31if ($SVN::Core::VERSION lt '1.1.0') {
207f1a75 32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
b9c85187 33}
d81bf827 34push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
35push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df 37use Carp qw/croak/;
8d7c4fad 38use Digest::MD5;
3397f9df
EW
39use IO::File qw//;
40use File::Basename qw/dirname basename/;
41use File::Path qw/mkpath/;
36db1edd 42use File::Spec;
512b620b 43use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
968bdf1f 44use IPC::Open3;
336f1714 45use Git;
a5e0cedc 46
336f1714 47BEGIN {
c5f71ad0
SV
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
336f1714 50 foreach (qw/command command_oneline command_noisy command_output_pipe
6ea42032
BB
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
c5f71ad0 53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
8d7c4fad 54 Git::SVN::Migration Git::SVN::Log Git::SVN),
c5f71ad0
SV
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
57 }
336f1714 58 }
336f1714
EW
59}
60
b9c85187 61my ($SVN);
83e9940a 62
f8c9d1d2
EW
63$sha1 = qr/[a-f\d]{40}/;
64$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 65my ($_stdin, $_help, $_edit,
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
3511sub is_path_ignored {
0d8bee71 3512 my ($self, $path) = @_;
edc662f9 3513 return 1 if in_dot_git($path);
0d8bee71
BJ
3514 return 1 if defined($self->{ignore_regex}) &&
3515 $path =~ m!$self->{ignore_regex}!;
edc662f9
VS
3516 return 0 unless defined($_ignore_regex);
3517 return 1 if $path =~ m!$_ignore_regex!o;
3518 return 0;
3519}
3520
8b8fc068
EW
3521sub set_path_strip {
3522 my ($self, $path) = @_;
4e9f6cc7 3523 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
3524}
3525
d2a9a87b
EW
3526sub open_root {
3527 { path => '' };
3528}
3529
3530sub open_directory {
3531 my ($self, $path, $pb, $rev) = @_;
3532 { path => $path };
3533}
3534
706587fc
EW
3535sub git_path {
3536 my ($self, $path) = @_;
2b27f6c8
EW
3537 if ($self->{path_strip}) {
3538 $path =~ s!$self->{path_strip}!! or
3539 die "Failed to strip path '$path' ($self->{path_strip})\n";
3540 }
706587fc
EW
3541 $path;
3542}
3543
27a1a801
EW
3544sub delete_entry {
3545 my ($self, $path, $rev, $pb) = @_;
0d8bee71 3546 return undef if $self->is_path_ignored($path);
4a87db0e 3547
706587fc 3548 my $gpath = $self->git_path($path);
8a603774
EW
3549 return undef if ($gpath eq '');
3550
4a87db0e 3551 # remove entire directories.
4f821012
EW
3552 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3553 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3554 if ($tree) {
4a87db0e
EW
3555 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3556 -r --name-only -z/,
4f821012 3557 $tree);
4a87db0e
EW
3558 local $/ = "\0";
3559 while (<$ls>) {
ef3cfaad 3560 chomp;
4f821012
EW
3561 my $rmpath = "$gpath/$_";
3562 $self->{gii}->remove($rmpath);
3563 print "\tD\t$rmpath\n" unless $::_q;
4a87db0e 3564 }
9e3cdbd4 3565 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
3566 command_close_pipe($ls, $ctx);
3567 $self->{empty}->{$path} = 0
3568 } else {
ef3cfaad 3569 $self->{gii}->remove($gpath);
9e3cdbd4 3570 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 3571 }
27a1a801
EW
3572 undef;
3573}
3574
3575sub open_file {
3576 my ($self, $path, $pb, $rev) = @_;
b03a71a6
EW
3577 my ($mode, $blob);
3578
0d8bee71 3579 goto out if $self->is_path_ignored($path);
b03a71a6 3580
706587fc 3581 my $gpath = $self->git_path($path);
4f821012
EW
3582 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3583 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
006ede5e
EW
3584 unless (defined $mode && defined $blob) {
3585 die "$path was not found in commit $self->{c} (r$rev)\n";
3586 }
dbc6c74d
EW
3587 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3588 $mode = '120000';
3589 }
b03a71a6 3590out:
27a1a801 3591 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 3592 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
3593}
3594
3595sub add_file {
3596 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
b03a71a6
EW
3597 my $mode;
3598
0d8bee71 3599 if (!$self->is_path_ignored($path)) {
b03a71a6
EW
3600 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3601 delete $self->{empty}->{$dir};
3602 $mode = '100644';
3603 }
3604 { path => $path, mode_a => $mode, mode_b => $mode,
0864e3ba 3605 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
3606}
3607
d2a9a87b
EW
3608sub add_directory {
3609 my ($self, $path, $cp_path, $cp_rev) = @_;
0d8bee71 3610 goto out if $self->is_path_ignored($path);
12a6d752
EW
3611 my $gpath = $self->git_path($path);
3612 if ($gpath eq '') {
3613 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3614 -r --name-only -z/,
3615 $self->{c});
3616 local $/ = "\0";
3617 while (<$ls>) {
3618 chomp;
3619 $self->{gii}->remove($_);
3620 print "\tD\t$_\n" unless $::_q;
3621 }
3622 command_close_pipe($ls, $ctx);
3623 $self->{empty}->{$path} = 0;
3624 }
d2a9a87b
EW
3625 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3626 delete $self->{empty}->{$dir};
3627 $self->{empty}->{$path} = 1;
b03a71a6 3628out:
d2a9a87b
EW
3629 { path => $path };
3630}
3631
3632sub change_dir_prop {
3633 my ($self, $db, $prop, $value) = @_;
0d8bee71 3634 return undef if $self->is_path_ignored($db->{path});
d2a9a87b
EW
3635 $self->{dir_prop}->{$db->{path}} ||= {};
3636 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3637 undef;
3638}
3639
3640sub absent_directory {
3641 my ($self, $path, $pb) = @_;
0d8bee71 3642 return undef if $self->is_path_ignored($path);
d2a9a87b
EW
3643 $self->{absent_dir}->{$pb->{path}} ||= [];
3644 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3645 undef;
3646}
3647
3648sub absent_file {
3649 my ($self, $path, $pb) = @_;
0d8bee71 3650 return undef if $self->is_path_ignored($path);
d2a9a87b
EW
3651 $self->{absent_file}->{$pb->{path}} ||= [];
3652 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3653 undef;
3654}
3655
27a1a801
EW
3656sub change_file_prop {
3657 my ($self, $fb, $prop, $value) = @_;
0d8bee71 3658 return undef if $self->is_path_ignored($fb->{path});
27a1a801
EW
3659 if ($prop eq 'svn:executable') {
3660 if ($fb->{mode_b} != 120000) {
3661 $fb->{mode_b} = defined $value ? 100755 : 100644;
3662 }
3663 } elsif ($prop eq 'svn:special') {
3664 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
3665 } else {
3666 $self->{file_prop}->{$fb->{path}} ||= {};
3667 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
3668 }
3669 undef;
3670}
3671
3672sub apply_textdelta {
3673 my ($self, $fb, $exp) = @_;
0d8bee71 3674 return undef if $self->is_path_ignored($fb->{path});
1b3069a7 3675 my $fh = $::_repository->temp_acquire('svn_delta');
27a1a801
EW
3676 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3677 # (but $base does not,) so dup() it for reading in close_file
3678 open my $dup, '<&', $fh or croak $!;
1b3069a7 3679 my $base = $::_repository->temp_acquire('git_blob');
b03a71a6 3680
27a1a801 3681 if ($fb->{blob}) {
baf5fa8a
EW
3682 my ($base_is_link, $size);
3683
dbc6c74d
EW
3684 if ($fb->{mode_a} eq '120000' &&
3685 ! $self->{empty_symlinks}->{$fb->{path}}) {
3686 print $base 'link ' or die "print $!\n";
baf5fa8a 3687 $base_is_link = 1;
dbc6c74d 3688 }
baf5fa8a
EW
3689 retry:
3690 $size = $::_repository->cat_blob($fb->{blob}, $base);
d683a0e0 3691 die "Failed to read object $fb->{blob}" if ($size < 0);
27a1a801
EW
3692
3693 if (defined $exp) {
3694 seek $base, 0, 0 or croak $!;
8d7c4fad 3695 my $got = ::md5sum($base);
baf5fa8a
EW
3696 if ($got ne $exp) {
3697 my $err = "Checksum mismatch: ".
3698 "$fb->{path} $fb->{blob}\n" .
3699 "expected: $exp\n" .
3700 " got: $got\n";
3701 if ($base_is_link) {
3702 warn $err,
3703 "Retrying... (possibly ",
3704 "a bad symlink from SVN)\n";
3705 $::_repository->temp_reset($base);
3706 $base_is_link = 0;
3707 goto retry;
3708 }
3709 die $err;
3710 }
27a1a801
EW
3711 }
3712 }
3713 seek $base, 0, 0 or croak $!;
0b19138b 3714 $fb->{fh} = $fh;
27a1a801 3715 $fb->{base} = $base;
0b19138b 3716 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
27a1a801
EW
3717}
3718
3719sub close_file {
3720 my ($self, $fb, $exp) = @_;
0d8bee71 3721 return undef if $self->is_path_ignored($fb->{path});
b03a71a6 3722
27a1a801 3723 my $hash;
706587fc 3724 my $path = $self->git_path($fb->{path});
27a1a801 3725 if (my $fh = $fb->{fh}) {
7faf0686
EW
3726 if (defined $exp) {
3727 seek($fh, 0, 0) or croak $!;
8d7c4fad 3728 my $got = ::md5sum($fh);
7faf0686
EW
3729 if ($got ne $exp) {
3730 die "Checksum mismatch: $path\n",
3731 "expected: $exp\n got: $got\n";
3732 }
3733 }
27a1a801 3734 if ($fb->{mode_b} == 120000) {
510b0945 3735 sysseek($fh, 0, 0) or croak $!;
dbc6c74d 3736 my $rd = sysread($fh, my $buf, 5);
ffe256f9 3737
dbc6c74d
EW
3738 if (!defined $rd) {
3739 croak "sysread: $!\n";
3740 } elsif ($rd == 0) {
3741 warn "$path has mode 120000",
3742 " but it points to nothing\n",
3743 "converting to an empty file with mode",
3744 " 100644\n";
3745 $fb->{mode_b} = '100644';
3746 } elsif ($buf ne 'link ') {
510b0945 3747 warn "$path has mode 120000",
dbc6c74d 3748 " but is not a link\n";
510b0945 3749 } else {
1b3069a7
MS
3750 my $tmp_fh = $::_repository->temp_acquire(
3751 'svn_hash');
510b0945
MG
3752 my $res;
3753 while ($res = sysread($fh, my $str, 1024)) {
3754 my $out = syswrite($tmp_fh, $str, $res);
3755 defined($out) && $out == $res
3756 or croak("write ",
836ff95d 3757 Git::temp_path($tmp_fh),
510b0945
MG
3758 ": $!\n");
3759 }
3760 defined $res or croak $!;
ffe256f9 3761
510b0945
MG
3762 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3763 Git::temp_release($tmp_fh, 1);
3764 }
3765 }
0b19138b
MG
3766
3767 $hash = $::_repository->hash_and_insert_object(
836ff95d 3768 Git::temp_path($fh));
27a1a801 3769 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
0b19138b
MG
3770
3771 Git::temp_release($fb->{base}, 1);
510b0945 3772 Git::temp_release($fh, 1);
27a1a801
EW
3773 } else {
3774 $hash = $fb->{blob} or die "no blob information\n";
3775 }
3776 $fb->{pool}->clear;
ef3cfaad 3777 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 3778 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
3779 undef;
3780}
3781
3782sub abort_edit {
3783 my $self = shift;
ef3cfaad
EW
3784 $self->{nr} = $self->{gii}->{nr};
3785 delete $self->{gii};
27a1a801
EW
3786 $self->SUPER::abort_edit(@_);
3787}
3788
3789sub close_edit {
3790 my $self = shift;
dad73c0b 3791 $self->{git_commit_ok} = 1;
ef3cfaad
EW
3792 $self->{nr} = $self->{gii}->{nr};
3793 delete $self->{gii};
27a1a801
EW
3794 $self->SUPER::close_edit(@_);
3795}
1a82e793 3796
a5e0cedc 3797package SVN::Git::Editor;
24e22aa8 3798use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
3799use strict;
3800use warnings;
3801use Carp qw/croak/;
3802use IO::File;
3803
3804sub new {
61395354
EW
3805 my ($class, $opts) = @_;
3806 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3807 die "$_ required!\n" unless (defined $opts->{$_});
3808 }
3809
3810 my $pool = SVN::Pool->new;
3811 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3812 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3813 $opts->{r}, $mods);
3814
3815 # $opts->{ra} functions should not be used after this:
3816 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3817 $opts->{editor_cb}, $pool);
3818 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 3819 bless $self, $class;
61395354
EW
3820 foreach (qw/svn_path r tree_a tree_b/) {
3821 $self->{$_} = $opts->{$_};
a5e0cedc 3822 }
61395354
EW
3823 $self->{url} = $opts->{ra}->{url};
3824 $self->{mods} = $mods;
3825 $self->{types} = $types;
3826 $self->{pool} = $pool;
a5e0cedc
EW
3827 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3828 $self->{rm} = { };
d3a840dc
EW
3829 $self->{path_prefix} = length $self->{svn_path} ?
3830 "$self->{svn_path}/" : '';
128de657 3831 $self->{config} = $opts->{config};
a5e0cedc
EW
3832 return $self;
3833}
3834
61395354
EW
3835sub generate_diff {
3836 my ($tree_a, $tree_b) = @_;
3837 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
3838 if ($_cp_similarity) {
3839 push @diff_tree, "-C$_cp_similarity";
61395354
EW
3840 } else {
3841 push @diff_tree, '-C';
3842 }
24e22aa8
EW
3843 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3844 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
3845 push @diff_tree, $tree_a, $tree_b;
3846 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3847 local $/ = "\0";
3848 my $state = 'meta';
3849 my @mods;
3850 while (<$diff_fh>) {
3851 chomp $_; # this gets rid of the trailing "\0"
3852 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2d0c8acc 3853 ($::sha1)\s($::sha1)\s
61395354
EW
3854 ([MTCRAD])\d*$/xo) {
3855 push @mods, { mode_a => $1, mode_b => $2,
2d0c8acc
FW
3856 sha1_a => $3, sha1_b => $4,
3857 chg => $5 };
3858 if ($5 =~ /^(?:C|R)$/) {
61395354
EW
3859 $state = 'file_a';
3860 } else {
3861 $state = 'file_b';
3862 }
3863 } elsif ($state eq 'file_a') {
3864 my $x = $mods[$#mods] or croak "Empty array\n";
3865 if ($x->{chg} !~ /^(?:C|R)$/) {
3866 croak "Error parsing $_, $x->{chg}\n";
3867 }
3868 $x->{file_a} = $_;
3869 $state = 'file_b';
3870 } elsif ($state eq 'file_b') {
3871 my $x = $mods[$#mods] or croak "Empty array\n";
3872 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3873 croak "Error parsing $_, $x->{chg}\n";
3874 }
3875 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3876 croak "Error parsing $_, $x->{chg}\n";
3877 }
3878 $x->{file_b} = $_;
3879 $state = 'meta';
3880 } else {
3881 croak "Error parsing $_\n";
3882 }
3883 }
3884 command_close_pipe($diff_fh, $ctx);
3885 \@mods;
3886}
3887
3888sub check_diff_paths {
3889 my ($ra, $pfx, $rev, $mods) = @_;
3890 my %types;
3891 $pfx .= '/' if length $pfx;
3892
3893 sub type_diff_paths {
3894 my ($ra, $types, $path, $rev) = @_;
3895 my @p = split m#/+#, $path;
3896 my $c = shift @p;
3897 unless (defined $types->{$c}) {
3898 $types->{$c} = $ra->check_path($c, $rev);
3899 }
3900 while (@p) {
3901 $c .= '/' . shift @p;
3902 next if defined $types->{$c};
3903 $types->{$c} = $ra->check_path($c, $rev);
3904 }
3905 }
3906
3907 foreach my $m (@$mods) {
3908 foreach my $f (qw/file_a file_b/) {
3909 next unless defined $m->{$f};
3910 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3911 if (length $pfx.$dir && ! defined $types{$dir}) {
3912 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3913 }
3914 }
3915 }
3916 \%types;
3917}
3918
a5e0cedc
EW
3919sub split_path {
3920 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3921}
3922
3923sub repo_path {
d3a840dc
EW
3924 my ($self, $path) = @_;
3925 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
3926}
3927
3928sub url_path {
3929 my ($self, $path) = @_;
29633bb9 3930 if ($self->{url} =~ m#^https?://#) {
6a004d3f 3931 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
29633bb9 3932 }
6e8548cc 3933 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
3934}
3935
3936sub rmdirs {
61395354 3937 my ($self) = @_;
a5e0cedc
EW
3938 my $rm = $self->{rm};
3939 delete $rm->{''}; # we never delete the url we're tracking
3940 return unless %$rm;
3941
3942 foreach (keys %$rm) {
3943 my @d = split m#/#, $_;
3944 my $c = shift @d;
3945 $rm->{$c} = 1;
3946 while (@d) {
3947 $c .= '/' . shift @d;
3948 $rm->{$c} = 1;
3949 }
3950 }
3951 delete $rm->{$self->{svn_path}};
3952 delete $rm->{''}; # we never delete the url we're tracking
3953 return unless %$rm;
3954
61395354
EW
3955 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3956 $self->{tree_b});
a5e0cedc
EW
3957 local $/ = "\0";
3958 while (<$fh>) {
3959 chomp;
747fa12c 3960 my @dn = split m#/#, $_;
c07eee1f
EW
3961 while (pop @dn) {
3962 delete $rm->{join '/', @dn};
3963 }
3964 unless (%$rm) {
22600a25 3965 close $fh;
c07eee1f
EW
3966 return;
3967 }
a5e0cedc 3968 }
aef4e921 3969 command_close_pipe($fh, $ctx);
c07eee1f 3970
a5e0cedc
EW
3971 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3972 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3973 $self->close_directory($bat->{$d}, $p);
3974 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 3975 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
3976 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3977 delete $bat->{$d};
3978 }
3979}
3980
3981sub open_or_add_dir {
3982 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
3983 my $t = $self->{types}->{$full_path};
3984 if (!defined $t) {
3985 die "$full_path not known in r$self->{r} or we have a bug!\n";
3986 }
fd499bcc
ER
3987 {
3988 no warnings 'once';
3989 # SVN::Node::none and SVN::Node::file are used only once,
3990 # so we're shutting up Perl's warnings about them.
3991 if ($t == $SVN::Node::none) {
3992 return $self->add_directory($full_path, $baton,
3993 undef, -1, $self->{pool});
3994 } elsif ($t == $SVN::Node::dir) {
3995 return $self->open_directory($full_path, $baton,
3996 $self->{r}, $self->{pool});
3997 } # no warnings 'once'
3998 print STDERR "$full_path already exists in repository at ",
3999 "r$self->{r} and it is not a directory (",
4000 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4001 } # no warnings 'once'
a5e0cedc
EW
4002 exit 1;
4003}
4004
4005sub ensure_path {
4006 my ($self, $path) = @_;
4007 my $bat = $self->{bat};
6e8548cc
EW
4008 my $repo_path = $self->repo_path($path);
4009 return $bat->{''} unless (length $repo_path);
4010 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
4011 my $c = shift @p;
4012 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4013 while (@p) {
4014 my $c0 = $c;
4015 $c .= '/' . shift @p;
4016 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4017 }
4018 return $bat->{$c};
4019}
4020
128de657
BK
4021# Subroutine to convert a globbing pattern to a regular expression.
4022# From perl cookbook.
4023sub glob2pat {
4024 my $globstr = shift;
4025 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4026 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4027 return '^' . $globstr . '$';
4028}
4029
4030sub check_autoprop {
4031 my ($self, $pattern, $properties, $file, $fbat) = @_;
4032 # Convert the globbing pattern to a regular expression.
4033 my $regex = glob2pat($pattern);
4034 # Check if the pattern matches the file name.
4035 if($file =~ m/($regex)/) {
4036 # Parse the list of properties to set.
4037 my @props = split(/;/, $properties);
4038 foreach my $prop (@props) {
4039 # Parse 'name=value' syntax and set the property.
4040 if ($prop =~ /([^=]+)=(.*)/) {
4041 my ($n,$v) = ($1,$2);
4042 for ($n, $v) {
4043 s/^\s+//; s/\s+$//;
4044 }
4045 $self->change_file_prop($fbat, $n, $v);
4046 }
4047 }
4048 }
4049}
4050
4051sub apply_autoprops {
4052 my ($self, $file, $fbat) = @_;
4053 my $conf_t = ${$self->{config}}{'config'};
4054 no warnings 'once';
4055 # Check [miscellany]/enable-auto-props in svn configuration.
4056 if (SVN::_Core::svn_config_get_bool(
4057 $conf_t,
4058 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4059 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4060 0)) {
4061 # Auto-props are enabled. Enumerate them to look for matches.
4062 my $callback = sub {
4063 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4064 };
4065 SVN::_Core::svn_config_enumerate(
4066 $conf_t,
4067 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4068 $callback);
4069 }
4070}
4071
a5e0cedc 4072sub A {
44320b9e 4073 my ($self, $m) = @_;
a5e0cedc
EW
4074 my ($dir, $file) = split_path($m->{file_b});
4075 my $pbat = $self->ensure_path($dir);
4076 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4077 undef, -1);
44320b9e 4078 print "\tA\t$m->{file_b}\n" unless $::_q;
128de657 4079 $self->apply_autoprops($file, $fbat);
a5e0cedc
EW
4080 $self->chg_file($fbat, $m);
4081 $self->close_file($fbat,undef,$self->{pool});
4082}
4083
4084sub C {
44320b9e 4085 my ($self, $m) = @_;
a5e0cedc
EW
4086 my ($dir, $file) = split_path($m->{file_b});
4087 my $pbat = $self->ensure_path($dir);
4088 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4089 $self->url_path($m->{file_a}), $self->{r});
44320b9e 4090 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
4091 $self->chg_file($fbat, $m);
4092 $self->close_file($fbat,undef,$self->{pool});
4093}
4094
4095sub delete_entry {
4096 my ($self, $path, $pbat) = @_;
4097 my $rpath = $self->repo_path($path);
4098 my ($dir, $file) = split_path($rpath);
4099 $self->{rm}->{$dir} = 1;
4100 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4101}
4102
4103sub R {
44320b9e 4104 my ($self, $m) = @_;
a5e0cedc
EW
4105 my ($dir, $file) = split_path($m->{file_b});
4106 my $pbat = $self->ensure_path($dir);
4107 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4108 $self->url_path($m->{file_a}), $self->{r});
44320b9e 4109 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
7c4d0219 4110 $self->apply_autoprops($file, $fbat);
a5e0cedc
EW
4111 $self->chg_file($fbat, $m);
4112 $self->close_file($fbat,undef,$self->{pool});
4113
4114 ($dir, $file) = split_path($m->{file_a});
4115 $pbat = $self->ensure_path($dir);
4116 $self->delete_entry($m->{file_a}, $pbat);
4117}
4118
4119sub M {
44320b9e 4120 my ($self, $m) = @_;
a5e0cedc
EW
4121 my ($dir, $file) = split_path($m->{file_b});
4122 my $pbat = $self->ensure_path($dir);
4123 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4124 $pbat,$self->{r},$self->{pool});
44320b9e 4125 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
4126 $self->chg_file($fbat, $m);
4127 $self->close_file($fbat,undef,$self->{pool});
4128}
4129
4130sub T { shift->M(@_) }
4131
4132sub change_file_prop {
4133 my ($self, $fbat, $pname, $pval) = @_;
4134 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4135}
4136
214a34d2
FW
4137sub _chg_file_get_blob ($$$$) {
4138 my ($self, $fbat, $m, $which) = @_;
1b3069a7 4139 my $fh = $::_repository->temp_acquire("git_blob_$which");
214a34d2 4140 if ($m->{"mode_$which"} =~ /^120/) {
a5e0cedc
EW
4141 print $fh 'link ' or croak $!;
4142 $self->change_file_prop($fbat,'svn:special','*');
214a34d2 4143 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
a5e0cedc
EW
4144 $self->change_file_prop($fbat,'svn:special',undef);
4145 }
214a34d2
FW
4146 my $blob = $m->{"sha1_$which"};
4147 return ($fh,) if ($blob =~ /^0{40}$/);
4148 my $size = $::_repository->cat_blob($blob, $fh);
4149 croak "Failed to read object $blob" if ($size < 0);
a5e0cedc
EW
4150 $fh->flush == 0 or croak $!;
4151 seek $fh, 0, 0 or croak $!;
4152
8d7c4fad 4153 my $exp = ::md5sum($fh);
a5e0cedc 4154 seek $fh, 0, 0 or croak $!;
214a34d2
FW
4155 return ($fh, $exp);
4156}
a5e0cedc 4157
214a34d2
FW
4158sub chg_file {
4159 my ($self, $fbat, $m) = @_;
4160 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4161 $self->change_file_prop($fbat,'svn:executable','*');
4162 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4163 $self->change_file_prop($fbat,'svn:executable',undef);
4164 }
8598db93
FW
4165 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4166 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
f7197dff 4167 my $pool = SVN::Pool->new;
8598db93
FW
4168 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4169 if (-s $fh_a) {
4170 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
991255c6
EW
4171 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4172 if (defined $res) {
4173 die "Unexpected result from send_txstream: $res\n",
4174 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4175 }
8598db93
FW
4176 } else {
4177 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4178 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4179 if ($got ne $exp_b);
4180 }
4181 Git::temp_release($fh_b, 1);
4182 Git::temp_release($fh_a, 1);
f7197dff 4183 $pool->clear;
a5e0cedc
EW
4184}
4185
4186sub D {
44320b9e 4187 my ($self, $m) = @_;
a5e0cedc
EW
4188 my ($dir, $file) = split_path($m->{file_b});
4189 my $pbat = $self->ensure_path($dir);
44320b9e 4190 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
4191 $self->delete_entry($m->{file_b}, $pbat);
4192}
4193
4194sub close_edit {
4195 my ($self) = @_;
4196 my ($p,$bat) = ($self->{pool}, $self->{bat});
4197 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
6442754d 4198 next if $_ eq '';
a5e0cedc
EW
4199 $self->close_directory($bat->{$_}, $p);
4200 }
6442754d 4201 $self->close_directory($bat->{''}, $p);
a5e0cedc
EW
4202 $self->SUPER::close_edit($p);
4203 $p->clear;
4204}
4205
4206sub abort_edit {
4207 my ($self) = @_;
4208 $self->SUPER::abort_edit($self->{pool});
61395354
EW
4209}
4210
4211sub DESTROY {
4212 my $self = shift;
4213 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
4214 $self->{pool}->clear;
4215}
4216
44320b9e
EW
4217# this drives the editor
4218sub apply_diff {
61395354
EW
4219 my ($self) = @_;
4220 my $mods = $self->{mods};
44320b9e 4221 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 4222 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
4223 my $f = $m->{chg};
4224 if (defined $o{$f}) {
4225 $self->$f($m);
4226 } else {
207f1a75 4227 fatal("Invalid change type: $f");
44320b9e
EW
4228 }
4229 }
24e22aa8 4230 $self->rmdirs if $_rmdir;
6e8548cc 4231 if (@$mods == 0) {
44320b9e
EW
4232 $self->abort_edit;
4233 } else {
4234 $self->close_edit;
4235 }
6e8548cc 4236 return scalar @$mods;
44320b9e
EW
4237}
4238
d81bf827 4239package Git::SVN::Ra;
6af1db44 4240use vars qw/@ISA $config_dir $_log_window_size/;
d81bf827
EW
4241use strict;
4242use warnings;
a51cdb0c 4243my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
d81bf827
EW
4244
4245BEGIN {
4246 # enforce temporary pool usage for some simple functions
c5f71ad0 4247 no strict 'refs';
bf8a40b8
EW
4248 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4249 get_file/) {
c5f71ad0
SV
4250 my $SUPER = "SUPER::$f";
4251 *$f = sub {
4252 my $self = shift;
4253 my $pool = SVN::Pool->new;
4254 my @ret = $self->$SUPER(@_,$pool);
4255 $pool->clear;
4256 wantarray ? @ret : $ret[0];
4257 };
d81bf827 4258 }
d81bf827
EW
4259}
4260
9ff74e95
SW
4261sub _auth_providers () {
4262 [
4263 SVN::Client::get_simple_provider(),
4264 SVN::Client::get_ssl_server_trust_file_provider(),
4265 SVN::Client::get_simple_prompt_provider(
4266 \&Git::SVN::Prompt::simple, 2),
4267 SVN::Client::get_ssl_client_cert_file_provider(),
4268 SVN::Client::get_ssl_client_cert_prompt_provider(
4269 \&Git::SVN::Prompt::ssl_client_cert, 2),
77266e96 4270 SVN::Client::get_ssl_client_cert_pw_file_provider(),
9ff74e95
SW
4271 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4272 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4273 SVN::Client::get_username_provider(),
4274 SVN::Client::get_ssl_server_trust_prompt_provider(
4275 \&Git::SVN::Prompt::ssl_server_trust),
4276 SVN::Client::get_username_prompt_provider(
4277 \&Git::SVN::Prompt::username, 2)
4278 ]
4279}
4280
cfbe7ab3
EW
4281sub escape_uri_only {
4282 my ($uri) = @_;
4283 my @tmp;
4284 foreach (split m{/}, $uri) {
6a004d3f 4285 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
cfbe7ab3
EW
4286 push @tmp, $_;
4287 }
4288 join('/', @tmp);
4289}
4290
4291sub escape_url {
4292 my ($url) = @_;
4293 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4294 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4295 $url = "$scheme://$domain$uri";
4296 }
4297 $url;
4298}
4299
d81bf827
EW
4300sub new {
4301 my ($class, $url) = @_;
f6f09876 4302 $url =~ s!/+$!!;
5d3b7cd5 4303 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 4304
d81bf827 4305 SVN::_Core::svn_config_ensure($config_dir, undef);
9ff74e95 4306 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
d81bf827 4307 my $config = SVN::Core::config_get_config($config_dir);
7730fbe6 4308 $RA = undef;
602015e0
ER
4309 my $dont_store_passwords = 1;
4310 my $conf_t = ${$config}{'config'};
4311 {
fd499bcc 4312 no warnings 'once';
602015e0
ER
4313 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4314 # produces warnings that variables are used only once.
4315 # I had not found the better way to shut them up, so
fd499bcc 4316 # the warnings of type 'once' are disabled in this block.
602015e0
ER
4317 if (SVN::_Core::svn_config_get_bool($conf_t,
4318 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4319 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4320 1) == 0) {
4321 SVN::_Core::svn_auth_set_parameter($baton,
4322 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4323 bless (\$dont_store_passwords, "_p_void"));
4324 }
4325 if (SVN::_Core::svn_config_get_bool($conf_t,
4326 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4327 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4328 1) == 0) {
4329 $Git::SVN::Prompt::_no_auth_cache = 1;
4330 }
fd499bcc 4331 } # no warnings 'once'
cfbe7ab3 4332 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
d81bf827
EW
4333 config => $config,
4334 pool => SVN::Pool->new,
4335 auth_provider_callbacks => $callbacks);
cfbe7ab3 4336 $self->{url} = $url;
d81bf827
EW
4337 $self->{svn_path} = $url;
4338 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 4339 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
0dc03d6a
EW
4340 $self->{cache} = { check_path => { r => 0, data => {} },
4341 get_dir => { r => 0, data => {} } };
5d3b7cd5 4342 $RA = bless $self, $class;
d81bf827
EW
4343}
4344
0dc03d6a
EW
4345sub check_path {
4346 my ($self, $path, $r) = @_;
4347 my $cache = $self->{cache}->{check_path};
4348 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4349 return $cache->{data}->{$path};
4350 }
4351 my $pool = SVN::Pool->new;
4352 my $t = $self->SUPER::check_path($path, $r, $pool);
4353 $pool->clear;
4354 if ($r != $cache->{r}) {
4355 %{$cache->{data}} = ();
4356 $cache->{r} = $r;
4357 }
4358 $cache->{data}->{$path} = $t;
4359}
4360
4361sub get_dir {
4362 my ($self, $dir, $r) = @_;
4363 my $cache = $self->{cache}->{get_dir};
4364 if ($r == $cache->{r}) {
4365 if (my $x = $cache->{data}->{$dir}) {
4366 return wantarray ? @$x : $x->[0];
4367 }
4368 }
4369 my $pool = SVN::Pool->new;
4370 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4371 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4372 $pool->clear;
4373 if ($r != $cache->{r}) {
4374 %{$cache->{data}} = ();
4375 $cache->{r} = $r;
4376 }
4377 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4378 wantarray ? (\%dirents, $r, $props) : \%dirents;
4379}
4380
d81bf827 4381sub DESTROY {
5d3b7cd5 4382 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
4383}
4384
1ef626b4
EW
4385# get_log(paths, start, end, limit,
4386# discover_changed_paths, strict_node_history, receiver)
d81bf827
EW
4387sub get_log {
4388 my ($self, @args) = @_;
4389 my $pool = SVN::Pool->new;
1ef626b4
EW
4390
4391 # the limit parameter was not supported in SVN 1.1.x, so we
4392 # drop it. Therefore, the receiver callback passed to it
4393 # is made aware of this limitation by being wrapped if
4394 # the limit passed to is being wrapped.
4395 if ($SVN::Core::VERSION le '1.2.0') {
4396 my $limit = splice(@args, 3, 1);
4397 if ($limit > 0) {
4398 my $receiver = pop @args;
4399 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4400 }
4401 }
d81bf827
EW
4402 my $ret = $self->SUPER::get_log(@args, $pool);
4403 $pool->clear;
4404 $ret;
4405}
4406
9ff74e95
SW
4407sub trees_match {
4408 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4409 my $ctx = SVN::Client->new(auth => _auth_providers);
4410 my $out = IO::File->new_tmpfile;
4411
4412 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4413 # $ctx->diff(), so we'll create a default one
4414 my $pool = SVN::Pool->new_default_sub;
4415
4416 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4417 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4418 $out->flush;
4419 my $ret = (($out->stat)[7] == 0);
4420 close $out or croak $!;
4421
4422 $ret;
4423}
4424
d81bf827 4425sub get_commit_editor {
44320b9e 4426 my ($self, $log, $cb, $pool) = @_;
d81bf827 4427 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 4428 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
4429}
4430
d81bf827 4431sub gs_do_update {
8a603774
EW
4432 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4433 my $new = ($rev_a == $rev_b);
4434 my $path = $gs->{path};
4435
2e5e2480
EW
4436 if ($new && -e $gs->{index}) {
4437 unlink $gs->{index} or die
4438 "Couldn't unlink index: $gs->{index}: $!\n";
4439 }
d81bf827 4440 my $pool = SVN::Pool->new;
8b8fc068 4441 $editor->set_path_strip($path);
2b27f6c8
EW
4442 my (@pc) = split m#/#, $path;
4443 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 4444 1, $editor, $pool);
d81bf827 4445 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
4446
4447 # Since we can't rely on svn_ra_reparent being available, we'll
4448 # just have to do some magic with set_path to make it so
4449 # we only want a partial path.
4450 my $sp = '';
4451 my $final = join('/', @pc);
4452 while (@pc) {
4453 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4454 $sp .= '/' if length $sp;
4455 $sp .= shift @pc;
4456 }
4457 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4458
2b27f6c8
EW
4459 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4460
d81bf827
EW
4461 $reporter->finish_report($pool);
4462 $pool->clear;
4463 $editor->{git_commit_ok};
4464}
4465
2b27f6c8
EW
4466# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4467# svn_ra_reparent didn't work before 1.4)
d81bf827 4468sub gs_do_switch {
8a603774
EW
4469 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4470 my $path = $gs->{path};
d81bf827 4471 my $pool = SVN::Pool->new;
2b27f6c8
EW
4472
4473 my $full_url = $self->{url};
4474 my $old_url = $full_url;
cfbe7ab3 4475 $full_url .= '/' . escape_uri_only($path) if length $path;
5d3b7cd5 4476 my ($ra, $reparented);
ad0a82ba
AB
4477
4478 if ($old_url =~ m#^svn(\+ssh)?://#) {
4479 $_[0] = undef;
4480 $self = undef;
4481 $RA = undef;
4482 $ra = Git::SVN::Ra->new($full_url);
4483 $ra_invalid = 1;
4484 } elsif ($old_url ne $full_url) {
4485 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4486 $self->{url} = $full_url;
4487 $reparented = 1;
5d3b7cd5 4488 }
ad0a82ba 4489
5d3b7cd5 4490 $ra ||= $self;
f4392df4 4491 $url_b = escape_url($url_b);
8a603774 4492 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 4493 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 4494 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 4495 $reporter->finish_report($pool);
2b27f6c8 4496
5d3b7cd5
EW
4497 if ($reparented) {
4498 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4499 $self->{url} = $old_url;
4500 }
2b27f6c8 4501
d81bf827
EW
4502 $pool->clear;
4503 $editor->{git_commit_ok};
4504}
4505
b54a901e
EW
4506sub longest_common_path {
4507 my ($gsv, $globs) = @_;
d2ae1434 4508 my %common;
e518192f
EW
4509 my $common_max = scalar @$gsv;
4510
4511 foreach my $gs (@$gsv) {
d2ae1434
EW
4512 my @tmp = split m#/#, $gs->{path};
4513 my $p = '';
4514 foreach (@tmp) {
4515 $p .= length($p) ? "/$_" : $_;
4516 $common{$p} ||= 0;
4517 $common{$p}++;
4518 }
4519 }
e518192f
EW
4520 $globs ||= [];
4521 $common_max += scalar @$globs;
4522 foreach my $glob (@$globs) {
4523 my @tmp = split m#/#, $glob->{path}->{left};
4524 my $p = '';
4525 foreach (@tmp) {
4526 $p .= length($p) ? "/$_" : $_;
4527 $common{$p} ||= 0;
4528 $common{$p}++;
4529 }
4530 }
4531
d2ae1434
EW
4532 my $longest_path = '';
4533 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 4534 if ($common{$_} == $common_max) {
d2ae1434
EW
4535 $longest_path = $_;
4536 last;
4537 }
0af9c9f9 4538 }
b54a901e
EW
4539 $longest_path;
4540}
4541
4542sub gs_fetch_loop_common {
4543 my ($self, $base, $head, $gsv, $globs) = @_;
4544 return if ($base > $head);
4545 my $inc = $_log_window_size;
4546 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4547 my $longest_path = longest_common_path($gsv, $globs);
a51cdb0c 4548 my $ra_url = $self->{url};
c69700fe 4549 my $find_trailing_edge;
0af9c9f9 4550 while (1) {
d4eff2bd 4551 my %revs;
d2ae1434 4552 my $err;
f7c3fc4a 4553 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
4554 $SVN::Error::handler = sub {
4555 ($err) = @_;
4556 skip_unknown_revs($err);
4557 };
4558 sub _cb {
4559 my ($paths, $r, $author, $date, $log) = @_;
4560 [ dup_changed_paths($paths),
4561 { author => $author, date => $date, log => $log } ];
4562 }
4563 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4564 sub { $revs{$_[1]} = _cb(@_) });
99366565
DM
4565 if ($err) {
4566 print "Checked through r$max\r";
c69700fe
AV
4567 } else {
4568 $find_trailing_edge = 1;
99366565 4569 }
c69700fe 4570 if ($err and $find_trailing_edge) {
d2ae1434
EW
4571 print STDERR "Path '$longest_path' ",
4572 "was probably deleted:\n",
4573 $err->expanded_message,
4574 "\nWill attempt to follow ",
4575 "revisions r$min .. r$max ",
4576 "committed before the deletion\n";
4577 my $hi = $max;
4578 while (--$hi >= $min) {
4579 my $ok;
4580 $self->get_log([$longest_path], $min, $hi,
4581 0, 1, 1, sub {
b6c61778 4582 $ok = $_[1];
d2ae1434
EW
4583 $revs{$_[1]} = _cb(@_) });
4584 if ($ok) {
4585 print STDERR "r$min .. r$ok OK\n";
4586 last;
4587 }
4588 }
c69700fe 4589 $find_trailing_edge = 0;
d2ae1434 4590 }
d4eff2bd 4591 $SVN::Error::handler = $err_handler;
fbcc1737 4592
e518192f 4593 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 4594 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 4595 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
4596
4597 foreach my $gs ($self->match_globs(\%exists, $paths,
4598 $globs, $r)) {
060610c5 4599 if ($gs->rev_map_max >= $r) {
fbcc1737
EW
4600 next;
4601 }
4602 next unless $gs->match_paths($paths, $r);
4603 $gs->{logged_rev_props} = $logged;
e8d120bd
EW
4604 if (my $last_commit = $gs->last_commit) {
4605 $gs->assert_index_clean($last_commit);
4606 }
fbcc1737
EW
4607 my $log_entry = $gs->do_fetch($paths, $r);
4608 if ($log_entry) {
0af9c9f9
EW
4609 $gs->do_git_commit($log_entry);
4610 }
321b1842 4611 $INDEX_FILES{$gs->{index}} = 1;
0af9c9f9 4612 }
e518192f 4613 foreach my $g (@$globs) {
93f2689c
EW
4614 my $k = "svn-remote.$g->{remote}." .
4615 "$g->{t}-maxRev";
4616 Git::SVN::tmp_config($k, $r);
e518192f 4617 }
a51cdb0c
EW
4618 if ($ra_invalid) {
4619 $_[0] = undef;
4620 $self = undef;
4621 $RA = undef;
4622 $self = Git::SVN::Ra->new($ra_url);
4623 $ra_invalid = undef;
4624 }
0af9c9f9 4625 }
9c93fee5
EW
4626 # pre-fill the .rev_db since it'll eventually get filled in
4627 # with '0' x40 if something new gets committed
e518192f 4628 foreach my $gs (@$gsv) {
66ab84b9
EW
4629 next if $gs->rev_map_max >= $max;
4630 next if defined $gs->rev_map_get($max);
4631 $gs->rev_map_set($max, 0 x40);
9c93fee5 4632 }
c3560e53
EW
4633 foreach my $g (@$globs) {
4634 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4635 Git::SVN::tmp_config($k, $max);
4636 }
0af9c9f9
EW
4637 last if $max >= $head;
4638 $min = $max + 1;
4639 $max += $inc;
4640 $max = $head if ($max > $head);
4641 }
94bc914c 4642 Git::SVN::gc();
0af9c9f9
EW
4643}
4644
570d35c2
MG
4645sub get_dir_globbed {
4646 my ($self, $left, $depth, $r) = @_;
4647
4648 my @x = eval { $self->get_dir($left, $r) };
4649 return unless scalar @x == 3;
4650 my $dirents = $x[0];
4651 my @finalents;
4652 foreach my $de (keys %$dirents) {
4653 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4654 if ($depth > 1) {
4655 my @args = ("$left/$de", $depth - 1, $r);
4656 foreach my $dir ($self->get_dir_globbed(@args)) {
4657 push @finalents, "$de/$dir";
4658 }
4659 } else {
4660 push @finalents, $de;
4661 }
4662 }
4663 @finalents;
4664}
4665
e518192f
EW
4666sub match_globs {
4667 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
4668
4669 sub get_dir_check {
4670 my ($self, $exists, $g, $r) = @_;
570d35c2
MG
4671
4672 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4673 $g->{path}->{depth},
4674 $r);
4675
4676 foreach my $de (@dirs) {
74a81227
EW
4677 my $p = $g->{path}->full_path($de);
4678 next if $exists->{$p};
4679 next if (length $g->{path}->{right} &&
4680 ($self->check_path($p, $r) !=
4681 $SVN::Node::dir));
4682 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4683 $g->{ref}->full_path($de), 1);
4684 }
4685 }
e518192f 4686 foreach my $g (@$globs) {
74a81227
EW
4687 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4688 if ($path->{action} =~ /^[AR]$/) {
4689 get_dir_check($self, $exists, $g, $r);
4690 }
4691 }
e518192f 4692 foreach (keys %$paths) {
28710f74
EW
4693 if (/$g->{path}->{left_regex}/ &&
4694 !/$g->{path}->{regex}/) {
74a81227
EW
4695 next if $paths->{$_}->{action} !~ /^[AR]$/;
4696 get_dir_check($self, $exists, $g, $r);
4697 }
e518192f
EW
4698 next unless /$g->{path}->{regex}/;
4699 my $p = $1;
4700 my $pathname = $g->{path}->full_path($p);
4701 next if $exists->{$pathname};
0c1ec5a1
EW
4702 next if ($self->check_path($pathname, $r) !=
4703 $SVN::Node::dir);
e518192f
EW
4704 $exists->{$pathname} = Git::SVN->init(
4705 $self->{url}, $pathname, undef,
4706 $g->{ref}->full_path($p), 1);
4707 }
4708 my $c = '';
4709 foreach (split m#/#, $g->{path}->{left}) {
4710 $c .= "/$_";
4711 next unless ($paths->{$c} &&
74a81227
EW
4712 ($paths->{$c}->{action} =~ /^[AR]$/));
4713 get_dir_check($self, $exists, $g, $r);
e518192f
EW
4714 }
4715 }
4716 values %$exists;
4717}
4718
e6434f87
EW
4719sub minimize_url {
4720 my ($self) = @_;
4721 return $self->{url} if ($self->{url} eq $self->{repos_root});
4722 my $url = $self->{repos_root};
4723 my @components = split(m!/!, $self->{svn_path});
4724 my $c = '';
4725 do {
4726 $url .= "/$c" if length $c;
4727 eval { (ref $self)->new($url)->get_latest_revnum };
4728 } while ($@ && ($c = shift @components));
4729 $url;
4730}
4731
d81bf827
EW
4732sub can_do_switch {
4733 my $self = shift;
4734 unless (defined $can_do_switch) {
4735 my $pool = SVN::Pool->new;
4736 my $rep = eval {
4737 $self->do_switch(1, '', 0, $self->{url},
4738 SVN::Delta::Editor->new, $pool);
4739 };
4740 if ($@) {
4741 $can_do_switch = 0;
4742 } else {
4743 $rep->abort_report($pool);
4744 $can_do_switch = 1;
4745 }
4746 $pool->clear;
4747 }
4748 $can_do_switch;
4749}
4750
0af9c9f9
EW
4751sub skip_unknown_revs {
4752 my ($err) = @_;
4753 my $errno = $err->apr_err();
4754 # Maybe the branch we're tracking didn't
4755 # exist when the repo started, so it's
4756 # not an error if it doesn't, just continue
4757 #
4758 # Wonderfully consistent library, eh?
4759 # 160013 - svn:// and file://
4760 # 175002 - http(s)://
4761 # 175007 - http(s):// (this repo required authorization, too...)
4762 # More codes may be discovered later...
4763 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
a6a15a99
EW
4764 my $err_key = $err->expanded_message;
4765 # revision numbers change every time, filter them out
4766 $err_key =~ s/\d+/\0/g;
4767 $err_key = "$errno\0$err_key";
4768 unless ($ignored_err{$err_key}) {
4769 warn "W: Ignoring error from SVN, path probably ",
4770 "does not exist: ($errno): ",
4771 $err->expanded_message,"\n";
eee8a174
EW
4772 warn "W: Do not be alarmed at the above message ",
4773 "git-svn is just searching aggressively for ",
4774 "old history.\n",
4775 "This may take a while on large repositories\n";
a6a15a99
EW
4776 $ignored_err{$err_key} = 1;
4777 }
0af9c9f9
EW
4778 return;
4779 }
4780 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4781}
4782
4783# svn_log_changed_path_t objects passed to get_log are likely to be
4784# overwritten even if only the refs are copied to an external variable,
4785# so we should dup the structures in their entirety. Using an externally
4786# passed pool (instead of our temporary and quickly cleared pool in
4787# Git::SVN::Ra) does not help matters at all...
4788sub dup_changed_paths {
4789 my ($paths) = @_;
4790 return undef unless $paths;
4791 my %ret;
4792 foreach my $p (keys %$paths) {
4793 my $i = $paths->{$p};
4794 my %s = map { $_ => $i->$_ }
4795 qw/copyfrom_path copyfrom_rev action/;
4796 $ret{$p} = \%s;
4797 }
4798 \%ret;
4799}
4800
f8c9d1d2
EW
4801package Git::SVN::Log;
4802use strict;
4803use warnings;
4804use POSIX qw/strftime/;
e8717841 4805use Time::Local;
111947ef 4806use constant commit_log_separator => ('-' x 72) . "\n";
f8c9d1d2
EW
4807use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4808 %rusers $show_commit $incremental/;
4809my $l_fmt;
4810
4811sub cmt_showable {
4812 my ($c) = @_;
4813 return 1 if defined $c->{r};
c16d0871
EW
4814
4815 # big commit message got truncated by the 16k pretty buffer in rev-list
f8c9d1d2
EW
4816 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4817 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
c16d0871 4818 @{$c->{l}} = ();
44320b9e 4819 my @log = command(qw/cat-file commit/, $c->{c});
c16d0871
EW
4820
4821 # shift off the headers
4822 shift @log while ($log[0] ne '');
44320b9e 4823 shift @log;
c16d0871
EW
4824
4825 # TODO: make $c->{l} not have a trailing newline in the future
4826 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
4827
4828 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 4829 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
4830 }
4831 return defined $c->{r};
4832}
4833
4834sub log_use_color {
cd459e3f 4835 return $color || Git->repository->get_colorbool('color.diff');
f8c9d1d2
EW
4836}
4837
4838sub git_svn_log_cmd {
3bc718ba
EW
4839 my ($r_min, $r_max, @args) = @_;
4840 my $head = 'HEAD';
6ed77266 4841 my (@files, @log_opts);
3bc718ba 4842 foreach my $x (@args) {
6ed77266
EW
4843 if ($x eq '--' || @files) {
4844 push @files, $x;
4845 } else {
4846 if (::verify_ref("$x^0")) {
4847 $head = $x;
4848 } else {
4849 push @log_opts, $x;
4850 }
4851 }
3bc718ba
EW
4852 }
4853
13c823fb
EW
4854 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4855 $gs ||= Git::SVN->_new;
f8c9d1d2
EW
4856 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4857 $gs->refname);
4858 push @cmd, '-r' unless $non_recursive;
4859 push @cmd, qw/--raw --name-status/ if $verbose;
4860 push @cmd, '--color' if log_use_color();
6ed77266
EW
4861 push @cmd, @log_opts;
4862 if (defined $r_max && $r_max == $r_min) {
f8c9d1d2 4863 push @cmd, '--max-count=1';
060610c5 4864 if (my $c = $gs->rev_map_get($r_max)) {
f8c9d1d2
EW
4865 push @cmd, $c;
4866 }
6ed77266 4867 } elsif (defined $r_max) {
111947ef
DK
4868 if ($r_max < $r_min) {
4869 ($r_min, $r_max) = ($r_max, $r_min);
4870 }
4871 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4872 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4873 # If there are no commits in the range, both $c_max and $c_min
4874 # will be undefined. If there is at least 1 commit in the
4875 # range, both will be defined.
4876 return () if !defined $c_min || !defined $c_max;
4877 if ($c_min eq $c_max) {
4878 push @cmd, '--max-count=1', $c_min;
f8c9d1d2 4879 } else {
111947ef 4880 push @cmd, '--boundary', "$c_min..$c_max";
f8c9d1d2
EW
4881 }
4882 }
6ed77266 4883 return (@cmd, @files);
f8c9d1d2
EW
4884}
4885
4886# adapted from pager.c
4887sub config_pager {
4888 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4889 if (!defined $pager) {
4890 $pager = 'less';
4891 } elsif (length $pager == 0 || $pager eq 'cat') {
4892 $pager = undef;
4893 }
cd459e3f 4894 $ENV{GIT_PAGER_IN_USE} = defined($pager);
f8c9d1d2
EW
4895}
4896
4897sub run_pager {
b0193048 4898 return unless -t *STDOUT && defined $pager;
971e6283 4899 pipe my ($rfd, $wfd) or return;
207f1a75 4900 defined(my $pid = fork) or ::fatal "Can't fork: $!";
f8c9d1d2
EW
4901 if (!$pid) {
4902 open STDOUT, '>&', $wfd or
207f1a75 4903 ::fatal "Can't redirect to stdout: $!";
f8c9d1d2
EW
4904 return;
4905 }
207f1a75 4906 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
f8c9d1d2 4907 $ENV{LESS} ||= 'FRSX';
207f1a75 4908 exec $pager or ::fatal "Can't run pager: $! ($pager)";
f8c9d1d2
EW
4909}
4910
b2b3ada7 4911sub format_svn_date {
e8717841 4912 # some systmes don't handle or mishandle %z, so be creative.
736e619a 4913 my $t = shift || time;
e8717841
BW
4914 my $gm = timelocal(gmtime($t));
4915 my $sign = qw( + + - )[ $t <=> $gm ];
4916 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4917 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
b2b3ada7
DK
4918}
4919
4920sub parse_git_date {
4921 my ($t, $tz) = @_;
4922 # Date::Parse isn't in the standard Perl distro :(
4923 if ($tz =~ s/^\+//) {
4924 $t += tz_to_s_offset($tz);
4925 } elsif ($tz =~ s/^\-//) {
4926 $t -= tz_to_s_offset($tz);
4927 }
4928 return $t;
4929}
4930
4931sub set_local_timezone {
4932 if (defined $TZ) {
4933 $ENV{TZ} = $TZ;
4934 } else {
4935 delete $ENV{TZ};
4936 }
4937}
4938
21819a37
EW
4939sub tz_to_s_offset {
4940 my ($tz) = @_;
4941 $tz =~ s/(\d\d)$//;
4942 return ($1 * 60) + ($tz * 3600);
4943}
4944
f8c9d1d2
EW
4945sub get_author_info {
4946 my ($dest, $author, $t, $tz) = @_;
4947 $author =~ s/(?:^\s*|\s*$)//g;
4948 $dest->{a_raw} = $author;
4949 my $au;
1c8443b0 4950 if ($::_authors) {
f8c9d1d2
EW
4951 $au = $rusers{$author} || undef;
4952 }
4953 if (!$au) {
4954 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4955 }
4956 $dest->{t} = $t;
4957 $dest->{tz} = $tz;
4958 $dest->{a} = $au;
b2b3ada7 4959 $dest->{t_utc} = parse_git_date($t, $tz);
f8c9d1d2
EW
4960}
4961
4962sub process_commit {
4963 my ($c, $r_min, $r_max, $defer) = @_;
4964 if (defined $r_min && defined $r_max) {
4965 if ($r_min == $c->{r} && $r_min == $r_max) {
4966 show_commit($c);
4967 return 0;
4968 }
4969 return 1 if $r_min == $r_max;
4970 if ($r_min < $r_max) {
4971 # we need to reverse the print order
4972 return 0 if (defined $limit && --$limit < 0);
4973 push @$defer, $c;
4974 return 1;
4975 }
4976 if ($r_min != $r_max) {
4977 return 1 if ($r_min < $c->{r});
4978 return 1 if ($r_max > $c->{r});
4979 }
4980 }
4981 return 0 if (defined $limit && --$limit < 0);
4982 show_commit($c);
4983 return 1;
4984}
4985
4986sub show_commit {
4987 my $c = shift;
4988 if ($oneline) {
4989 my $x = "\n";
4990 if (my $l = $c->{l}) {
4991 while ($l->[0] =~ /^\s*$/) { shift @$l }
4992 $x = $l->[0];
4993 }
4994 $l_fmt ||= 'A' . length($c->{r});
4995 print 'r',pack($l_fmt, $c->{r}),' | ';
4996 print "$c->{c} | " if $show_commit;
4997 print $x;
4998 } else {
4999 show_commit_normal($c);
5000 }
5001}
5002
5003sub show_commit_changed_paths {
5004 my ($c) = @_;
5005 return unless $c->{changed};
5006 print "Changed paths:\n", @{$c->{changed}};
5007}
5008
5009sub show_commit_normal {
5010 my ($c) = @_;
111947ef 5011 print commit_log_separator, "r$c->{r} | ";
f8c9d1d2 5012 print "$c->{c} | " if $show_commit;
b2b3ada7 5013 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
f8c9d1d2
EW
5014 my $nr_line = 0;
5015
5016 if (my $l = $c->{l}) {
5017 while ($l->[$#$l] eq "\n" && $#$l > 0
5018 && $l->[($#$l - 1)] eq "\n") {
5019 pop @$l;
5020 }
5021 $nr_line = scalar @$l;
5022 if (!$nr_line) {
5023 print "1 line\n\n\n";
5024 } else {
5025 if ($nr_line == 1) {
5026 $nr_line = '1 line';
5027 } else {
5028 $nr_line .= ' lines';
5029 }
5030 print $nr_line, "\n";
5031 show_commit_changed_paths($c);
5032 print "\n";
5033 print $_ foreach @$l;
5034 }
5035 } else {
5036 print "1 line\n";
5037 show_commit_changed_paths($c);
5038 print "\n";
5039
5040 }
488a63ec 5041 foreach my $x (qw/raw stat diff/) {
f8c9d1d2
EW
5042 if ($c->{$x}) {
5043 print "\n";
5044 print $_ foreach @{$c->{$x}}
5045 }
5046 }
5047}
5048
5049sub cmd_show_log {
5050 my (@args) = @_;
5051 my ($r_min, $r_max);
5052 my $r_last = -1; # prevent dupes
b2b3ada7 5053 set_local_timezone();
f8c9d1d2
EW
5054 if (defined $::_revision) {
5055 if ($::_revision =~ /^(\d+):(\d+)$/) {
5056 ($r_min, $r_max) = ($1, $2);
5057 } elsif ($::_revision =~ /^\d+$/) {
5058 $r_min = $r_max = $::_revision;
5059 } else {
5060 ::fatal "-r$::_revision is not supported, use ",
207f1a75 5061 "standard 'git log' arguments instead";
f8c9d1d2
EW
5062 }
5063 }
5064
5065 config_pager();
6ed77266 5066 @args = git_svn_log_cmd($r_min, $r_max, @args);
111947ef
DK
5067 if (!@args) {
5068 print commit_log_separator unless $incremental || $oneline;
5069 return;
5070 }
f8c9d1d2
EW
5071 my $log = command_output_pipe(@args);
5072 run_pager();
488a63ec 5073 my (@k, $c, $d, $stat);
f8c9d1d2
EW
5074 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5075 while (<$log>) {
60f3ff12 5076 if (/^${esc_color}commit -?($::sha1_short)/o) {
f8c9d1d2
EW
5077 my $cmt = $1;
5078 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5079 $r_last = $c->{r};
5080 process_commit($c, $r_min, $r_max, \@k) or
5081 goto out;
5082 }
5083 $d = undef;
5084 $c = { c => $cmt };
5085 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5086 get_author_info($c, $1, $2, $3);
5087 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5088 # ignore
5089 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5090 push @{$c->{raw}}, $_;
5091 } elsif (/^${esc_color}[ACRMDT]\t/) {
5092 # we could add $SVN->{svn_path} here, but that requires
5093 # remote access at the moment (repo_path_split)...
5094 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5095 push @{$c->{changed}}, $_;
5096 } elsif (/^${esc_color}diff /o) {
5097 $d = 1;
5098 push @{$c->{diff}}, $_;
5099 } elsif ($d) {
5100 push @{$c->{diff}}, $_;
488a63ec
EW
5101 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5102 $esc_color*[\+\-]*$esc_color$/x) {
5103 $stat = 1;
5104 push @{$c->{stat}}, $_;
5105 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5106 push @{$c->{stat}}, $_;
5107 $stat = undef;
f8c9d1d2
EW
5108 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5109 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5110 } elsif (s/^${esc_color} //o) {
5111 push @{$c->{l}}, $_;
5112 }
5113 }
5114 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5115 $r_last = $c->{r};
5116 process_commit($c, $r_min, $r_max, \@k);
5117 }
5118 if (@k) {
111947ef 5119 ($r_min, $r_max) = ($r_max, $r_min);
f8c9d1d2
EW
5120 process_commit($_, $r_min, $r_max) foreach reverse @k;
5121 }
5122out:
c843c464 5123 close $log;
111947ef 5124 print commit_log_separator unless $incremental || $oneline;
f8c9d1d2
EW
5125}
5126
6fb5375e 5127sub cmd_blame {
4be40381 5128 my $path = pop;
6fb5375e
TS
5129
5130 config_pager();
5131 run_pager();
5132
4be40381
SG
5133 my ($fh, $ctx, $rev);
5134
5135 if ($_git_format) {
5136 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5137 while (my $line = <$fh>) {
5138 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5139 # Uncommitted edits show up as a rev ID of
5140 # all zeros, which we can't look up with
5141 # cmt_metadata
5142 if ($1 !~ /^0+$/) {
5143 (undef, $rev, undef) =
5144 ::cmt_metadata($1);
5145 $rev = '0' if (!$rev);
5146 } else {
5147 $rev = '0';
5148 }
5149 $rev = sprintf('%-10s', $rev);
5150 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5151 }
5152 print $line;
5153 }
5154 } else {
5155 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5156 '--', $path);
5157 my ($sha1);
5158 my %authors;
6ea42032
BB
5159 my @buffer;
5160 my %dsha; #distinct sha keys
5161
4be40381 5162 while (my $line = <$fh>) {
6ea42032
BB
5163 push @buffer, $line;
5164 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5165 $dsha{$1} = 1;
5166 }
5167 }
5168
5169 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5170
5171 foreach my $line (@buffer) {
4be40381 5172 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
6ea42032
BB
5173 $rev = $s2r->{$1};
5174 $rev = '0' if (!$rev)
4be40381
SG
5175 }
5176 elsif ($line =~ /^author (.*)/) {
5177 $authors{$rev} = $1;
5178 $authors{$rev} =~ s/\s/_/g;
5179 }
5180 elsif ($line =~ /^\t(.*)$/) {
5181 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5182 }
6fb5375e 5183 }
6fb5375e
TS
5184 }
5185 command_close_pipe($fh, $ctx);
5186}
5187
706587fc
EW
5188package Git::SVN::Migration;
5189# these version numbers do NOT correspond to actual version numbers
5190# of git nor git-svn. They are just relative.
5191#
5192# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5193#
5194# v1 layout: .git/$id/info/url, refs/remotes/$id
5195#
5196# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5197#
5198# v3 layout: .git/svn/$id, refs/remotes/$id
5199# - info/url may remain for backwards compatibility
5200# - this is what we migrate up to this layout automatically,
5201# - this will be used by git svn init on single branches
26a62d57
EW
5202# v3.1 layout (auto migrated):
5203# - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5204# for backwards compatibility
706587fc
EW
5205#
5206# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5207# - this is only created for newly multi-init-ed
5208# repositories. Similar in spirit to the
5209# --use-separate-remotes option in git-clone (now default)
5210# - we do not automatically migrate to this (following
5211# the example set by core git)
060610c5
EW
5212#
5213# v5 layout: .rev_db.$UUID => .rev_map.$UUID
5214# - newer, more-efficient format that uses 24-bytes per record
5215# with no filler space.
5216# - use xxd -c24 < .rev_map.$UUID to view and debug
5217# - This is a one-way migration, repositories updated to the
5218# new format will not be able to use old git-svn without
5219# rebuilding the .rev_db. Rebuilding the rev_db is not
5220# possible if noMetadata or useSvmProps are set; but should
5221# be no problem for users that use the (sensible) defaults.
706587fc
EW
5222use strict;
5223use warnings;
5224use Carp qw/croak/;
5225use File::Path qw/mkpath/;
47e39c55
EW
5226use File::Basename qw/dirname basename/;
5227use vars qw/$_minimize/;
706587fc
EW
5228
5229sub migrate_from_v0 {
5230 my $git_dir = $ENV{GIT_DIR};
5231 return undef unless -d $git_dir;
5232 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5233 my $migrated = 0;
5234 while (<$fh>) {
5235 chomp;
5236 my ($id, $orig_ref) = ($_, $_);
5237 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5238 next unless -f "$git_dir/$id/info/url";
5239 my $new_ref = "refs/remotes/$id";
5240 if (::verify_ref("$new_ref^0")) {
5241 print STDERR "W: $orig_ref is probably an old ",
5242 "branch used by an ancient version of ",
5243 "git-svn.\n",
5244 "However, $new_ref also exists.\n",
5245 "We will not be able ",
5246 "to use this branch until this ",
5247 "ambiguity is resolved.\n";
5248 next;
5249 }
5250 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5251 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5252 command_noisy('update-ref', $new_ref, $orig_ref);
5253 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5254 $migrated++;
5255 }
5256 command_close_pipe($fh, $ctx);
5257 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5258 $migrated;
5259}
5260
5261sub migrate_from_v1 {
5262 my $git_dir = $ENV{GIT_DIR};
5263 my $migrated = 0;
5264 return $migrated unless -d $git_dir;
5265 my $svn_dir = "$git_dir/svn";
5266
5267 # just in case somebody used 'svn' as their $id at some point...
5268 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5269
5270 print STDERR "Migrating from a git-svn v1 layout...\n";
5271 mkpath([$svn_dir]);
5272 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5273 "$svn_dir\n\t(required for this version ",
8f510bef 5274 "($::VERSION) of git-svn) does not exist.\n";
706587fc
EW
5275 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5276 while (<$fh>) {
5277 my $x = $_;
5278 next unless $x =~ s#^refs/remotes/##;
5279 chomp $x;
5280 next unless -f "$git_dir/$x/info/url";
5281 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5282 next unless $u;
5283 my $dn = dirname("$git_dir/svn/$x");
5284 mkpath([$dn]) unless -d $dn;
5285 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5286 mkpath(["$git_dir/svn/svn"]);
5287 print STDERR " - $git_dir/$x/info => ",
5288 "$git_dir/svn/$x/info\n";
5289 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5290 croak "$!: $x";
5291 # don't worry too much about these, they probably
5292 # don't exist with repos this old (save for index,
5293 # and we can easily regenerate that)
5294 foreach my $f (qw/unhandled.log index .rev_db/) {
5295 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5296 }
5297 } else {
5298 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5299 rename "$git_dir/$x", "$git_dir/svn/$x" or
5300 croak "$!: $x";
5301 }
5302 $migrated++;
5303 }
5304 command_close_pipe($fh, $ctx);
5305 print STDERR "Done migrating from a git-svn v1 layout\n";
5306 $migrated;
5307}
5308
5309sub read_old_urls {
5310 my ($l_map, $pfx, $path) = @_;
5311 my @dir;
5312 foreach (<$path/*>) {
5313 if (-r "$_/info/url") {
5314 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5315 my $ref_id = $pfx . basename $_;
5316 my $url = ::file_to_s("$_/info/url");
5317 $l_map->{$ref_id} = $url;
5318 } elsif (-d $_) {
5319 push @dir, $_;
5320 }
5321 }
5322 foreach (@dir) {
5323 my $x = $_;
5324 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5325 read_old_urls($l_map, $x, $_);
5326 }
5327}
5328
5329sub migrate_from_v2 {
5330 my @cfg = command(qw/config -l/);
5331 return if grep /^svn-remote\..+\.url=/, @cfg;
5332 my %l_map;
5333 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5334 my $migrated = 0;
5335
5336 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
5337 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5338 if ($@) {
5339 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5340 }
706587fc
EW
5341 $migrated++;
5342 }
5343 $migrated;
5344}
5345
47e39c55
EW
5346sub minimize_connections {
5347 my $r = Git::SVN::read_all_remotes();
5348 my $new_urls = {};
5349 my $root_repos = {};
5350 foreach my $repo_id (keys %$r) {
5351 my $url = $r->{$repo_id}->{url} or next;
5352 my $fetch = $r->{$repo_id}->{fetch} or next;
5353 my $ra = Git::SVN::Ra->new($url);
5354
5355 # skip existing cases where we already connect to the root
5356 if (($ra->{url} eq $ra->{repos_root}) ||
7829f20f 5357 ($ra->{repos_root} eq $repo_id)) {
47e39c55
EW
5358 $root_repos->{$ra->{url}} = $repo_id;
5359 next;
5360 }
5361
5362 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5363 my $root_path = $ra->{url};
4e9f6cc7 5364 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
5365 foreach my $path (keys %$fetch) {
5366 my $ref_id = $fetch->{$path};
5367 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5368
5369 # make sure we can read when connecting to
5370 # a higher level of a repository
5371 my ($last_rev, undef) = $gs->last_rev_commit;
5372 if (!defined $last_rev) {
5373 $last_rev = eval {
5374 $root_ra->get_latest_revnum;
5375 };
5376 next if $@;
5377 }
5378 my $new = $root_path;
5379 $new .= length $path ? "/$path" : '';
5380 eval {
5381 $root_ra->get_log([$new], $last_rev, $last_rev,
5382 0, 0, 1, sub { });
5383 };
5384 next if $@;
5385 $new_urls->{$ra->{repos_root}}->{$new} =
5386 { ref_id => $ref_id,
5387 old_repo_id => $repo_id,
5388 old_path => $path };
5389 }
5390 }
5391
5392 my @emptied;
5393 foreach my $url (keys %$new_urls) {
5394 # see if we can re-use an existing [svn-remote "repo_id"]
5395 # instead of creating a(n ugly) new section:
7829f20f 5396 my $repo_id = $root_repos->{$url} || $url;
47e39c55
EW
5397
5398 my $fetch = $new_urls->{$url};
5399 foreach my $path (keys %$fetch) {
5400 my $x = $fetch->{$path};
5401 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5402 my $pfx = "svn-remote.$x->{old_repo_id}";
5403
5404 my $old_fetch = quotemeta("$x->{old_path}:".
5405 "refs/remotes/$x->{ref_id}");
8b8fc068 5406 command_noisy(qw/config --unset/,
47e39c55
EW
5407 "$pfx.fetch", '^'. $old_fetch . '$');
5408 delete $r->{$x->{old_repo_id}}->
5409 {fetch}->{$x->{old_path}};
5410 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 5411 command_noisy(qw/config --unset/,
47e39c55
EW
5412 "$pfx.url");
5413 push @emptied, $x->{old_repo_id}
5414 }
5415 }
5416 }
5417 if (@emptied) {
8befc50c 5418 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
47e39c55
EW
5419 print STDERR <<EOF;
5420The following [svn-remote] sections in your config file ($file) are empty
5421and can be safely removed:
5422EOF
5423 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5424 }
5425}
5426
706587fc
EW
5427sub migration_check {
5428 migrate_from_v0();
5429 migrate_from_v1();
5430 migrate_from_v2();
47e39c55 5431 minimize_connections() if $_minimize;
706587fc
EW
5432}
5433
ef3cfaad
EW
5434package Git::IndexInfo;
5435use strict;
5436use warnings;
5437use Git qw/command_input_pipe command_close_pipe/;
5438
5439sub new {
5440 my ($class) = @_;
5441 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5442 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5443}
5444
5445sub remove {
5446 my ($self, $path) = @_;
5447 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5448 return ++$self->{nr};
5449 }
5450 undef;
5451}
5452
5453sub update {
5454 my ($self, $mode, $hash, $path) = @_;
5455 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5456 return ++$self->{nr};
5457 }
5458 undef;
5459}
5460
5461sub DESTROY {
5462 my ($self) = @_;
5463 command_close_pipe($self->{gui}, $self->{ctx});
5464}
5465
4bb9ed04
EW
5466package Git::SVN::GlobSpec;
5467use strict;
5468use warnings;
5469
5470sub new {
5471 my ($class, $glob) = @_;
4bb9ed04
EW
5472 my $re = $glob;
5473 $re =~ s!/+$!!g; # no need for trailing slashes
570d35c2
MG
5474 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5475 my $temp = $re;
5476 my ($left, $right) = ($1, $3);
5477 $re = $2;
5478 my $depth = $re =~ tr/*/*/;
5479 if ($depth != $temp =~ tr/*/*/) {
5480 die "Only one set of wildcard directories " .
5481 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5482 }
5483 if ($depth == 0) {
e518192f 5484 die "One '*' is needed for glob: '$glob'\n";
4bb9ed04 5485 }
570d35c2
MG
5486 $re =~ s!\*!\[^/\]*!g;
5487 $re = quotemeta($left) . "($re)" . quotemeta($right);
4e9f6cc7
EW
5488 if (length $left && !($left =~ s!/+$!!g)) {
5489 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5490 }
5491 if (length $right && !($right =~ s!^/+!!g)) {
5492 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5493 }
74a81227
EW
5494 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5495 bless { left => $left, right => $right, left_regex => $left_re,
570d35c2 5496 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4bb9ed04
EW
5497}
5498
5499sub full_path {
5500 my ($self, $path) = @_;
5501 return (length $self->{left} ? "$self->{left}/" : '') .
5502 $path . (length $self->{right} ? "/$self->{right}" : '');
5503}
5504
3397f9df
EW
5505__END__
5506
5507Data structures:
5508
4bb9ed04
EW
5509
5510$remotes = { # returned by read_all_remotes()
5511 'svn' => {
5512 # svn-remote.svn.url=https://svn.musicpd.org
5513 url => 'https://svn.musicpd.org',
5514 # svn-remote.svn.fetch=mpd/trunk:trunk
5515 fetch => {
5516 'mpd/trunk' => 'trunk',
5517 },
5518 # svn-remote.svn.tags=mpd/tags/*:tags/*
5519 tags => {
5520 path => {
5521 left => 'mpd/tags',
5522 right => '',
5523 regex => qr!mpd/tags/([^/]+)$!,
5524 glob => 'tags/*',
5525 },
5526 ref => {
5527 left => 'tags',
5528 right => '',
5529 regex => qr!tags/([^/]+)$!,
5530 glob => 'tags/*',
5531 },
5532 }
5533 }
5534};
5535
44320b9e 5536$log_entry hashref as returned by libsvn_log_entry()
3397f9df 5537{
44320b9e 5538 log => 'whitespace-formatted log entry
3397f9df
EW
5539', # trailing newline is preserved
5540 revision => '8', # integer
5541 date => '2004-02-24T17:01:44.108345Z', # commit date
5542 author => 'committer name'
5543};
5544
6e8548cc
EW
5545
5546# this is generated by generate_diff();
3397f9df
EW
5547@mods = array of diff-index line hashes, each element represents one line
5548 of diff-index output
5549
5550diff-index line ($m hash)
5551{
5552 mode_a => first column of diff-index output, no leading ':',
5553 mode_b => second column of diff-index output,
5554 sha1_b => sha1sum of the final blob,
ac8e0b91 5555 chg => change type [MCRADT],
3397f9df
EW
5556 file_a => original file name of a file (iff chg is 'C' or 'R')
5557 file_b => new/current file name of a file (any chg)
5558}
5559;
a5e0cedc 5560
a00439ac
EW
5561# retval of read_url_paths{,_all}();
5562$l_map = {
5563 # repository root url
5564 'https://svn.musicpd.org' => {
5565 # repository path # GIT_SVN_ID
5566 'mpd/trunk' => 'trunk',
5567 'mpd/tags/0.11.5' => 'tags/0.11.5',
5568 },
5569}
5570
a5e0cedc
EW
5571Notes:
5572 I don't trust the each() function on unless I created %hash myself
5573 because the internal iterator may not have started at base.