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