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