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