git-svn: correctly handle globs with a right-hand-side path component
[git/git.git] / git-svn.perl
CommitLineData
3397f9df 1#!/usr/bin/env perl
551ce28f
EW
2# Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3# License: GPL v2 or later
3397f9df
EW
4use warnings;
5use strict;
6use vars qw/ $AUTHOR $VERSION
9760adcc
EW
7 $sha1 $sha1_short $_revision
8 $_q $_authors %users/;
3397f9df 9$AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
60d02ccc 10$VERSION = '@@GIT_VERSION@@';
13ccd6d4 11
706587fc 12$ENV{GIT_DIR} ||= '.git';
9fa00b65 13$Git::SVN::default_repo_id = 'svn';
8b8fc068 14$Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
13ccd6d4 15
f8c9d1d2 16$Git::SVN::Log::TZ = $ENV{TZ};
3397f9df 17$ENV{TZ} = 'UTC';
a00439ac 18$| = 1; # unbuffer STDOUT
3397f9df 19
6fda05ae 20sub fatal (@) { print STDERR @_; exit 1 }
b9c85187
EW
21require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
22require SVN::Ra;
23require SVN::Delta;
24if ($SVN::Core::VERSION lt '1.1.0') {
25 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)\n";
26}
d81bf827 27push @Git::SVN::Ra::ISA, 'SVN::Ra';
b9c85187
EW
28push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
29push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
3397f9df
EW
30use Carp qw/croak/;
31use IO::File qw//;
32use File::Basename qw/dirname basename/;
33use File::Path qw/mkpath/;
79bb8d88 34use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev pass_through/;
968bdf1f 35use IPC::Open3;
336f1714 36use Git;
a5e0cedc 37
336f1714
EW
38BEGIN {
39 my $s;
40 foreach (qw/command command_oneline command_noisy command_output_pipe
41 command_input_pipe command_close_pipe/) {
42 $s .= "*SVN::Git::Editor::$_ = *SVN::Git::Fetcher::$_ = ".
706587fc 43 "*Git::SVN::Migration::$_ = ".
f8c9d1d2 44 "*Git::SVN::Log::$_ = *Git::SVN::$_ = *$_ = *Git::$_; ";
336f1714
EW
45 }
46 eval $s;
47}
48
b9c85187 49my ($SVN);
83e9940a 50
42d32870 51my $_optimize_commits = 1 unless $ENV{GIT_SVN_NO_OPTIMIZE_COMMITS};
f8c9d1d2
EW
52$sha1 = qr/[a-f\d]{40}/;
53$sha1_short = qr/[a-f\d]{4,40}/;
44320b9e 54my ($_stdin, $_help, $_edit,
9760adcc 55 $_message, $_file,
d05d72e0 56 $_template, $_shared,
9760adcc 57 $_version,
f8c9d1d2
EW
58 $_merge, $_strategy, $_dry_run,
59 $_prefix);
0bed5eaa 60$Git::SVN::_follow_parent = 1;
706587fc
EW
61my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
62 'config-dir=s' => \$Git::SVN::Ra::config_dir,
63 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
0bed5eaa 64my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
dc5869c0 65 'authors-file|A=s' => \$_authors,
ecc712dd 66 'repack:i' => \$Git::SVN::_repack,
9760adcc 67 'no-metadata' => \$Git::SVN::_no_metadata,
80f50749 68 'quiet|q' => \$_q,
ecc712dd
EW
69 'repack-flags|repack-args|repack-opts=s' =>
70 \$Git::SVN::_repack_flags,
706587fc 71 %remote_opts );
36f5b1f0 72
9d55b41a
EW
73my ($_trunk, $_tags, $_branches);
74my %multi_opts = ( 'trunk|T=s' => \$_trunk,
75 'tags|t=s' => \$_tags,
76 'branches|b=s' => \$_branches );
77my %init_opts = ( 'template=s' => \$_template, 'shared' => \$_shared );
27e9fb8d 78my %cmt_opts = ( 'edit|e' => \$_edit,
24e22aa8
EW
79 'rmdir' => \$SVN::Git::Editor::_rmdir,
80 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
81 'l=i' => \$SVN::Git::Editor::_rename_limit,
82 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
27e9fb8d 83);
9d55b41a 84
3397f9df 85my %cmd = (
2a3240be 86 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
eeb0abe0 87 { 'revision|r=s' => \$_revision, %fc_opts } ],
d2866f9e 88 init => [ \&cmd_init, "Initialize a repo for tracking" .
f8ab6b73 89 " (requires URL argument)",
9d55b41a 90 \%init_opts ],
d7ad3bed
EW
91 dcommit => [ \&cmd_dcommit,
92 'Commit several diffs to merge with upstream',
3289e86e
EW
93 { 'merge|m|M' => \$_merge,
94 'strategy|s=s' => \$_strategy,
95 'dry-run|n' => \$_dry_run,
4b155223 96 %cmt_opts, %fc_opts } ],
1ce255dc
EW
97 'set-tree' => [ \&cmd_set_tree,
98 "Set an SVN repository to a git tree-ish",
99 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
5969cbe1 100 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
a5e0cedc 101 { 'revision|r=i' => \$_revision } ],
8164b652 102 'multi-init' => [ \&cmd_multi_init,
9d55b41a 103 'Initialize multiple trees (like git-svnimport)',
706587fc 104 { %multi_opts, %init_opts, %remote_opts,
1ca7558d 105 'revision|r=i' => \$_revision,
ae410987 106 'prefix=s' => \$_prefix,
1ca7558d 107 } ],
1c8443b0 108 'multi-fetch' => [ \&cmd_multi_fetch,
9d55b41a
EW
109 'Fetch multiple trees (like git-svnimport)',
110 \%fc_opts ],
706587fc
EW
111 'migrate' => [ sub { },
112 # no-op, we automatically run this anyways,
706587fc
EW
113 'Migrate configuration/metadata/layout from
114 previous versions of git-svn',
115 \%remote_opts ],
f8c9d1d2
EW
116 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
117 { 'limit=i' => \$Git::SVN::Log::limit,
79bb8d88 118 'revision|r=s' => \$_revision,
f8c9d1d2
EW
119 'verbose|v' => \$Git::SVN::Log::verbose,
120 'incremental' => \$Git::SVN::Log::incremental,
121 'oneline' => \$Git::SVN::Log::oneline,
122 'show-commit' => \$Git::SVN::Log::show_commit,
123 'non-recursive' => \$Git::SVN::Log::non_recursive,
79bb8d88 124 'authors-file|A=s' => \$_authors,
f8c9d1d2
EW
125 'color' => \$Git::SVN::Log::color,
126 'pager=s' => \$Git::SVN::Log::pager,
79bb8d88 127 } ],
44320b9e
EW
128 'commit-diff' => [ \&cmd_commit_diff,
129 'Commit a diff between two trees',
27e9fb8d
EW
130 { 'message|m=s' => \$_message,
131 'file|F=s' => \$_file,
45bf473a 132 'revision|r=s' => \$_revision,
27e9fb8d 133 %cmt_opts } ],
3397f9df 134);
9d55b41a 135
3397f9df
EW
136my $cmd;
137for (my $i = 0; $i < @ARGV; $i++) {
138 if (defined $cmd{$ARGV[$i]}) {
139 $cmd = $ARGV[$i];
140 splice @ARGV, $i, 1;
141 last;
142 }
143};
144
448c81b4 145my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
a9612be2 146
b8c92cad 147read_repo_config(\%opts);
9760adcc
EW
148my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
149 'minimize-connections' => \$Git::SVN::Migration::_minimize,
150 'id|i=s' => \$Git::SVN::default_ref_id,
151 'svn-remote|remote|R=s' => \$Git::SVN::default_repo_id);
79bb8d88 152exit 1 if (!$rv && $cmd ne 'log');
6f0783cf 153
3397f9df 154usage(0) if $_help;
551ce28f 155version() if $_version;
eeb0abe0
EW
156usage(1) unless defined $cmd;
157load_authors() if $_authors;
f0ecca10 158unless ($cmd =~ /^(?:init|multi-init|commit-diff)$/) {
706587fc
EW
159 Git::SVN::Migration::migration_check();
160}
ecc712dd 161Git::SVN::init_vars();
b805b44a
EW
162eval {
163 Git::SVN::verify_remotes_sanity();
164 $cmd{$cmd}->[0]->(@ARGV);
165};
166fatal $@ if $@;
3397f9df
EW
167exit 0;
168
169####################### primary functions ######################
170sub usage {
171 my $exit = shift || 0;
172 my $fd = $exit ? \*STDERR : \*STDOUT;
173 print $fd <<"";
174git-svn - bidirectional operations between a single Subversion tree and git
175Usage: $0 <command> [options] [arguments]\n
448c81b4
EW
176
177 print $fd "Available commands:\n" unless $cmd;
3397f9df
EW
178
179 foreach (sort keys %cmd) {
448c81b4 180 next if $cmd && $cmd ne $_;
b203b769 181 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
448c81b4
EW
182 foreach (keys %{$cmd{$_}->[2]}) {
183 # prints out arguments as they should be passed:
b8c92cad 184 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
b203b769 185 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
448c81b4
EW
186 "--$_" : "-$_" }
187 split /\|/,$_)," $x\n";
188 }
3397f9df
EW
189 }
190 print $fd <<"";
448c81b4
EW
191\nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
192arbitrary identifier if you're tracking multiple SVN branches/repositories in
193one git repository and want to keep them separate. See git-svn(1) for more
194information.
3397f9df
EW
195
196 exit $exit;
197}
198
551ce28f 199sub version {
7d60ab2c 200 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
551ce28f
EW
201 exit 0;
202}
203
8164b652
EW
204sub do_git_init_db {
205 unless (-d $ENV{GIT_DIR}) {
206 my @init_db = ('init');
207 push @init_db, "--template=$_template" if defined $_template;
208 push @init_db, "--shared" if defined $_shared;
209 command_noisy(@init_db);
210 }
211}
212
d2866f9e 213sub cmd_init {
03e0ea87 214 my $url = shift or die "SVN repository location required " .
81c5a0e6 215 "as a command-line argument\n";
03e0ea87
EW
216 if (my $repo_path = shift) {
217 unless (-d $repo_path) {
218 mkpath([$repo_path]);
219 }
d2866f9e
EW
220 chdir $repo_path or croak $!;
221 $ENV{GIT_DIR} = $repo_path . "/.git";
03e0ea87 222 }
8164b652 223 do_git_init_db();
03e0ea87 224
706587fc 225 Git::SVN->init($url);
3397f9df
EW
226}
227
2a3240be 228sub cmd_fetch {
07a1c950
EW
229 if (@_) {
230 die "Additional fetch arguments are no longer supported.\n",
231 "Use --follow-parent if you have moved/copied directories
232 instead.\n";
233 }
1c8443b0 234 my $gs = Git::SVN->new;
3ebe8df7 235 $gs->fetch(parse_revision_argument());
1c8443b0
EW
236 if ($gs->{last_commit} && !verify_ref('refs/heads/master^0')) {
237 command_noisy(qw(update-ref refs/heads/master),
238 $gs->{last_commit});
239 }
2a3240be
EW
240}
241
1ce255dc 242sub cmd_set_tree {
3397f9df
EW
243 my (@commits) = @_;
244 if ($_stdin || !@commits) {
245 print "Reading from stdin...\n";
246 @commits = ();
247 while (<STDIN>) {
1ca72aef 248 if (/\b($sha1_short)\b/o) {
3397f9df
EW
249 unshift @commits, $1;
250 }
251 }
252 }
253 my @revs;
8de010ad 254 foreach my $c (@commits) {
aef4e921 255 my @tmp = command('rev-parse',$c);
8de010ad
EW
256 if (scalar @tmp == 1) {
257 push @revs, $tmp[0];
258 } elsif (scalar @tmp > 1) {
aef4e921 259 push @revs, reverse(command('rev-list',@tmp));
8de010ad 260 } else {
1ce255dc 261 fatal "Failed to rev-parse $c\n";
8de010ad 262 }
3397f9df 263 }
1ce255dc
EW
264 my $gs = Git::SVN->new;
265 my ($r_last, $cmt_last) = $gs->last_rev_commit;
266 $gs->fetch;
97f6987a 267 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
1ce255dc
EW
268 fatal "There are new revisions that were fetched ",
269 "and need to be merged (or acknowledged) ",
270 "before committing.\nlast rev: $r_last\n",
271 " current: $gs->{last_rev}\n";
a5e0cedc 272 }
1ce255dc
EW
273 $gs->set_tree($_) foreach @revs;
274 print "Done committing ",scalar @revs," revisions to SVN\n";
a5e0cedc 275}
8f22562c 276
d7ad3bed
EW
277sub cmd_dcommit {
278 my $head = shift;
279 my $gs = Git::SVN->new;
280 $head ||= 'HEAD';
281 my @refs = command(qw/rev-list --no-merges/, $gs->refname."..$head");
45bf473a 282 my $last_rev;
b22d4497 283 foreach my $d (reverse @refs) {
aef4e921 284 if (!verify_ref("$d~1")) {
d7ad3bed
EW
285 fatal "Commit $d\n",
286 "has no parent commit, and therefore ",
287 "nothing to diff against.\n",
288 "You should be working from a repository ",
289 "originally created by git-svn\n";
48d044b5 290 }
45bf473a
EW
291 unless (defined $last_rev) {
292 (undef, $last_rev, undef) = cmt_metadata("$d~1");
293 unless (defined $last_rev) {
d7ad3bed
EW
294 fatal "Unable to extract revision information ",
295 "from commit $d~1\n";
45bf473a
EW
296 }
297 }
b22d4497
EW
298 if ($_dry_run) {
299 print "diff-tree $d~1 $d\n";
300 } else {
d7ad3bed 301 my %ed_opts = ( r => $last_rev,
61395354
EW
302 log => get_commit_entry($d)->{log},
303 ra => $gs->ra,
304 tree_a => "$d~1",
305 tree_b => $d,
306 editor_cb => sub {
307 print "Committed r$_[0]\n";
308 $last_rev = $_[0]; },
d3a840dc 309 svn_path => $gs->{path} );
61395354 310 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
d7ad3bed
EW
311 print "No changes\n$d~1 == $d\n";
312 }
b22d4497
EW
313 }
314 }
315 return if $_dry_run;
d7ad3bed
EW
316 $gs->fetch;
317 # we always want to rebase against the current HEAD, not any
318 # head that was passed to us
319 my @diff = command('diff-tree', 'HEAD', $gs->refname, '--');
b22d4497
EW
320 my @finish;
321 if (@diff) {
322 @finish = qw/rebase/;
323 push @finish, qw/--merge/ if $_merge;
324 push @finish, "--strategy=$_strategy" if $_strategy;
d7ad3bed
EW
325 print STDERR "W: HEAD and ", $gs->refname, " differ, ",
326 "using @finish:\n", "@diff";
b22d4497 327 } else {
d7ad3bed
EW
328 print "No changes between current HEAD and ",
329 $gs->refname, "\nResetting to the latest ",
330 $gs->refname, "\n";
4769489a 331 @finish = qw/reset --mixed/;
b22d4497 332 }
d7ad3bed 333 command_noisy(@finish, $gs->refname);
b22d4497
EW
334}
335
5969cbe1
EW
336sub cmd_show_ignore {
337 my $gs = Git::SVN->new;
338 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
339 $gs->traverse_ignore(\*STDOUT, '', $r);
a5e0cedc
EW
340}
341
8164b652 342sub cmd_multi_init {
9d55b41a 343 my $url = shift;
98327e58
EW
344 unless (defined $_trunk || defined $_branches || defined $_tags) {
345 usage(1);
9d55b41a 346 }
8164b652
EW
347 do_git_init_db();
348 $_prefix = '' unless defined $_prefix;
706587fc 349 $url =~ s#/+$## if defined $url;
98327e58 350 if (defined $_trunk) {
706587fc
EW
351 my $trunk_ref = $_prefix . 'trunk';
352 # try both old-style and new-style lookups:
353 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
8164b652 354 unless ($gs_trunk) {
706587fc
EW
355 my ($trunk_url, $trunk_path) =
356 complete_svn_url($url, $_trunk);
357 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
358 undef, $trunk_ref);
98327e58 359 }
c35b96e7 360 }
706587fc 361 return unless defined $_branches || defined $_tags;
e7db67e6
EW
362 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
363 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
364 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
9d55b41a
EW
365}
366
1c8443b0 367sub cmd_multi_fetch {
0af9c9f9
EW
368 my $remotes = Git::SVN::read_all_remotes();
369 foreach my $repo_id (sort keys %$remotes) {
4bb9ed04
EW
370 if ($remotes->{$repo_id}->{url} &&
371 $remotes->{$repo_id}->{fetch}) {
372 Git::SVN::fetch_all($repo_id, $remotes);
373 }
9d55b41a 374 }
9d55b41a
EW
375}
376
44320b9e
EW
377# this command is special because it requires no metadata
378sub cmd_commit_diff {
379 my ($ta, $tb, $url) = @_;
380 my $usage = "Usage: $0 commit-diff -r<revision> ".
381 "<tree-ish> <tree-ish> [<URL>]\n";
382 fatal($usage) if (!defined $ta || !defined $tb);
d3a840dc 383 my $svn_path;
44320b9e
EW
384 if (!defined $url) {
385 my $gs = eval { Git::SVN->new };
386 if (!$gs) {
387 fatal("Needed URL or usable git-svn --id in ",
388 "the command-line\n", $usage);
389 }
390 $url = $gs->{url};
d3a840dc 391 $svn_path = $gs->{path};
44320b9e
EW
392 }
393 unless (defined $_revision) {
394 fatal("-r|--revision is a required argument\n", $usage);
395 }
396 if (defined $_message && defined $_file) {
397 fatal("Both --message/-m and --file/-F specified ",
398 "for the commit message.\n",
399 "I have no idea what you mean\n");
400 }
401 if (defined $_file) {
402 $_message = file_to_s($_file);
403 } else {
404 $_message ||= get_commit_entry($tb)->{log};
405 }
406 my $ra ||= Git::SVN::Ra->new($url);
d3a840dc 407 $svn_path ||= $ra->{svn_path};
44320b9e
EW
408 my $r = $_revision;
409 if ($r eq 'HEAD') {
410 $r = $ra->get_latest_revnum;
411 } elsif ($r !~ /^\d+$/) {
412 die "revision argument: $r not understood by git-svn\n";
413 }
61395354
EW
414 my %ed_opts = ( r => $r,
415 log => $_message,
416 ra => $ra,
417 tree_a => $ta,
418 tree_b => $tb,
419 editor_cb => sub { print "Committed r$_[0]\n" },
420 svn_path => $svn_path );
421 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
44320b9e
EW
422 print "No changes\n$ta == $tb\n";
423 }
44320b9e
EW
424}
425
3397f9df
EW
426########################### utility functions #########################
427
3ebe8df7
EW
428sub parse_revision_argument {
429 if (!defined $_revision || $_revision eq 'BASE:HEAD') {
430 return (undef, undef);
431 }
432 return ($1, $2) if ($_revision =~ /^(\d+):(\d+)$/);
433 return ($_revision, $_revision) if ($_revision =~ /^\d+$/);
434 return (undef, $1) if ($_revision =~ /^BASE:(\d+)$/);
435 return ($1, undef) if ($_revision =~ /^(\d+):HEAD$/);
436 die "revision argument: $_revision not understood by git-svn\n",
437 "Try using the command-line svn client instead\n";
438}
439
98327e58
EW
440sub complete_svn_url {
441 my ($url, $path) = @_;
442 $path =~ s#/+$##;
98327e58 443 if ($path !~ m#^[a-z\+]+://#) {
98327e58
EW
444 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
445 fatal("E: '$path' is not a complete URL ",
446 "and a separate URL is not specified\n");
447 }
706587fc 448 return ($url, $path);
98327e58 449 }
706587fc 450 return ($path, '');
98327e58
EW
451}
452
9d55b41a 453sub complete_url_ls_init {
706587fc
EW
454 my ($ra, $repo_path, $switch, $pfx) = @_;
455 unless ($repo_path) {
9d55b41a
EW
456 print STDERR "W: $switch not specified\n";
457 return;
458 }
706587fc
EW
459 $repo_path =~ s#/+$##;
460 if ($repo_path =~ m#^[a-z\+]+://#) {
461 $ra = Git::SVN::Ra->new($repo_path);
462 $repo_path = '';
e7db67e6 463 } else {
706587fc 464 $repo_path =~ s#^/+##;
e7db67e6 465 unless ($ra) {
706587fc 466 fatal("E: '$repo_path' is not a complete URL ",
e7db67e6 467 "and a separate URL is not specified\n");
8164b652 468 }
e7db67e6
EW
469 }
470 my $r = defined $_revision ? $_revision : $ra->get_latest_revnum;
706587fc
EW
471 my ($dirent, undef, undef) = $ra->get_dir($repo_path, $r);
472 my $url = $ra->{url};
88cf4107
EW
473 my $remote_id;
474 my $remote_path;
e7db67e6
EW
475 foreach my $d (sort keys %$dirent) {
476 next if ($dirent->{$d}->kind != $SVN::Node::dir);
706587fc
EW
477 my $path = "$repo_path/$d";
478 my $ref = "$pfx$d";
479 my $gs = eval { Git::SVN->new($ref) };
e7db67e6 480 # don't try to init already existing refs
8164b652 481 unless ($gs) {
706587fc 482 print "init $url/$path => $ref\n";
4bb9ed04
EW
483 $gs = Git::SVN->init($url, $path, undef, $ref, 1);
484 }
485 if ($gs) {
486 $remote_id = $gs->{repo_id};
487 last;
9d55b41a 488 }
88cf4107
EW
489 }
490 if (defined $remote_id) {
491 $remote_path = "$ra->{svn_path}/$repo_path/*";
492 $remote_path =~ s#/+#/#g;
493 $remote_path =~ s#^/##g;
494 my ($n) = ($switch =~ /^--(\w+)/);
4e9f6cc7
EW
495 if (length $pfx && $pfx !~ m#/$#) {
496 die "--prefix='$pfx' must have a trailing slash '/'\n";
497 }
88cf4107 498 command_noisy('config', "svn-remote.$remote_id.$n",
4bb9ed04 499 "$remote_path:refs/remotes/$pfx*");
9d55b41a 500 }
9d55b41a
EW
501}
502
aef4e921
EW
503sub verify_ref {
504 my ($ref) = @_;
2c5c1d53
EW
505 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
506 { STDERR => 0 }); };
aef4e921
EW
507}
508
a5e0cedc 509sub get_tree_from_treeish {
cf52b8f0 510 my ($treeish) = @_;
44320b9e 511 # $treeish can be a symbolic ref, too:
aef4e921 512 my $type = command_oneline(qw/cat-file -t/, $treeish);
cf52b8f0
EW
513 my $expected;
514 while ($type eq 'tag') {
aef4e921 515 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
cf52b8f0
EW
516 }
517 if ($type eq 'commit') {
aef4e921
EW
518 $expected = (grep /^tree /, command(qw/cat-file commit/,
519 $treeish))[0];
44320b9e 520 ($expected) = ($expected =~ /^tree ($sha1)$/o);
cf52b8f0
EW
521 die "Unable to get tree from $treeish\n" unless $expected;
522 } elsif ($type eq 'tree') {
523 $expected = $treeish;
524 } else {
525 die "$treeish is a $type, expected tree, tag or commit\n";
526 }
a5e0cedc
EW
527 return $expected;
528}
529
44320b9e
EW
530sub get_commit_entry {
531 my ($treeish) = shift;
532 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
533 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
534 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
535 open my $log_fh, '>', $commit_editmsg or croak $!;
3397f9df 536
44320b9e 537 my $type = command_oneline(qw/cat-file -t/, $treeish);
4ad4515d 538 if ($type eq 'commit' || $type eq 'tag') {
aef4e921 539 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
44320b9e 540 $type, $treeish);
3397f9df
EW
541 my $in_msg = 0;
542 while (<$msg_fh>) {
543 if (!$in_msg) {
544 $in_msg = 1 if (/^\s*$/);
df746c5a 545 } elsif (/^git-svn-id: /) {
44320b9e
EW
546 # skip this for now, we regenerate the
547 # correct one on re-fetch anyways
548 # TODO: set *:merge properties or like...
3397f9df 549 } else {
44320b9e 550 print $log_fh $_ or croak $!;
3397f9df
EW
551 }
552 }
aef4e921 553 command_close_pipe($msg_fh, $ctx);
3397f9df 554 }
44320b9e 555 close $log_fh or croak $!;
3397f9df
EW
556
557 if ($_edit || ($type eq 'tree')) {
558 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
44320b9e
EW
559 # TODO: strip out spaces, comments, like git-commit.sh
560 system($editor, $commit_editmsg);
3397f9df 561 }
44320b9e
EW
562 rename $commit_editmsg, $commit_msg or croak $!;
563 open $log_fh, '<', $commit_msg or croak $!;
564 { local $/; chomp($log_entry{log} = <$log_fh>); }
565 close $log_fh or croak $!;
566 unlink $commit_msg;
567 \%log_entry;
a5e0cedc
EW
568}
569
3397f9df
EW
570sub s_to_file {
571 my ($str, $file, $mode) = @_;
572 open my $fd,'>',$file or croak $!;
573 print $fd $str,"\n" or croak $!;
574 close $fd or croak $!;
575 chmod ($mode &~ umask, $file) if (defined $mode);
576}
577
578sub file_to_s {
579 my $file = shift;
580 open my $fd,'<',$file or croak "$!: file: $file\n";
581 local $/;
582 my $ret = <$fd>;
583 close $fd or croak $!;
584 $ret =~ s/\s*$//s;
585 return $ret;
586}
587
eeb0abe0
EW
588# '<svn username> = real-name <email address>' mapping based on git-svnimport:
589sub load_authors {
590 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
f8c9d1d2 591 my $log = $cmd eq 'log';
eeb0abe0
EW
592 while (<$authors>) {
593 chomp;
8815788e 594 next unless /^(\S+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
eeb0abe0 595 my ($user, $name, $email) = ($1, $2, $3);
f8c9d1d2
EW
596 if ($log) {
597 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
598 } else {
599 $users{$user} = [$name, $email];
600 }
79bb8d88
EW
601 }
602 close $authors or croak $!;
603}
604
e0d10e1c 605# convert GetOpt::Long specs for use by git-config
b8c92cad 606sub read_repo_config {
706587fc 607 return unless -d $ENV{GIT_DIR};
b8c92cad
EW
608 my $opts = shift;
609 foreach my $o (keys %$opts) {
610 my $v = $opts->{$o};
611 my ($key) = ($o =~ /^([a-z\-]+)/);
612 $key =~ s/-//g;
e0d10e1c 613 my $arg = 'git-config';
b8c92cad
EW
614 $arg .= ' --int' if ($o =~ /[:=]i$/);
615 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
616 if (ref $v eq 'ARRAY') {
617 chomp(my @tmp = `$arg --get-all svn.$key`);
618 @$v = @tmp if @tmp;
619 } else {
620 chomp(my $tmp = `$arg --get svn.$key`);
7774284a 621 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
b8c92cad
EW
622 $$v = $tmp;
623 }
624 }
625 }
626}
627
79bb8d88 628sub extract_metadata {
c1927a85 629 my $id = shift or return (undef, undef, undef);
79bb8d88
EW
630 my ($url, $rev, $uuid) = ($id =~ /^git-svn-id:\s(\S+?)\@(\d+)
631 \s([a-f\d\-]+)$/x);
e70dc780 632 if (!defined $rev || !$uuid || !$url) {
79bb8d88 633 # some of the original repositories I made had
82e5a82f 634 # identifiers like this:
79bb8d88
EW
635 ($rev, $uuid) = ($id =~/^git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
636 }
637 return ($url, $rev, $uuid);
638}
639
c1927a85
EW
640sub cmt_metadata {
641 return extract_metadata((grep(/^git-svn-id: /,
aef4e921 642 command(qw/cat-file commit/, shift)))[-1]);
c1927a85
EW
643}
644
9b981fc6
EW
645package Git::SVN;
646use strict;
647use warnings;
ecc712dd
EW
648use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
649 $_repack $_repack_flags/;
9b981fc6
EW
650use Carp qw/croak/;
651use File::Path qw/mkpath/;
373274f9 652use File::Copy qw/copy/;
9b981fc6
EW
653use IPC::Open3;
654
ecc712dd 655my $_repack_nr;
9b981fc6
EW
656# properties that we do not log:
657my %SKIP_PROP;
658BEGIN {
659 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
660 svn:special svn:executable
661 svn:entry:committed-rev
662 svn:entry:last-author
663 svn:entry:uuid
664 svn:entry:committed-date/;
665}
666
373274f9
EW
667my %LOCKFILES;
668END { unlink keys %LOCKFILES if %LOCKFILES }
669
4bb9ed04
EW
670sub resolve_local_globs {
671 my ($url, $fetch, $glob_spec) = @_;
672 return unless defined $glob_spec;
673 my $ref = $glob_spec->{ref};
674 my $path = $glob_spec->{path};
675 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
676 next unless m#^refs/remotes/$ref->{regex}$#;
677 my $p = $1;
678 my $pathname = $path->full_path($p);
679 my $refname = $ref->full_path($p);
680 if (my $existing = $fetch->{$pathname}) {
681 if ($existing ne $refname) {
682 die "Refspec conflict:\n",
683 "existing: refs/remotes/$existing\n",
684 " globbed: refs/remotes/$refname\n";
685 }
686 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
4e9f6cc7 687 $u =~ s!^\Q$url\E(/|$)!! or die
4bb9ed04
EW
688 "refs/remotes/$refname: '$url' not found in '$u'\n";
689 if ($pathname ne $u) {
690 warn "W: Refspec glob conflict ",
691 "(ref: refs/remotes/$refname):\n",
692 "expected path: $pathname\n",
693 " real path: $u\n",
694 "Continuing ahead with $u\n";
695 next;
696 }
697 } else {
4bb9ed04
EW
698 $fetch->{$pathname} = $refname;
699 }
700 }
701}
702
0af9c9f9 703sub fetch_all {
4bb9ed04 704 my ($repo_id, $remotes) = @_;
e518192f
EW
705 my $remote = $remotes->{$repo_id};
706 my $fetch = $remote->{fetch};
707 my $url = $remote->{url};
708 my (@gs, @globs);
0af9c9f9 709 my $ra = Git::SVN::Ra->new($url);
e518192f 710 my $uuid = $ra->uuid;
0af9c9f9
EW
711 my $head = $ra->get_latest_revnum;
712 my $base = $head;
e518192f
EW
713
714 # read the max revs for wildcard expansion (branches/*, tags/*)
715 foreach my $t (qw/branches tags/) {
716 defined $remote->{$t} or next;
717 push @globs, $remote->{$t};
718 my $f = "$ENV{GIT_DIR}/svn/.$uuid.$t";
719 if (open my $fh, '<', $f) {
720 chomp(my $max_rev = <$fh>);
721 close $fh or die "Error closing $f: $!\n";
722
723 if ($max_rev !~ /^\d+$/) {
724 die "$max_rev (in $f) is not an integer!\n";
725 }
726 $remote->{$t}->{max_rev} = $max_rev;
727 $base = $max_rev if ($max_rev < $base);
728 }
729 }
730
0af9c9f9
EW
731 foreach my $p (sort keys %$fetch) {
732 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
9c93fee5 733 my $lr = $gs->rev_db_max;
0af9c9f9
EW
734 if (defined $lr) {
735 $base = $lr if ($lr < $base);
0af9c9f9
EW
736 }
737 push @gs, $gs;
738 }
e518192f 739 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
0af9c9f9
EW
740}
741
47e39c55
EW
742sub read_all_remotes {
743 my $r = {};
8b8fc068 744 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
47e39c55
EW
745 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
746 $r->{$1}->{fetch}->{$2} = $3;
747 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
748 $r->{$1}->{url} = $2;
4bb9ed04
EW
749 } elsif (m!^(.+)\.(branches|tags)=
750 (.*):refs/remotes/(.+)\s*$/!x) {
751 my ($p, $g) = ($3, $4);
752 my $rs = $r->{$1}->{$2} = {
e518192f 753 t => $2,
4bb9ed04
EW
754 path => Git::SVN::GlobSpec->new($p),
755 ref => Git::SVN::GlobSpec->new($g) };
756 if (length($rs->{ref}->{right}) != 0) {
757 die "The '*' glob character must be the last ",
758 "character of '$g'\n";
759 }
47e39c55
EW
760 }
761 }
762 $r;
763}
764
ecc712dd
EW
765sub init_vars {
766 if (defined $_repack) {
767 $_repack = 1000 if ($_repack <= 0);
768 $_repack_nr = $_repack;
769 $_repack_flags ||= '-d';
770 }
771}
772
b805b44a 773sub verify_remotes_sanity {
536c4b09 774 return unless -d $ENV{GIT_DIR};
b805b44a
EW
775 my %seen;
776 foreach (command(qw/config -l/)) {
777 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
778 if ($seen{$1}) {
779 die "Remote ref refs/remote/$1 is tracked by",
780 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
781 "Please resolve this ambiguity in ",
782 "your git configuration file before ",
783 "continuing\n";
784 }
785 $seen{$1} = $_;
786 }
787 }
788}
789
47e39c55 790# we allow more chars than remotes2config.sh...
706587fc
EW
791sub sanitize_remote_name {
792 my ($name) = @_;
47e39c55 793 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
706587fc
EW
794 $name;
795}
796
e6434f87
EW
797sub find_existing_remote {
798 my ($url, $remotes) = @_;
799 my $existing;
800 foreach my $repo_id (keys %$remotes) {
801 my $u = $remotes->{$repo_id}->{url} or next;
802 next if $u ne $url;
803 $existing = $repo_id;
804 last;
805 }
806 $existing;
807}
b805b44a 808
e6434f87 809sub init_remote_config {
d8115c51 810 my ($self, $url, $no_write) = @_;
e6434f87
EW
811 $url =~ s!/+$!!; # strip trailing slash
812 my $r = read_all_remotes();
813 my $existing = find_existing_remote($url, $r);
814 if ($existing) {
e518192f
EW
815 unless ($no_write) {
816 print STDERR "Using existing ",
817 "[svn-remote \"$existing\"]\n";
818 }
e6434f87
EW
819 $self->{repo_id} = $existing;
820 } else {
821 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
822 $existing = find_existing_remote($min_url, $r);
823 if ($existing) {
e518192f
EW
824 unless ($no_write) {
825 print STDERR "Using existing ",
826 "[svn-remote \"$existing\"]\n";
827 }
e6434f87
EW
828 $self->{repo_id} = $existing;
829 }
830 if ($min_url ne $url) {
e518192f
EW
831 unless ($no_write) {
832 print STDERR "Using higher level of URL: ",
833 "$url => $min_url\n";
834 }
e6434f87
EW
835 my $old_path = $self->{path};
836 $self->{path} = $url;
4e9f6cc7 837 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
e6434f87
EW
838 if (length $old_path) {
839 $self->{path} .= "/$old_path";
840 }
841 $url = $min_url;
842 }
843 }
844 my $orig_url;
845 if (!$existing) {
b805b44a 846 # verify that we aren't overwriting anything:
e6434f87 847 $orig_url = eval {
706587fc 848 command_oneline('config', '--get',
e6434f87 849 "svn-remote.$self->{repo_id}.url")
706587fc 850 };
b805b44a 851 if ($orig_url && ($orig_url ne $url)) {
e6434f87 852 die "svn-remote.$self->{repo_id}.url already set: ",
b805b44a
EW
853 "$orig_url\nwanted to set to: $url\n";
854 }
9b981fc6 855 }
e6434f87
EW
856 my ($xrepo_id, $xpath) = find_ref($self->refname);
857 if (defined $xpath) {
858 die "svn-remote.$xrepo_id.fetch already set to track ",
859 "$xpath:refs/remotes/", $self->refname, "\n";
860 }
d8115c51
EW
861 unless ($no_write) {
862 command_noisy('config',
863 "svn-remote.$self->{repo_id}.url", $url);
864 command_noisy('config', '--add',
865 "svn-remote.$self->{repo_id}.fetch",
866 "$self->{path}:".$self->refname);
867 }
9b981fc6 868 $self->{url} = $url;
e6434f87
EW
869}
870
871sub init {
d8115c51 872 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
e6434f87
EW
873 my $self = _new($class, $repo_id, $ref_id, $path);
874 if (defined $url) {
d8115c51 875 $self->init_remote_config($url, $no_write);
e6434f87 876 }
9b981fc6
EW
877 $self;
878}
879
706587fc
EW
880sub find_ref {
881 my ($ref_id) = @_;
882 foreach (command(qw/config -l/)) {
883 next unless m!^svn-remote\.(.+)\.fetch=
884 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
885 my ($repo_id, $path, $ref) = ($1, $2, $3);
886 if ($ref eq $ref_id) {
887 $path = '' if ($path =~ m#^\./?#);
888 return ($repo_id, $path);
889 }
890 }
891 (undef, undef, undef);
892}
893
9b981fc6 894sub new {
706587fc
EW
895 my ($class, $ref_id, $repo_id, $path) = @_;
896 if (defined $ref_id && !defined $repo_id && !defined $path) {
897 ($repo_id, $path) = find_ref($ref_id);
898 if (!defined $repo_id) {
899 die "Could not find a \"svn-remote.*.fetch\" key ",
900 "in the repository configuration matching: ",
901 "refs/remotes/$ref_id\n";
902 }
903 }
904 my $self = _new($class, $repo_id, $ref_id, $path);
8b8fc068
EW
905 if (!defined $self->{path} || !length $self->{path}) {
906 my $fetch = command_oneline('config', '--get',
907 "svn-remote.$repo_id.fetch",
908 ":refs/remotes/$ref_id\$") or
909 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
910 "\":refs/remotes/$ref_id\$\" in config\n";
911 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
912 }
706587fc
EW
913 $self->{url} = command_oneline('config', '--get',
914 "svn-remote.$repo_id.url") or
915 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
f0ecca10
EW
916 if (-z $self->{db_path} && ::verify_ref($self->refname.'^0')) {
917 $self->rebuild;
918 }
9b981fc6
EW
919 $self;
920}
921
706587fc 922sub refname { "refs/remotes/$_[0]->{ref_id}" }
9b981fc6
EW
923
924sub ra {
925 my ($self) = shift;
5d3b7cd5 926 Git::SVN::Ra->new($self->{url});
9b981fc6
EW
927}
928
15710b6f
EW
929sub rel_path {
930 my ($self) = @_;
931 my $repos_root = $self->ra->{repos_root};
932 return $self->{path} if ($self->{url} eq $repos_root);
4e9f6cc7
EW
933 die "BUG: rel_path failed! repos_root: $repos_root, Ra URL: ",
934 $self->ra->{url}, " path: $self->{path}, URL: $self->{url}\n";
15710b6f
EW
935}
936
9b981fc6
EW
937sub traverse_ignore {
938 my ($self, $fh, $path, $r) = @_;
939 $path =~ s#^/+##g;
5d3b7cd5
EW
940 my $ra = $self->ra;
941 my ($dirent, undef, $props) = $ra->get_dir($path, $r);
9b981fc6 942 my $p = $path;
5d3b7cd5 943 $p =~ s#^\Q$ra->{svn_path}\E/##;
9b981fc6
EW
944 print $fh length $p ? "\n# $p\n" : "\n# /\n";
945 if (my $s = $props->{'svn:ignore'}) {
946 $s =~ s/[\r\n]+/\n/g;
947 chomp $s;
948 if (length $p == 0) {
949 $s =~ s#\n#\n/$p#g;
950 print $fh "/$s\n";
951 } else {
952 $s =~ s#\n#\n/$p/#g;
953 print $fh "/$p/$s\n";
954 }
955 }
956 foreach (sort keys %$dirent) {
957 next if $dirent->{$_}->kind != $SVN::Node::dir;
958 $self->traverse_ignore($fh, "$path/$_", $r);
959 }
960}
961
3ebe8df7
EW
962sub last_rev { ($_[0]->last_rev_commit)[0] }
963sub last_commit { ($_[0]->last_rev_commit)[1] }
964
9b981fc6
EW
965# returns the newest SVN revision number and newest commit SHA1
966sub last_rev_commit {
967 my ($self) = @_;
968 if (defined $self->{last_rev} && defined $self->{last_commit}) {
969 return ($self->{last_rev}, $self->{last_commit});
970 }
d2866f9e 971 my $c = ::verify_ref($self->refname.'^0');
706587fc 972 if ($c) {
d2866f9e 973 my $rev = (::cmt_metadata($c))[1];
9b981fc6
EW
974 if (defined $rev) {
975 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
976 return ($rev, $c);
977 }
978 }
979 my $offset = -41; # from tail
980 my $rl;
981 open my $fh, '<', $self->{db_path} or
982 croak "$self->{db_path} not readable: $!\n";
ce4b4af7
EW
983 sysseek($fh, $offset, 2); # don't care for errors
984 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6 985 chomp $rl;
ce4b4af7 986 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
9b981fc6 987 $offset -= 41;
ce4b4af7
EW
988 sysseek($fh, $offset, 2); # don't care for errors
989 sysread($fh, $rl, 41) == 41 or return (undef, undef);
9b981fc6
EW
990 chomp $rl;
991 }
9c93fee5
EW
992 if ($c) {
993 die "$self->{db_path} and ", $self->refname,
994 " inconsistent!:\n$c != $rl\n";
995 }
ce4b4af7 996 my $rev = sysseek($fh, 0, 1) or croak $!;
9b981fc6
EW
997 $rev = ($rev - 41) / 41;
998 close $fh or croak $!;
999 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1000 return ($rev, $c);
1001}
1002
3ebe8df7
EW
1003sub get_fetch_range {
1004 my ($self, $min, $max) = @_;
1005 $max ||= $self->ra->get_latest_revnum;
9c93fee5 1006 $min ||= $self->rev_db_max;
3ebe8df7 1007 (++$min, $max);
9b981fc6
EW
1008}
1009
1010sub tmp_index_do {
1011 my ($self, $sub) = @_;
1012 my $old_index = $ENV{GIT_INDEX_FILE};
1013 $ENV{GIT_INDEX_FILE} = $self->{index};
1014 my @ret = &$sub;
1015 if ($old_index) {
1016 $ENV{GIT_INDEX_FILE} = $old_index;
1017 } else {
1018 delete $ENV{GIT_INDEX_FILE};
1019 }
1020 wantarray ? @ret : $ret[0];
1021}
1022
1023sub assert_index_clean {
1024 my ($self, $treeish) = @_;
1025
1026 $self->tmp_index_do(sub {
1027 command_noisy('read-tree', $treeish) unless -e $self->{index};
1028 my $x = command_oneline('write-tree');
1029 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1030 /^tree ($::sha1)/mo);
1031 if ($y ne $x) {
1032 unlink $self->{index} or croak $!;
1033 command_noisy('read-tree', $treeish);
1034 }
1035 $x = command_oneline('write-tree');
1036 if ($y ne $x) {
1037 ::fatal "trees ($treeish) $y != $x\n",
1038 "Something is seriously wrong...\n";
1039 }
1040 });
1041}
1042
1043sub get_commit_parents {
0af9c9f9 1044 my ($self, $log_entry) = @_;
9b981fc6 1045 my (%seen, @ret, @tmp);
0af9c9f9
EW
1046 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1047 if (my $ip = $self->{inject_parents}) {
1048 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1049 push @tmp, $commit;
9b981fc6
EW
1050 }
1051 }
d2866f9e 1052 if (my $cur = ::verify_ref($self->refname.'^0')) {
9b981fc6
EW
1053 push @tmp, $cur;
1054 }
44320b9e 1055 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
9b981fc6
EW
1056 while (my $p = shift @tmp) {
1057 next if $seen{$p};
1058 $seen{$p} = 1;
1059 push @ret, $p;
1060 # MAXPARENT is defined to 16 in commit-tree.c:
1061 last if @ret >= 16;
1062 }
1063 if (@tmp) {
44320b9e 1064 die "r$log_entry->{revision}: No room for parents:\n\t",
9b981fc6
EW
1065 join("\n\t", @tmp), "\n";
1066 }
1067 @ret;
1068}
1069
706587fc 1070sub full_url {
9b981fc6 1071 my ($self) = @_;
5d3b7cd5 1072 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
9b981fc6
EW
1073}
1074
1075sub do_git_commit {
0af9c9f9 1076 my ($self, $log_entry) = @_;
8a603774
EW
1077 my $lr = $self->last_rev;
1078 if (defined $lr && $lr >= $log_entry->{revision}) {
1079 die "Last fetched revision of ", $self->refname,
1080 " was r$lr, but we are about to fetch: ",
1081 "r$log_entry->{revision}!\n";
1082 }
44320b9e
EW
1083 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1084 croak "$log_entry->{revision} = $c already exists! ",
9b981fc6
EW
1085 "Why are we refetching it?\n";
1086 }
1c8443b0
EW
1087 my $author = $log_entry->{author};
1088 my ($name, $email) = (defined $::users{$author} ? @{$::users{$author}}
1089 : ($author, "$author\@".$self->ra->uuid));
9b981fc6
EW
1090 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $name;
1091 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} = $email;
44320b9e 1092 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
9b981fc6 1093
44320b9e 1094 my $tree = $log_entry->{tree};
9b981fc6
EW
1095 if (!defined $tree) {
1096 $tree = $self->tmp_index_do(sub {
1097 command_oneline('write-tree') });
1098 }
1099 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1100
1101 my @exec = ('git-commit-tree', $tree);
0af9c9f9 1102 foreach ($self->get_commit_parents($log_entry)) {
9b981fc6
EW
1103 push @exec, '-p', $_;
1104 }
1105 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1106 or croak $!;
44320b9e 1107 print $msg_fh $log_entry->{log} or croak $!;
9760adcc
EW
1108 unless ($_no_metadata) {
1109 print $msg_fh "\ngit-svn-id: ", $self->full_url, '@',
1110 $log_entry->{revision}, ' ',
1111 $self->ra->uuid, "\n" or croak $!;
1112 }
9b981fc6
EW
1113 $msg_fh->flush == 0 or croak $!;
1114 close $msg_fh or croak $!;
1115 chomp(my $commit = do { local $/; <$out_fh> });
1116 close $out_fh or croak $!;
1117 waitpid $pid, 0;
1118 croak $? if $?;
1119 if ($commit !~ /^$::sha1$/o) {
1120 die "Failed to commit, invalid sha1: $commit\n";
1121 }
1122
373274f9 1123 $self->rev_db_set($log_entry->{revision}, $commit, 1);
9b981fc6 1124
44320b9e 1125 $self->{last_rev} = $log_entry->{revision};
9b981fc6 1126 $self->{last_commit} = $commit;
8a603774 1127 print "r$log_entry->{revision} = $commit ($self->{ref_id})\n";
ecc712dd
EW
1128 if (defined $_repack && (--$_repack_nr == 0)) {
1129 $_repack_nr = $_repack;
1130 # repack doesn't use any arguments with spaces in them, does it?
1131 print "Running git repack $_repack_flags ...\n";
1132 command_noisy('repack', split(/\s+/, $_repack_flags));
1133 print "Done repacking\n";
1134 }
9b981fc6
EW
1135 return $commit;
1136}
1137
fbcc1737
EW
1138sub match_paths {
1139 my ($self, $paths, $r) = @_;
4e9f6cc7 1140 return 1 if $self->{path} eq '';
d542aedb
EW
1141 if (my $path = $paths->{"/$self->{path}"}) {
1142 return ($path->{action} eq 'D') ? 0 : 1;
1143 }
4e9f6cc7 1144 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
fbcc1737
EW
1145 if (grep /$self->{path_regex}/, keys %$paths) {
1146 return 1;
1147 }
1148 my $c = '';
1149 foreach (split m#/#, $self->{path}) {
1150 $c .= "/$_";
74a81227
EW
1151 next unless ($paths->{$c} &&
1152 ($paths->{$c}->{action} =~ /^[AR]$/));
e518192f
EW
1153 if ($self->ra->check_path($self->{path}, $r) ==
1154 $SVN::Node::dir) {
fbcc1737
EW
1155 return 1;
1156 }
1157 }
1158 return 0;
1159}
1160
15710b6f
EW
1161sub find_parent_branch {
1162 my ($self, $paths, $rev) = @_;
9760adcc 1163 return undef unless $_follow_parent;
e5a0b240 1164 unless (defined $paths) {
c7eba716
EW
1165 my $err_handler = $SVN::Error::handler;
1166 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
d4eff2bd
EW
1167 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1168 $paths =
1169 Git::SVN::Ra::dup_changed_paths($_[0]) });
c7eba716 1170 $SVN::Error::handler = $err_handler;
e5a0b240
EW
1171 }
1172 return undef unless defined $paths;
15710b6f
EW
1173
1174 # look for a parent from another branch:
7f578c55
EW
1175 my @b_path_components = split m#/#, $self->rel_path;
1176 my @a_path_components;
1177 my $i;
1178 while (@b_path_components) {
1179 $i = $paths->{'/'.join('/', @b_path_components)};
74a81227 1180 last if $i && defined $i->{copyfrom_path};
7f578c55
EW
1181 unshift(@a_path_components, pop(@b_path_components));
1182 }
74a81227
EW
1183 return undef unless defined $i && defined $i->{copyfrom_path};
1184 my $branch_from = $i->{copyfrom_path};
7f578c55
EW
1185 if (@a_path_components) {
1186 print STDERR "branch_from: $branch_from => ";
1187 $branch_from .= '/'.join('/', @a_path_components);
1188 print STDERR $branch_from, "\n";
1189 }
3ebe8df7 1190 my $r = $i->{copyfrom_rev};
15710b6f
EW
1191 my $repos_root = $self->ra->{repos_root};
1192 my $url = $self->ra->{url};
1193 my $new_url = $repos_root . $branch_from;
1194 print STDERR "Found possible branch point: ",
1195 "$new_url => ", $self->full_url, ", $r\n";
1196 $branch_from =~ s#^/##;
1197 my $remotes = read_all_remotes();
1198 my $gs;
1199 foreach my $repo_id (keys %$remotes) {
1200 my $u = $remotes->{$repo_id}->{url} or next;
1201 next if $url ne $u;
1202 my $fetch = $remotes->{$repo_id}->{fetch};
e518192f
EW
1203 foreach (qw/branches tags/) {
1204 resolve_local_globs($url, $fetch,
1205 $remotes->{$repo_id}->{$_});
1206 }
15710b6f
EW
1207 foreach my $f (keys %$fetch) {
1208 next if $f ne $branch_from;
1209 $gs = Git::SVN->new($fetch->{$f}, $repo_id, $f);
1210 last;
1211 }
1212 last if $gs;
1213 }
1214 unless ($gs) {
ce2a0f2f
EW
1215 my $ref_id = $self->{ref_id};
1216 $ref_id =~ s/\@\d+$//;
1217 $ref_id .= "\@$r";
15710b6f
EW
1218 # just grow a tail if we're not unique enough :x
1219 $ref_id .= '-' while find_ref($ref_id);
ce2a0f2f 1220 print STDERR "Initializing parent: $ref_id\n";
d8115c51 1221 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
15710b6f
EW
1222 }
1223 my ($r0, $parent) = $gs->find_rev_before($r, 1);
9760adcc 1224 if ($_follow_parent && (!defined $r0 || !defined $parent)) {
3ebe8df7 1225 $gs->fetch(0, $r);
15710b6f
EW
1226 ($r0, $parent) = $gs->last_rev_commit;
1227 }
ef70de96 1228 if (defined $r0 && defined $parent) {
15710b6f 1229 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
a2003abc 1230 $self->assert_index_clean($parent);
15710b6f
EW
1231 my $ed;
1232 if ($self->ra->can_do_switch) {
8b8fc068 1233 print STDERR "Following parent with do_switch\n";
15710b6f 1234 # do_switch works with svn/trunk >= r22312, but that
2b27f6c8 1235 # is not included with SVN 1.4.3 (the latest version
15710b6f
EW
1236 # at the moment), so we can't rely on it
1237 $self->{last_commit} = $parent;
1238 $ed = SVN::Git::Fetcher->new($self);
8a603774 1239 $gs->ra->gs_do_switch($r0, $rev, $gs,
15710b6f
EW
1240 $self->full_url, $ed)
1241 or die "SVN connection failed somewhere...\n";
1242 } else {
8b8fc068 1243 print STDERR "Following parent with do_update\n";
15710b6f 1244 $ed = SVN::Git::Fetcher->new($self);
8a603774 1245 $self->ra->gs_do_update($rev, $rev, $self, $ed)
15710b6f
EW
1246 or die "SVN connection failed somewhere...\n";
1247 }
f7c3fc4a 1248 print STDERR "Successfully followed parent\n";
15710b6f
EW
1249 return $self->make_log_entry($rev, [$parent], $ed);
1250 }
15710b6f
EW
1251 return undef;
1252}
1253
9b981fc6 1254sub do_fetch {
706587fc 1255 my ($self, $paths, $rev) = @_;
15710b6f 1256 my $ed;
9b981fc6 1257 my ($last_rev, @parents);
b9dffd8c
EW
1258 if (my $lc = $self->last_commit) {
1259 # we can have a branch that was deleted, then re-added
1260 # under the same name but copied from another path, in
1261 # which case we'll have multiple parents (we don't
1262 # want to break the original ref, nor lose copypath info):
1263 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1264 push @{$log_entry->{parents}}, $lc;
1265 return $log_entry;
1266 }
15710b6f 1267 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1268 $last_rev = $self->{last_rev};
b9dffd8c
EW
1269 $ed->{c} = $lc;
1270 @parents = ($lc);
9b981fc6
EW
1271 } else {
1272 $last_rev = $rev;
15710b6f
EW
1273 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
1274 return $log_entry;
1275 }
1276 $ed = SVN::Git::Fetcher->new($self);
9b981fc6 1277 }
8a603774 1278 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
9b981fc6
EW
1279 die "SVN connection failed somewhere...\n";
1280 }
1281 $self->make_log_entry($rev, \@parents, $ed);
1282}
1283
97f6987a
EW
1284sub get_untracked {
1285 my ($self, $ed) = @_;
1286 my @out;
1287 my $h = $ed->{empty};
9b981fc6
EW
1288 foreach (sort keys %$h) {
1289 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
97f6987a 1290 push @out, " $act: " . uri_encode($_);
9b981fc6
EW
1291 warn "W: $act: $_\n";
1292 }
1293 foreach my $t (qw/dir_prop file_prop/) {
97f6987a 1294 $h = $ed->{$t} or next;
9b981fc6
EW
1295 foreach my $path (sort keys %$h) {
1296 my $ppath = $path eq '' ? '.' : $path;
1297 foreach my $prop (sort keys %{$h->{$path}}) {
1ce255dc 1298 next if $SKIP_PROP{$prop};
9b981fc6 1299 my $v = $h->{$path}->{$prop};
97f6987a
EW
1300 my $t_ppath_prop = "$t: " .
1301 uri_encode($ppath) . ' ' .
1302 uri_encode($prop);
9b981fc6 1303 if (defined $v) {
97f6987a
EW
1304 push @out, " +$t_ppath_prop " .
1305 uri_encode($v);
9b981fc6 1306 } else {
97f6987a 1307 push @out, " -$t_ppath_prop";
9b981fc6
EW
1308 }
1309 }
1310 }
1311 }
1312 foreach my $t (qw/absent_file absent_directory/) {
97f6987a 1313 $h = $ed->{$t} or next;
9b981fc6
EW
1314 foreach my $parent (sort keys %$h) {
1315 foreach my $path (sort @{$h->{$parent}}) {
97f6987a
EW
1316 push @out, " $t: " .
1317 uri_encode("$parent/$path");
9b981fc6
EW
1318 warn "W: $t: $parent/$path ",
1319 "Insufficient permissions?\n";
1320 }
1321 }
1322 }
97f6987a 1323 \@out;
9b981fc6
EW
1324}
1325
1c8443b0
EW
1326sub parse_svn_date {
1327 my $date = shift || return '+0000 1970-01-01 00:00:00';
1328 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
1329 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
1330 croak "Unable to parse date: $date\n";
1331 "+0000 $Y-$m-$d $H:$M:$S";
1332}
1333
1334sub check_author {
1335 my ($author) = @_;
1336 if (!defined $author || length $author == 0) {
1337 $author = '(no author)';
1338 }
1339 if (defined $::_authors && ! defined $::users{$author}) {
1340 die "Author: $author not defined in $::_authors file\n";
1341 }
1342 $author;
1343}
1344
9b981fc6 1345sub make_log_entry {
97f6987a
EW
1346 my ($self, $rev, $parents, $ed) = @_;
1347 my $untracked = $self->get_untracked($ed);
1348
9b981fc6 1349 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
97f6987a
EW
1350 print $un "r$rev\n" or croak $!;
1351 print $un $_, "\n" foreach @$untracked;
1352 my %log_entry = ( parents => $parents || [], revision => $rev,
1353 log => '');
fbcc1737
EW
1354
1355 my $logged = delete $self->{logged_rev_props};
1356 if (!$logged || $self->{-want_extra_revprops}) {
1357 my $rp = $self->ra->rev_proplist($rev);
1358 foreach (sort keys %$rp) {
1359 my $v = $rp->{$_};
1360 if (/^svn:(author|date|log)$/) {
1361 $log_entry{$1} = $v;
1362 } else {
1363 print $un " rev_prop: ", uri_encode($_), ' ',
1364 uri_encode($v), "\n";
1365 }
9b981fc6 1366 }
fbcc1737
EW
1367 } else {
1368 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
9b981fc6
EW
1369 }
1370 close $un or croak $!;
97f6987a 1371
9b981fc6
EW
1372 $log_entry{date} = parse_svn_date($log_entry{date});
1373 $log_entry{author} = check_author($log_entry{author});
1374 $log_entry{log} .= "\n";
1375 \%log_entry;
1376}
1377
1378sub fetch {
3ebe8df7 1379 my ($self, $min_rev, $max_rev, @parents) = @_;
9b981fc6 1380 my ($last_rev, $last_commit) = $self->last_rev_commit;
3ebe8df7 1381 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
e518192f 1382 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
9b981fc6
EW
1383}
1384
1385sub set_tree_cb {
1386 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
1387 # TODO: enable and test optimized commits:
1388 if (0 && $rev == ($self->{last_rev} + 1)) {
1389 $log_entry->{revision} = $rev;
1390 $log_entry->{author} = $author;
1391 $self->do_git_commit($log_entry, "$rev=$tree");
1392 } else {
0af9c9f9
EW
1393 $self->{inject_parents} = { $rev => $tree };
1394 $self->fetch(undef, undef);
9b981fc6
EW
1395 }
1396}
1397
1398sub set_tree {
1399 my ($self, $tree) = (shift, shift);
1ce255dc 1400 my $log_entry = ::get_commit_entry($tree);
9b981fc6
EW
1401 unless ($self->{last_rev}) {
1402 fatal("Must have an existing revision to commit\n");
1403 }
61395354
EW
1404 my %ed_opts = ( r => $self->{last_rev},
1405 log => $log_entry->{log},
1406 ra => $self->ra,
1407 tree_a => $self->{last_commit},
1408 tree_b => $tree,
1409 editor_cb => sub {
1410 $self->set_tree_cb($log_entry, $tree, @_) },
1411 svn_path => $self->{path} );
1412 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
9b981fc6
EW
1413 print "No changes\nr$self->{last_rev} = $tree\n";
1414 }
9b981fc6
EW
1415}
1416
f0ecca10
EW
1417sub rebuild {
1418 my ($self) = @_;
1419 print "Rebuilding $self->{db_path} ...\n";
1420 my ($rev_list, $ctx) = command_output_pipe("rev-list", $self->refname);
1421 my $latest;
1422 my $full_url = $self->full_url;
1423 my $svn_uuid;
1424 while (<$rev_list>) {
1425 chomp;
1426 my $c = $_;
1427 die "Non-SHA1: $c\n" unless $c =~ /^$::sha1$/o;
1428 my ($url, $rev, $uuid) = ::cmt_metadata($c);
1429
1430 # ignore merges (from set-tree)
1431 next if (!defined $rev || !$uuid);
1432
1433 # if we merged or otherwise started elsewhere, this is
1434 # how we break out of it
1435 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
1436 ($full_url && $url && ($url ne $full_url))) {
1437 next;
1438 }
1439 $latest ||= $rev;
1440 $svn_uuid ||= $uuid;
1441
1442 $self->rev_db_set($rev, $c);
1443 print "r$rev = $c\n";
1444 }
1445 command_close_pipe($rev_list, $ctx);
1446 print "Done rebuilding $self->{db_path}\n";
1447}
1448
9b981fc6
EW
1449# rev_db:
1450# Tie::File seems to be prone to offset errors if revisions get sparse,
1451# it's not that fast, either. Tie::File is also not in Perl 5.6. So
1452# one of my favorite modules is out :< Next up would be one of the DBM
1453# modules, but I'm not sure which is most portable... So I'll just
1454# go with something that's plain-text, but still capable of
1455# being randomly accessed. So here's my ultra-simple fixed-width
1456# database. All records are 40 characters + "\n", so it's easy to seek
1457# to a revision: (41 * rev) is the byte offset.
1458# A record of 40 0s denotes an empty revision.
1459# And yes, it's still pretty fast (faster than Tie::File).
373274f9 1460# These files are disposable unless --no-metadata is set
9b981fc6
EW
1461
1462sub rev_db_set {
373274f9 1463 my ($self, $rev, $commit, $update_ref) = @_;
9b981fc6 1464 length $commit == 40 or croak "arg3 must be a full SHA1 hexsum\n";
373274f9
EW
1465 my ($db, $db_lock) = ($self->{db_path}, "$self->{db_path}.lock");
1466 my $sig;
1467 if ($update_ref) {
1468 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1469 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
1470 }
1471 $LOCKFILES{$db_lock} = 1;
1472 if ($_no_metadata) {
1473 copy($db, $db_lock) or die "rev_db_set(@_): ",
1474 "Failed to copy: ",
1475 "$db => $db_lock ($!)\n";
1476 } else {
1477 rename $db, $db_lock or die "rev_db_set(@_): ",
1478 "Failed to rename: ",
1479 "$db => $db_lock ($!)\n";
1480 }
1481 open my $fh, '+<', $db_lock or croak $!;
9b981fc6
EW
1482 my $offset = $rev * 41;
1483 # assume that append is the common case:
1484 seek $fh, 0, 2 or croak $!;
1485 my $pos = tell $fh;
1486 if ($pos < $offset) {
47a0b75e
EW
1487 for (1 .. (($offset - $pos) / 41)) {
1488 print $fh (('0' x 40),"\n") or croak $!;
1489 }
9b981fc6
EW
1490 }
1491 seek $fh, $offset, 0 or croak $!;
1492 print $fh $commit,"\n" or croak $!;
1493 close $fh or croak $!;
373274f9
EW
1494 if ($update_ref) {
1495 command_noisy('update-ref', '-m', "r$rev",
1496 $self->refname, $commit);
1497 }
1498 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
1499 "$db_lock => $db ($!)\n";
1500 delete $LOCKFILES{$db_lock};
1501 if ($update_ref) {
1502 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
1503 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
1504 kill $sig, $$ if defined $sig;
1505 }
9b981fc6
EW
1506}
1507
9c93fee5
EW
1508sub rev_db_max {
1509 my ($self) = @_;
1510 my @stat = stat $self->{db_path} or
1511 die "Couldn't stat $self->{db_path}: $!\n";
1512 ($stat[7] % 41) == 0 or
1513 die "$self->{db_path} inconsistent size:$stat[7]\n";
1514 my $max = $stat[7] / 41;
1515 (($max > 0) ? $max - 1 : 0);
1516}
1517
9b981fc6
EW
1518sub rev_db_get {
1519 my ($self, $rev) = @_;
1520 my $ret;
1521 my $offset = $rev * 41;
1522 open my $fh, '<', $self->{db_path} or croak $!;
ce4b4af7
EW
1523 if (sysseek($fh, $offset, 0) == $offset) {
1524 my $read = sysread($fh, $ret, 40);
1525 $ret = undef if ($read != 40 || $ret eq ('0'x40));
9b981fc6
EW
1526 }
1527 close $fh or croak $!;
1528 $ret;
1529}
1530
15710b6f
EW
1531sub find_rev_before {
1532 my ($self, $rev, $eq_ok) = @_;
1533 --$rev unless $eq_ok;
1534 while ($rev > 0) {
1535 if (my $c = $self->rev_db_get($rev)) {
1536 return ($rev, $c);
1537 }
1538 --$rev;
1539 }
1540 return (undef, undef);
1541}
1542
9b981fc6 1543sub _new {
706587fc
EW
1544 my ($class, $repo_id, $ref_id, $path) = @_;
1545 unless (defined $repo_id && length $repo_id) {
1546 $repo_id = $Git::SVN::default_repo_id;
1547 }
1548 unless (defined $ref_id && length $ref_id) {
8b8fc068 1549 $_[2] = $ref_id = $Git::SVN::default_ref_id;
706587fc
EW
1550 }
1551 $_[1] = $repo_id = sanitize_remote_name($repo_id);
1552 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
1553 $_[3] = $path = '' unless (defined $path);
8b8fc068
EW
1554 mkpath([$dir]);
1555 unless (-f "$dir/.rev_db") {
1556 open my $fh, '>>', "$dir/.rev_db" or croak $!;
1557 close $fh or croak $!;
1558 }
706587fc
EW
1559 bless { ref_id => $ref_id, dir => $dir, index => "$dir/index",
1560 path => $path,
1561 db_path => "$dir/.rev_db", repo_id => $repo_id }, $class;
9b981fc6
EW
1562}
1563
1c8443b0
EW
1564sub uri_encode {
1565 my ($f) = @_;
1566 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
1567 $f
1568}
9b981fc6 1569
d976acfd
EW
1570package Git::SVN::Prompt;
1571use strict;
1572use warnings;
1573require SVN::Core;
1574use vars qw/$_no_auth_cache $_username/;
1575
1576sub simple {
30d055aa
EW
1577 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
1578 $may_save = undef if $_no_auth_cache;
1579 $default_username = $_username if defined $_username;
1580 if (defined $default_username && length $default_username) {
1581 if (defined $realm && length $realm) {
6f729591
EW
1582 print STDERR "Authentication realm: $realm\n";
1583 STDERR->flush;
30d055aa
EW
1584 }
1585 $cred->username($default_username);
1586 } else {
d976acfd 1587 username($cred, $realm, $may_save, $pool);
30d055aa
EW
1588 }
1589 $cred->password(_read_password("Password for '" .
1590 $cred->username . "': ", $realm));
1591 $cred->may_save($may_save);
1592 $SVN::_Core::SVN_NO_ERROR;
1593}
1594
d976acfd 1595sub ssl_server_trust {
30d055aa
EW
1596 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
1597 $may_save = undef if $_no_auth_cache;
6f729591 1598 print STDERR "Error validating server certificate for '$realm':\n";
30d055aa 1599 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
6f729591 1600 print STDERR " - The certificate is not issued by a trusted ",
30d055aa
EW
1601 "authority. Use the\n",
1602 " fingerprint to validate the certificate manually!\n";
1603 }
1604 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
6f729591 1605 print STDERR " - The certificate hostname does not match.\n";
30d055aa
EW
1606 }
1607 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
6f729591 1608 print STDERR " - The certificate is not yet valid.\n";
30d055aa
EW
1609 }
1610 if ($failures & $SVN::Auth::SSL::EXPIRED) {
6f729591 1611 print STDERR " - The certificate has expired.\n";
30d055aa
EW
1612 }
1613 if ($failures & $SVN::Auth::SSL::OTHER) {
6f729591 1614 print STDERR " - The certificate has an unknown error.\n";
30d055aa 1615 }
6f729591
EW
1616 printf STDERR
1617 "Certificate information:\n".
30d055aa
EW
1618 " - Hostname: %s\n".
1619 " - Valid: from %s until %s\n".
1620 " - Issuer: %s\n".
1621 " - Fingerprint: %s\n",
1622 map $cert_info->$_, qw(hostname valid_from valid_until
6f729591 1623 issuer_dname fingerprint);
30d055aa
EW
1624 my $choice;
1625prompt:
6f729591 1626 print STDERR $may_save ?
30d055aa
EW
1627 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
1628 "(R)eject or accept (t)emporarily? ";
6f729591 1629 STDERR->flush;
30d055aa
EW
1630 $choice = lc(substr(<STDIN> || 'R', 0, 1));
1631 if ($choice =~ /^t$/i) {
1632 $cred->may_save(undef);
1633 } elsif ($choice =~ /^r$/i) {
1634 return -1;
1635 } elsif ($may_save && $choice =~ /^p$/i) {
1636 $cred->may_save($may_save);
1637 } else {
1638 goto prompt;
1639 }
1640 $cred->accepted_failures($failures);
1641 $SVN::_Core::SVN_NO_ERROR;
1642}
1643
d976acfd 1644sub ssl_client_cert {
30d055aa
EW
1645 my ($cred, $realm, $may_save, $pool) = @_;
1646 $may_save = undef if $_no_auth_cache;
6f729591
EW
1647 print STDERR "Client certificate filename: ";
1648 STDERR->flush;
30d055aa
EW
1649 chomp(my $filename = <STDIN>);
1650 $cred->cert_file($filename);
1651 $cred->may_save($may_save);
1652 $SVN::_Core::SVN_NO_ERROR;
1653}
1654
d976acfd 1655sub ssl_client_cert_pw {
30d055aa
EW
1656 my ($cred, $realm, $may_save, $pool) = @_;
1657 $may_save = undef if $_no_auth_cache;
1658 $cred->password(_read_password("Password: ", $realm));
1659 $cred->may_save($may_save);
1660 $SVN::_Core::SVN_NO_ERROR;
1661}
1662
d976acfd 1663sub username {
30d055aa
EW
1664 my ($cred, $realm, $may_save, $pool) = @_;
1665 $may_save = undef if $_no_auth_cache;
1666 if (defined $realm && length $realm) {
6f729591 1667 print STDERR "Authentication realm: $realm\n";
30d055aa
EW
1668 }
1669 my $username;
1670 if (defined $_username) {
1671 $username = $_username;
1672 } else {
6f729591
EW
1673 print STDERR "Username: ";
1674 STDERR->flush;
30d055aa
EW
1675 chomp($username = <STDIN>);
1676 }
1677 $cred->username($username);
1678 $cred->may_save($may_save);
1679 $SVN::_Core::SVN_NO_ERROR;
1680}
1681
1682sub _read_password {
1683 my ($prompt, $realm) = @_;
6f729591
EW
1684 print STDERR $prompt;
1685 STDERR->flush;
30d055aa
EW
1686 require Term::ReadKey;
1687 Term::ReadKey::ReadMode('noecho');
1688 my $password = '';
1689 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
1690 last if $key =~ /[\012\015]/; # \n\r
1691 $password .= $key;
1692 }
1693 Term::ReadKey::ReadMode('restore');
6f729591
EW
1694 print STDERR "\n";
1695 STDERR->flush;
30d055aa
EW
1696 $password;
1697}
1698
d976acfd
EW
1699package main;
1700
b9c85187
EW
1701{
1702 my $kill_stupid_warnings = $SVN::Node::none.$SVN::Node::file.
1703 $SVN::Node::dir.$SVN::Node::unknown.
1704 $SVN::Node::none.$SVN::Node::file.
1705 $SVN::Node::dir.$SVN::Node::unknown.
1706 $SVN::Auth::SSL::CNMISMATCH.
1707 $SVN::Auth::SSL::NOTYETVALID.
1708 $SVN::Auth::SSL::EXPIRED.
1709 $SVN::Auth::SSL::UNKNOWNCA.
1710 $SVN::Auth::SSL::OTHER;
1711}
1712
27a1a801
EW
1713package SVN::Git::Fetcher;
1714use vars qw/@ISA/;
1715use strict;
1716use warnings;
1717use Carp qw/croak/;
1718use IO::File qw//;
90c1b15d 1719use Digest::MD5;
27a1a801
EW
1720
1721# file baton members: path, mode_a, mode_b, pool, fh, blob, base
1722sub new {
1723 my ($class, $git_svn) = @_;
1724 my $self = SVN::Delta::Editor->new;
1725 bless $self, $class;
1c8443b0 1726 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
d2a9a87b
EW
1727 $self->{empty} = {};
1728 $self->{dir_prop} = {};
1729 $self->{file_prop} = {};
1730 $self->{absent_dir} = {};
1731 $self->{absent_file} = {};
ef3cfaad 1732 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
27a1a801
EW
1733 $self;
1734}
1735
8b8fc068
EW
1736sub set_path_strip {
1737 my ($self, $path) = @_;
4e9f6cc7 1738 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
8b8fc068
EW
1739}
1740
d2a9a87b
EW
1741sub open_root {
1742 { path => '' };
1743}
1744
1745sub open_directory {
1746 my ($self, $path, $pb, $rev) = @_;
1747 { path => $path };
1748}
1749
706587fc
EW
1750sub git_path {
1751 my ($self, $path) = @_;
2b27f6c8
EW
1752 if ($self->{path_strip}) {
1753 $path =~ s!$self->{path_strip}!! or
1754 die "Failed to strip path '$path' ($self->{path_strip})\n";
1755 }
706587fc
EW
1756 $path;
1757}
1758
27a1a801
EW
1759sub delete_entry {
1760 my ($self, $path, $rev, $pb) = @_;
4a87db0e 1761
706587fc 1762 my $gpath = $self->git_path($path);
8a603774
EW
1763 return undef if ($gpath eq '');
1764
4a87db0e 1765 # remove entire directories.
706587fc 1766 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
4a87db0e
EW
1767 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
1768 -r --name-only -z/,
706587fc 1769 $self->{c}, '--', $gpath);
4a87db0e
EW
1770 local $/ = "\0";
1771 while (<$ls>) {
ef3cfaad
EW
1772 chomp;
1773 $self->{gii}->remove($_);
9e3cdbd4 1774 print "\tD\t$_\n" unless $::_q;
4a87db0e 1775 }
9e3cdbd4 1776 print "\tD\t$gpath/\n" unless $::_q;
4a87db0e
EW
1777 command_close_pipe($ls, $ctx);
1778 $self->{empty}->{$path} = 0
1779 } else {
ef3cfaad 1780 $self->{gii}->remove($gpath);
9e3cdbd4 1781 print "\tD\t$gpath\n" unless $::_q;
4a87db0e 1782 }
27a1a801
EW
1783 undef;
1784}
1785
1786sub open_file {
1787 my ($self, $path, $pb, $rev) = @_;
706587fc
EW
1788 my $gpath = $self->git_path($path);
1789 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
27a1a801 1790 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
006ede5e
EW
1791 unless (defined $mode && defined $blob) {
1792 die "$path was not found in commit $self->{c} (r$rev)\n";
1793 }
27a1a801 1794 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
0864e3ba 1795 pool => SVN::Pool->new, action => 'M' };
27a1a801
EW
1796}
1797
1798sub add_file {
1799 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
d2a9a87b
EW
1800 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1801 delete $self->{empty}->{$dir};
27a1a801 1802 { path => $path, mode_a => 100644, mode_b => 100644,
0864e3ba 1803 pool => SVN::Pool->new, action => 'A' };
27a1a801
EW
1804}
1805
d2a9a87b
EW
1806sub add_directory {
1807 my ($self, $path, $cp_path, $cp_rev) = @_;
1808 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
1809 delete $self->{empty}->{$dir};
1810 $self->{empty}->{$path} = 1;
1811 { path => $path };
1812}
1813
1814sub change_dir_prop {
1815 my ($self, $db, $prop, $value) = @_;
1816 $self->{dir_prop}->{$db->{path}} ||= {};
1817 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
1818 undef;
1819}
1820
1821sub absent_directory {
1822 my ($self, $path, $pb) = @_;
1823 $self->{absent_dir}->{$pb->{path}} ||= [];
1824 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
1825 undef;
1826}
1827
1828sub absent_file {
1829 my ($self, $path, $pb) = @_;
1830 $self->{absent_file}->{$pb->{path}} ||= [];
1831 push @{$self->{absent_file}->{$pb->{path}}}, $path;
1832 undef;
1833}
1834
27a1a801
EW
1835sub change_file_prop {
1836 my ($self, $fb, $prop, $value) = @_;
1837 if ($prop eq 'svn:executable') {
1838 if ($fb->{mode_b} != 120000) {
1839 $fb->{mode_b} = defined $value ? 100755 : 100644;
1840 }
1841 } elsif ($prop eq 'svn:special') {
1842 $fb->{mode_b} = defined $value ? 120000 : 100644;
d2a9a87b
EW
1843 } else {
1844 $self->{file_prop}->{$fb->{path}} ||= {};
1845 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
27a1a801
EW
1846 }
1847 undef;
1848}
1849
1850sub apply_textdelta {
1851 my ($self, $fb, $exp) = @_;
1852 my $fh = IO::File->new_tmpfile;
1853 $fh->autoflush(1);
1854 # $fh gets auto-closed() by SVN::TxDelta::apply(),
1855 # (but $base does not,) so dup() it for reading in close_file
1856 open my $dup, '<&', $fh or croak $!;
1857 my $base = IO::File->new_tmpfile;
1858 $base->autoflush(1);
1859 if ($fb->{blob}) {
1860 defined (my $pid = fork) or croak $!;
1861 if (!$pid) {
1862 open STDOUT, '>&', $base or croak $!;
1863 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
1864 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
1865 }
1866 waitpid $pid, 0;
1867 croak $? if $?;
1868
1869 if (defined $exp) {
1870 seek $base, 0, 0 or croak $!;
1871 my $md5 = Digest::MD5->new;
1872 $md5->addfile($base);
1873 my $got = $md5->hexdigest;
1874 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
1875 "expected: $exp\n",
1876 " got: $got\n" if ($got ne $exp);
1877 }
1878 }
1879 seek $base, 0, 0 or croak $!;
1880 $fb->{fh} = $dup;
1881 $fb->{base} = $base;
1882 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
1883}
1884
1885sub close_file {
1886 my ($self, $fb, $exp) = @_;
1887 my $hash;
706587fc 1888 my $path = $self->git_path($fb->{path});
27a1a801
EW
1889 if (my $fh = $fb->{fh}) {
1890 seek($fh, 0, 0) or croak $!;
1891 my $md5 = Digest::MD5->new;
1892 $md5->addfile($fh);
1893 my $got = $md5->hexdigest;
1894 die "Checksum mismatch: $path\n",
1895 "expected: $exp\n got: $got\n" if ($got ne $exp);
1896 seek($fh, 0, 0) or croak $!;
1897 if ($fb->{mode_b} == 120000) {
1898 read($fh, my $buf, 5) == 5 or croak $!;
1899 $buf eq 'link ' or die "$path has mode 120000",
1900 "but is not a link\n";
1901 }
1902 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
1903 if (!$pid) {
1904 open STDIN, '<&', $fh or croak $!;
1905 exec qw/git-hash-object -w --stdin/ or croak $!;
1906 }
1907 chomp($hash = do { local $/; <$out> });
1908 close $out or croak $!;
1909 close $fh or croak $!;
1910 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
1911 close $fb->{base} or croak $!;
1912 } else {
1913 $hash = $fb->{blob} or die "no blob information\n";
1914 }
1915 $fb->{pool}->clear;
ef3cfaad 1916 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
9e3cdbd4 1917 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
27a1a801
EW
1918 undef;
1919}
1920
1921sub abort_edit {
1922 my $self = shift;
ef3cfaad
EW
1923 $self->{nr} = $self->{gii}->{nr};
1924 delete $self->{gii};
27a1a801
EW
1925 $self->SUPER::abort_edit(@_);
1926}
1927
1928sub close_edit {
1929 my $self = shift;
dad73c0b 1930 $self->{git_commit_ok} = 1;
ef3cfaad
EW
1931 $self->{nr} = $self->{gii}->{nr};
1932 delete $self->{gii};
27a1a801
EW
1933 $self->SUPER::close_edit(@_);
1934}
1a82e793 1935
a5e0cedc 1936package SVN::Git::Editor;
24e22aa8 1937use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
a5e0cedc
EW
1938use strict;
1939use warnings;
1940use Carp qw/croak/;
1941use IO::File;
90c1b15d 1942use Digest::MD5;
a5e0cedc
EW
1943
1944sub new {
61395354
EW
1945 my ($class, $opts) = @_;
1946 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
1947 die "$_ required!\n" unless (defined $opts->{$_});
1948 }
1949
1950 my $pool = SVN::Pool->new;
1951 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
1952 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
1953 $opts->{r}, $mods);
1954
1955 # $opts->{ra} functions should not be used after this:
1956 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
1957 $opts->{editor_cb}, $pool);
1958 my $self = SVN::Delta::Editor->new(@ce, $pool);
a5e0cedc 1959 bless $self, $class;
61395354
EW
1960 foreach (qw/svn_path r tree_a tree_b/) {
1961 $self->{$_} = $opts->{$_};
a5e0cedc 1962 }
61395354
EW
1963 $self->{url} = $opts->{ra}->{url};
1964 $self->{mods} = $mods;
1965 $self->{types} = $types;
1966 $self->{pool} = $pool;
a5e0cedc
EW
1967 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
1968 $self->{rm} = { };
d3a840dc
EW
1969 $self->{path_prefix} = length $self->{svn_path} ?
1970 "$self->{svn_path}/" : '';
a5e0cedc
EW
1971 return $self;
1972}
1973
61395354
EW
1974sub generate_diff {
1975 my ($tree_a, $tree_b) = @_;
1976 my @diff_tree = qw(diff-tree -z -r);
24e22aa8
EW
1977 if ($_cp_similarity) {
1978 push @diff_tree, "-C$_cp_similarity";
61395354
EW
1979 } else {
1980 push @diff_tree, '-C';
1981 }
24e22aa8
EW
1982 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
1983 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
61395354
EW
1984 push @diff_tree, $tree_a, $tree_b;
1985 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
1986 local $/ = "\0";
1987 my $state = 'meta';
1988 my @mods;
1989 while (<$diff_fh>) {
1990 chomp $_; # this gets rid of the trailing "\0"
1991 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
1992 $::sha1\s($::sha1)\s
1993 ([MTCRAD])\d*$/xo) {
1994 push @mods, { mode_a => $1, mode_b => $2,
1995 sha1_b => $3, chg => $4 };
1996 if ($4 =~ /^(?:C|R)$/) {
1997 $state = 'file_a';
1998 } else {
1999 $state = 'file_b';
2000 }
2001 } elsif ($state eq 'file_a') {
2002 my $x = $mods[$#mods] or croak "Empty array\n";
2003 if ($x->{chg} !~ /^(?:C|R)$/) {
2004 croak "Error parsing $_, $x->{chg}\n";
2005 }
2006 $x->{file_a} = $_;
2007 $state = 'file_b';
2008 } elsif ($state eq 'file_b') {
2009 my $x = $mods[$#mods] or croak "Empty array\n";
2010 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2011 croak "Error parsing $_, $x->{chg}\n";
2012 }
2013 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2014 croak "Error parsing $_, $x->{chg}\n";
2015 }
2016 $x->{file_b} = $_;
2017 $state = 'meta';
2018 } else {
2019 croak "Error parsing $_\n";
2020 }
2021 }
2022 command_close_pipe($diff_fh, $ctx);
2023 \@mods;
2024}
2025
2026sub check_diff_paths {
2027 my ($ra, $pfx, $rev, $mods) = @_;
2028 my %types;
2029 $pfx .= '/' if length $pfx;
2030
2031 sub type_diff_paths {
2032 my ($ra, $types, $path, $rev) = @_;
2033 my @p = split m#/+#, $path;
2034 my $c = shift @p;
2035 unless (defined $types->{$c}) {
2036 $types->{$c} = $ra->check_path($c, $rev);
2037 }
2038 while (@p) {
2039 $c .= '/' . shift @p;
2040 next if defined $types->{$c};
2041 $types->{$c} = $ra->check_path($c, $rev);
2042 }
2043 }
2044
2045 foreach my $m (@$mods) {
2046 foreach my $f (qw/file_a file_b/) {
2047 next unless defined $m->{$f};
2048 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2049 if (length $pfx.$dir && ! defined $types{$dir}) {
2050 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2051 }
2052 }
2053 }
2054 \%types;
2055}
2056
a5e0cedc
EW
2057sub split_path {
2058 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2059}
2060
2061sub repo_path {
d3a840dc
EW
2062 my ($self, $path) = @_;
2063 $self->{path_prefix}.(defined $path ? $path : '');
a5e0cedc
EW
2064}
2065
2066sub url_path {
2067 my ($self, $path) = @_;
6e8548cc 2068 $self->{url} . '/' . $self->repo_path($path);
a5e0cedc
EW
2069}
2070
2071sub rmdirs {
61395354 2072 my ($self) = @_;
a5e0cedc
EW
2073 my $rm = $self->{rm};
2074 delete $rm->{''}; # we never delete the url we're tracking
2075 return unless %$rm;
2076
2077 foreach (keys %$rm) {
2078 my @d = split m#/#, $_;
2079 my $c = shift @d;
2080 $rm->{$c} = 1;
2081 while (@d) {
2082 $c .= '/' . shift @d;
2083 $rm->{$c} = 1;
2084 }
2085 }
2086 delete $rm->{$self->{svn_path}};
2087 delete $rm->{''}; # we never delete the url we're tracking
2088 return unless %$rm;
2089
61395354
EW
2090 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2091 $self->{tree_b});
a5e0cedc
EW
2092 local $/ = "\0";
2093 while (<$fh>) {
2094 chomp;
747fa12c 2095 my @dn = split m#/#, $_;
c07eee1f
EW
2096 while (pop @dn) {
2097 delete $rm->{join '/', @dn};
2098 }
2099 unless (%$rm) {
22600a25 2100 close $fh;
c07eee1f
EW
2101 return;
2102 }
a5e0cedc 2103 }
aef4e921 2104 command_close_pipe($fh, $ctx);
c07eee1f 2105
a5e0cedc
EW
2106 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
2107 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
2108 $self->close_directory($bat->{$d}, $p);
2109 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
44320b9e 2110 print "\tD+\t$d/\n" unless $::_q;
a5e0cedc
EW
2111 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
2112 delete $bat->{$d};
2113 }
2114}
2115
2116sub open_or_add_dir {
2117 my ($self, $full_path, $baton) = @_;
6e8548cc
EW
2118 my $t = $self->{types}->{$full_path};
2119 if (!defined $t) {
2120 die "$full_path not known in r$self->{r} or we have a bug!\n";
2121 }
a5e0cedc
EW
2122 if ($t == $SVN::Node::none) {
2123 return $self->add_directory($full_path, $baton,
2124 undef, -1, $self->{pool});
2125 } elsif ($t == $SVN::Node::dir) {
2126 return $self->open_directory($full_path, $baton,
2127 $self->{r}, $self->{pool});
2128 }
2129 print STDERR "$full_path already exists in repository at ",
2130 "r$self->{r} and it is not a directory (",
2131 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
2132 exit 1;
2133}
2134
2135sub ensure_path {
2136 my ($self, $path) = @_;
2137 my $bat = $self->{bat};
6e8548cc
EW
2138 my $repo_path = $self->repo_path($path);
2139 return $bat->{''} unless (length $repo_path);
2140 my @p = split m#/+#, $repo_path;
a5e0cedc
EW
2141 my $c = shift @p;
2142 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
2143 while (@p) {
2144 my $c0 = $c;
2145 $c .= '/' . shift @p;
2146 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
2147 }
2148 return $bat->{$c};
2149}
2150
2151sub A {
44320b9e 2152 my ($self, $m) = @_;
a5e0cedc
EW
2153 my ($dir, $file) = split_path($m->{file_b});
2154 my $pbat = $self->ensure_path($dir);
2155 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2156 undef, -1);
44320b9e 2157 print "\tA\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2158 $self->chg_file($fbat, $m);
2159 $self->close_file($fbat,undef,$self->{pool});
2160}
2161
2162sub C {
44320b9e 2163 my ($self, $m) = @_;
a5e0cedc
EW
2164 my ($dir, $file) = split_path($m->{file_b});
2165 my $pbat = $self->ensure_path($dir);
2166 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2167 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2168 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2169 $self->chg_file($fbat, $m);
2170 $self->close_file($fbat,undef,$self->{pool});
2171}
2172
2173sub delete_entry {
2174 my ($self, $path, $pbat) = @_;
2175 my $rpath = $self->repo_path($path);
2176 my ($dir, $file) = split_path($rpath);
2177 $self->{rm}->{$dir} = 1;
2178 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
2179}
2180
2181sub R {
44320b9e 2182 my ($self, $m) = @_;
a5e0cedc
EW
2183 my ($dir, $file) = split_path($m->{file_b});
2184 my $pbat = $self->ensure_path($dir);
2185 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
2186 $self->url_path($m->{file_a}), $self->{r});
44320b9e 2187 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2188 $self->chg_file($fbat, $m);
2189 $self->close_file($fbat,undef,$self->{pool});
2190
2191 ($dir, $file) = split_path($m->{file_a});
2192 $pbat = $self->ensure_path($dir);
2193 $self->delete_entry($m->{file_a}, $pbat);
2194}
2195
2196sub M {
44320b9e 2197 my ($self, $m) = @_;
a5e0cedc
EW
2198 my ($dir, $file) = split_path($m->{file_b});
2199 my $pbat = $self->ensure_path($dir);
2200 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
2201 $pbat,$self->{r},$self->{pool});
44320b9e 2202 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2203 $self->chg_file($fbat, $m);
2204 $self->close_file($fbat,undef,$self->{pool});
2205}
2206
2207sub T { shift->M(@_) }
2208
2209sub change_file_prop {
2210 my ($self, $fbat, $pname, $pval) = @_;
2211 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
2212}
2213
2214sub chg_file {
2215 my ($self, $fbat, $m) = @_;
2216 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
2217 $self->change_file_prop($fbat,'svn:executable','*');
2218 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
2219 $self->change_file_prop($fbat,'svn:executable',undef);
2220 }
2221 my $fh = IO::File->new_tmpfile or croak $!;
2222 if ($m->{mode_b} =~ /^120/) {
2223 print $fh 'link ' or croak $!;
2224 $self->change_file_prop($fbat,'svn:special','*');
2225 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
2226 $self->change_file_prop($fbat,'svn:special',undef);
2227 }
2228 defined(my $pid = fork) or croak $!;
2229 if (!$pid) {
2230 open STDOUT, '>&', $fh or croak $!;
2231 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
2232 }
2233 waitpid $pid, 0;
2234 croak $? if $?;
2235 $fh->flush == 0 or croak $!;
2236 seek $fh, 0, 0 or croak $!;
2237
2238 my $md5 = Digest::MD5->new;
2239 $md5->addfile($fh) or croak $!;
2240 seek $fh, 0, 0 or croak $!;
2241
2242 my $exp = $md5->hexdigest;
f7197dff
EW
2243 my $pool = SVN::Pool->new;
2244 my $atd = $self->apply_textdelta($fbat, undef, $pool);
2245 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
a5e0cedc 2246 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
f7197dff 2247 $pool->clear;
a5e0cedc
EW
2248
2249 close $fh or croak $!;
2250}
2251
2252sub D {
44320b9e 2253 my ($self, $m) = @_;
a5e0cedc
EW
2254 my ($dir, $file) = split_path($m->{file_b});
2255 my $pbat = $self->ensure_path($dir);
44320b9e 2256 print "\tD\t$m->{file_b}\n" unless $::_q;
a5e0cedc
EW
2257 $self->delete_entry($m->{file_b}, $pbat);
2258}
2259
2260sub close_edit {
2261 my ($self) = @_;
2262 my ($p,$bat) = ($self->{pool}, $self->{bat});
2263 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
2264 $self->close_directory($bat->{$_}, $p);
2265 }
2266 $self->SUPER::close_edit($p);
2267 $p->clear;
2268}
2269
2270sub abort_edit {
2271 my ($self) = @_;
2272 $self->SUPER::abort_edit($self->{pool});
61395354
EW
2273}
2274
2275sub DESTROY {
2276 my $self = shift;
2277 $self->SUPER::DESTROY(@_);
a5e0cedc
EW
2278 $self->{pool}->clear;
2279}
2280
44320b9e
EW
2281# this drives the editor
2282sub apply_diff {
61395354
EW
2283 my ($self) = @_;
2284 my $mods = $self->{mods};
44320b9e 2285 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
6e8548cc 2286 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
44320b9e
EW
2287 my $f = $m->{chg};
2288 if (defined $o{$f}) {
2289 $self->$f($m);
2290 } else {
2291 fatal("Invalid change type: $f\n");
2292 }
2293 }
24e22aa8 2294 $self->rmdirs if $_rmdir;
6e8548cc 2295 if (@$mods == 0) {
44320b9e
EW
2296 $self->abort_edit;
2297 } else {
2298 $self->close_edit;
2299 }
6e8548cc 2300 return scalar @$mods;
44320b9e
EW
2301}
2302
d81bf827
EW
2303package Git::SVN::Ra;
2304use vars qw/@ISA $config_dir/;
2305use strict;
2306use warnings;
2307my ($can_do_switch);
5d3b7cd5 2308my $RA;
d81bf827
EW
2309
2310BEGIN {
2311 # enforce temporary pool usage for some simple functions
2312 my $e;
74a81227 2313 foreach (qw/get_latest_revnum get_uuid get_repos_root/) {
d81bf827
EW
2314 $e .= "sub $_ {
2315 my \$self = shift;
2316 my \$pool = SVN::Pool->new;
2317 my \@ret = \$self->SUPER::$_(\@_,\$pool);
2318 \$pool->clear;
2319 wantarray ? \@ret : \$ret[0]; }\n";
2320 }
74a81227
EW
2321
2322 # get_dir needs $pool held in cache for dirents to work,
2323 # check_path is cacheable and rev_proplist is close enough
2324 # for our purposes.
2325 foreach (qw/check_path get_dir rev_proplist/) {
2326 $e .= "my \%${_}_cache; my \$${_}_rev = 0; sub $_ {
2327 my \$self = shift;
2328 my \$r = pop;
2329 my \$k = join(\"\\0\", \@_);
2330 if (my \$x = \$${_}_cache{\$r}->{\$k}) {
2331 return wantarray ? \@\$x : \$x->[0];
2332 }
2333 my \$pool = SVN::Pool->new;
2334 my \@ret = \$self->SUPER::$_(\@_, \$r, \$pool);
2335 if (\$r != \$${_}_rev) {
2336 \%${_}_cache = ( pool => [] );
2337 \$${_}_rev = \$r;
2338 }
2339 \$${_}_cache{\$r}->{\$k} = \\\@ret;
2340 push \@{\$${_}_cache{pool}}, \$pool;
2341 wantarray ? \@ret : \$ret[0]; }\n";
2342 }
2343 $e .= "\n1;";
2344 eval $e or die $@;
d81bf827
EW
2345}
2346
2347sub new {
2348 my ($class, $url) = @_;
f6f09876 2349 $url =~ s!/+$!!;
5d3b7cd5 2350 return $RA if ($RA && $RA->{url} eq $url);
f6f09876 2351
d81bf827
EW
2352 SVN::_Core::svn_config_ensure($config_dir, undef);
2353 my ($baton, $callbacks) = SVN::Core::auth_open_helper([
2354 SVN::Client::get_simple_provider(),
2355 SVN::Client::get_ssl_server_trust_file_provider(),
2356 SVN::Client::get_simple_prompt_provider(
2357 \&Git::SVN::Prompt::simple, 2),
2358 SVN::Client::get_ssl_client_cert_prompt_provider(
2359 \&Git::SVN::Prompt::ssl_client_cert, 2),
2360 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
2361 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
2362 SVN::Client::get_username_provider(),
2363 SVN::Client::get_ssl_server_trust_prompt_provider(
2364 \&Git::SVN::Prompt::ssl_server_trust),
2365 SVN::Client::get_username_prompt_provider(
2366 \&Git::SVN::Prompt::username, 2),
2367 ]);
2368 my $config = SVN::Core::config_get_config($config_dir);
2369 my $self = SVN::Ra->new(url => $url, auth => $baton,
2370 config => $config,
2371 pool => SVN::Pool->new,
2372 auth_provider_callbacks => $callbacks);
2373 $self->{svn_path} = $url;
2374 $self->{repos_root} = $self->get_repos_root;
4e9f6cc7 2375 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
5d3b7cd5 2376 $RA = bless $self, $class;
d81bf827
EW
2377}
2378
2379sub DESTROY {
5d3b7cd5 2380 # do not call the real DESTROY since we store ourselves in $RA
d81bf827
EW
2381}
2382
d81bf827
EW
2383sub get_log {
2384 my ($self, @args) = @_;
2385 my $pool = SVN::Pool->new;
d81bf827
EW
2386 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
2387 my $ret = $self->SUPER::get_log(@args, $pool);
2388 $pool->clear;
2389 $ret;
2390}
2391
2392sub get_commit_editor {
44320b9e 2393 my ($self, $log, $cb, $pool) = @_;
d81bf827 2394 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
44320b9e 2395 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
d81bf827
EW
2396}
2397
2398sub uuid {
2399 my ($self) = @_;
2400 $self->{uuid} ||= $self->get_uuid;
2401}
2402
2403sub gs_do_update {
8a603774
EW
2404 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
2405 my $new = ($rev_a == $rev_b);
2406 my $path = $gs->{path};
2407
d81bf827 2408 my $pool = SVN::Pool->new;
8b8fc068 2409 $editor->set_path_strip($path);
2b27f6c8
EW
2410 my (@pc) = split m#/#, $path;
2411 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
8a603774 2412 1, $editor, $pool);
d81bf827 2413 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
2b27f6c8
EW
2414
2415 # Since we can't rely on svn_ra_reparent being available, we'll
2416 # just have to do some magic with set_path to make it so
2417 # we only want a partial path.
2418 my $sp = '';
2419 my $final = join('/', @pc);
2420 while (@pc) {
2421 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
2422 $sp .= '/' if length $sp;
2423 $sp .= shift @pc;
2424 }
2425 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
2426
2b27f6c8
EW
2427 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
2428
d81bf827
EW
2429 $reporter->finish_report($pool);
2430 $pool->clear;
2431 $editor->{git_commit_ok};
2432}
2433
2b27f6c8
EW
2434# this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
2435# svn_ra_reparent didn't work before 1.4)
d81bf827 2436sub gs_do_switch {
8a603774
EW
2437 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
2438 my $path = $gs->{path};
d81bf827 2439 my $pool = SVN::Pool->new;
2b27f6c8
EW
2440
2441 my $full_url = $self->{url};
2442 my $old_url = $full_url;
2443 $full_url .= "/$path" if length $path;
5d3b7cd5
EW
2444 my ($ra, $reparented);
2445 if ($old_url ne $full_url) {
2446 if ($old_url !~ m#^svn(\+ssh)?://#) {
2447 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
2448 $pool);
2449 $self->{url} = $full_url;
2450 $reparented = 1;
2451 } else {
2452 $ra = Git::SVN::Ra->new($full_url);
2453 }
2454 }
2455 $ra ||= $self;
8a603774 2456 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
d81bf827 2457 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
8b8fc068 2458 $reporter->set_path('', $rev_a, 0, @lock, $pool);
d81bf827 2459 $reporter->finish_report($pool);
2b27f6c8 2460
5d3b7cd5
EW
2461 if ($reparented) {
2462 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
2463 $self->{url} = $old_url;
2464 }
2b27f6c8 2465
d81bf827
EW
2466 $pool->clear;
2467 $editor->{git_commit_ok};
2468}
2469
0af9c9f9 2470sub gs_fetch_loop_common {
e518192f
EW
2471 my ($self, $base, $head, $gsv, $globs) = @_;
2472 return if ($base > $head);
0af9c9f9
EW
2473 my $inc = 1000;
2474 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
d2ae1434 2475 my %common;
e518192f
EW
2476 my $common_max = scalar @$gsv;
2477
2478 foreach my $gs (@$gsv) {
0af9c9f9
EW
2479 if (my $last_commit = $gs->last_commit) {
2480 $gs->assert_index_clean($last_commit);
2481 }
d2ae1434
EW
2482 my @tmp = split m#/#, $gs->{path};
2483 my $p = '';
2484 foreach (@tmp) {
2485 $p .= length($p) ? "/$_" : $_;
2486 $common{$p} ||= 0;
2487 $common{$p}++;
2488 }
2489 }
e518192f
EW
2490 $globs ||= [];
2491 $common_max += scalar @$globs;
2492 foreach my $glob (@$globs) {
2493 my @tmp = split m#/#, $glob->{path}->{left};
2494 my $p = '';
2495 foreach (@tmp) {
2496 $p .= length($p) ? "/$_" : $_;
2497 $common{$p} ||= 0;
2498 $common{$p}++;
2499 }
2500 }
2501
d2ae1434
EW
2502 my $longest_path = '';
2503 foreach (sort {length $b <=> length $a} keys %common) {
e518192f 2504 if ($common{$_} == $common_max) {
d2ae1434
EW
2505 $longest_path = $_;
2506 last;
2507 }
0af9c9f9
EW
2508 }
2509 while (1) {
d4eff2bd 2510 my %revs;
d2ae1434 2511 my $err;
f7c3fc4a 2512 my $err_handler = $SVN::Error::handler;
d2ae1434
EW
2513 $SVN::Error::handler = sub {
2514 ($err) = @_;
2515 skip_unknown_revs($err);
2516 };
2517 sub _cb {
2518 my ($paths, $r, $author, $date, $log) = @_;
2519 [ dup_changed_paths($paths),
2520 { author => $author, date => $date, log => $log } ];
2521 }
2522 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
2523 sub { $revs{$_[1]} = _cb(@_) });
2524 if ($err && $max >= $head) {
2525 print STDERR "Path '$longest_path' ",
2526 "was probably deleted:\n",
2527 $err->expanded_message,
2528 "\nWill attempt to follow ",
2529 "revisions r$min .. r$max ",
2530 "committed before the deletion\n";
2531 my $hi = $max;
2532 while (--$hi >= $min) {
2533 my $ok;
2534 $self->get_log([$longest_path], $min, $hi,
2535 0, 1, 1, sub {
2536 $ok ||= $_[1];
2537 $revs{$_[1]} = _cb(@_) });
2538 if ($ok) {
2539 print STDERR "r$min .. r$ok OK\n";
2540 last;
2541 }
2542 }
2543 }
d4eff2bd 2544 $SVN::Error::handler = $err_handler;
fbcc1737 2545
e518192f 2546 my %exists = map { $_->{path} => $_ } @$gsv;
d4eff2bd 2547 foreach my $r (sort {$a <=> $b} keys %revs) {
fbcc1737 2548 my ($paths, $logged) = @{$revs{$r}};
e518192f
EW
2549
2550 foreach my $gs ($self->match_globs(\%exists, $paths,
2551 $globs, $r)) {
fbcc1737
EW
2552 if ($gs->rev_db_max >= $r) {
2553 next;
2554 }
2555 next unless $gs->match_paths($paths, $r);
2556 $gs->{logged_rev_props} = $logged;
2557 my $log_entry = $gs->do_fetch($paths, $r);
2558 if ($log_entry) {
0af9c9f9
EW
2559 $gs->do_git_commit($log_entry);
2560 }
2561 }
e518192f
EW
2562 foreach my $g (@$globs) {
2563 my $f = "$ENV{GIT_DIR}/svn/." .
2564 $self->uuid . ".$g->{t}";
2565 open my $fh, '>', "$f.tmp" or
2566 die "Can't open $f.tmp for writing: $!";
2567 print $fh "$r\n" or
2568 die "Couldn't write to $f: $!\n";
2569 close $fh or die "Error closing $f: $!\n";
2570 rename "$f.tmp", $f or
2571 die "Couldn't rename ",
2572 "$f.tmp => $f: $!\n";
2573 }
0af9c9f9 2574 }
9c93fee5
EW
2575 # pre-fill the .rev_db since it'll eventually get filled in
2576 # with '0' x40 if something new gets committed
e518192f 2577 foreach my $gs (@$gsv) {
9c93fee5
EW
2578 next if defined $gs->rev_db_get($max);
2579 $gs->rev_db_set($max, 0 x40);
2580 }
0af9c9f9
EW
2581 last if $max >= $head;
2582 $min = $max + 1;
2583 $max += $inc;
2584 $max = $head if ($max > $head);
2585 }
0af9c9f9
EW
2586}
2587
e518192f
EW
2588sub match_globs {
2589 my ($self, $exists, $paths, $globs, $r) = @_;
74a81227
EW
2590
2591 sub get_dir_check {
2592 my ($self, $exists, $g, $r) = @_;
2593 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
2594 return unless scalar @x == 3;
2595 my $dirents = $x[0];
2596 foreach my $de (keys %$dirents) {
2597 next if $dirents->{$de}->kind != $SVN::Node::dir;
2598 my $p = $g->{path}->full_path($de);
2599 next if $exists->{$p};
2600 next if (length $g->{path}->{right} &&
2601 ($self->check_path($p, $r) !=
2602 $SVN::Node::dir));
2603 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
2604 $g->{ref}->full_path($de), 1);
2605 }
2606 }
e518192f 2607 foreach my $g (@$globs) {
74a81227
EW
2608 if (my $path = $paths->{"/$g->{path}->{left}"}) {
2609 if ($path->{action} =~ /^[AR]$/) {
2610 get_dir_check($self, $exists, $g, $r);
2611 }
2612 }
e518192f 2613 foreach (keys %$paths) {
74a81227
EW
2614 if (/$g->{path}->{left_regex}/) {
2615 next if $paths->{$_}->{action} !~ /^[AR]$/;
2616 get_dir_check($self, $exists, $g, $r);
2617 }
e518192f
EW
2618 next unless /$g->{path}->{regex}/;
2619 my $p = $1;
2620 my $pathname = $g->{path}->full_path($p);
2621 next if $exists->{$pathname};
2622 $exists->{$pathname} = Git::SVN->init(
2623 $self->{url}, $pathname, undef,
2624 $g->{ref}->full_path($p), 1);
2625 }
2626 my $c = '';
2627 foreach (split m#/#, $g->{path}->{left}) {
2628 $c .= "/$_";
2629 next unless ($paths->{$c} &&
74a81227
EW
2630 ($paths->{$c}->{action} =~ /^[AR]$/));
2631 get_dir_check($self, $exists, $g, $r);
e518192f
EW
2632 }
2633 }
2634 values %$exists;
2635}
2636
e6434f87
EW
2637sub minimize_url {
2638 my ($self) = @_;
2639 return $self->{url} if ($self->{url} eq $self->{repos_root});
2640 my $url = $self->{repos_root};
2641 my @components = split(m!/!, $self->{svn_path});
2642 my $c = '';
2643 do {
2644 $url .= "/$c" if length $c;
2645 eval { (ref $self)->new($url)->get_latest_revnum };
2646 } while ($@ && ($c = shift @components));
2647 $url;
2648}
2649
d81bf827
EW
2650sub can_do_switch {
2651 my $self = shift;
2652 unless (defined $can_do_switch) {
2653 my $pool = SVN::Pool->new;
2654 my $rep = eval {
2655 $self->do_switch(1, '', 0, $self->{url},
2656 SVN::Delta::Editor->new, $pool);
2657 };
2658 if ($@) {
2659 $can_do_switch = 0;
2660 } else {
2661 $rep->abort_report($pool);
2662 $can_do_switch = 1;
2663 }
2664 $pool->clear;
2665 }
2666 $can_do_switch;
2667}
2668
0af9c9f9
EW
2669sub skip_unknown_revs {
2670 my ($err) = @_;
2671 my $errno = $err->apr_err();
2672 # Maybe the branch we're tracking didn't
2673 # exist when the repo started, so it's
2674 # not an error if it doesn't, just continue
2675 #
2676 # Wonderfully consistent library, eh?
2677 # 160013 - svn:// and file://
2678 # 175002 - http(s)://
2679 # 175007 - http(s):// (this repo required authorization, too...)
2680 # More codes may be discovered later...
2681 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
2682 return;
2683 }
2684 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
2685}
2686
2687# svn_log_changed_path_t objects passed to get_log are likely to be
2688# overwritten even if only the refs are copied to an external variable,
2689# so we should dup the structures in their entirety. Using an externally
2690# passed pool (instead of our temporary and quickly cleared pool in
2691# Git::SVN::Ra) does not help matters at all...
2692sub dup_changed_paths {
2693 my ($paths) = @_;
2694 return undef unless $paths;
2695 my %ret;
2696 foreach my $p (keys %$paths) {
2697 my $i = $paths->{$p};
2698 my %s = map { $_ => $i->$_ }
2699 qw/copyfrom_path copyfrom_rev action/;
2700 $ret{$p} = \%s;
2701 }
2702 \%ret;
2703}
2704
f8c9d1d2
EW
2705package Git::SVN::Log;
2706use strict;
2707use warnings;
2708use POSIX qw/strftime/;
2709use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
2710 %rusers $show_commit $incremental/;
2711my $l_fmt;
2712
2713sub cmt_showable {
2714 my ($c) = @_;
2715 return 1 if defined $c->{r};
2716 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
2717 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
44320b9e
EW
2718 my @log = command(qw/cat-file commit/, $c->{c});
2719 shift @log while ($log[0] ne "\n");
2720 shift @log;
2721 @{$c->{l}} = grep !/^git-svn-id: /, @log;
f8c9d1d2
EW
2722
2723 (undef, $c->{r}, undef) = ::extract_metadata(
44320b9e 2724 (grep(/^git-svn-id: /, @log))[-1]);
f8c9d1d2
EW
2725 }
2726 return defined $c->{r};
2727}
2728
2729sub log_use_color {
2730 return 1 if $color;
2731 my ($dc, $dcvar);
2732 $dcvar = 'color.diff';
2733 $dc = `git-config --get $dcvar`;
2734 if ($dc eq '') {
2735 # nothing at all; fallback to "diff.color"
2736 $dcvar = 'diff.color';
2737 $dc = `git-config --get $dcvar`;
2738 }
2739 chomp($dc);
2740 if ($dc eq 'auto') {
2741 my $pc;
2742 $pc = `git-config --get color.pager`;
2743 if ($pc eq '') {
2744 # does not have it -- fallback to pager.color
2745 $pc = `git-config --bool --get pager.color`;
2746 }
2747 else {
2748 $pc = `git-config --bool --get color.pager`;
2749 if ($?) {
2750 $pc = 'false';
2751 }
2752 }
2753 chomp($pc);
2754 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
2755 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
2756 }
2757 return 0;
2758 }
2759 return 0 if $dc eq 'never';
2760 return 1 if $dc eq 'always';
2761 chomp($dc = `git-config --bool --get $dcvar`);
2762 return ($dc eq 'true');
2763}
2764
2765sub git_svn_log_cmd {
2766 my ($r_min, $r_max) = @_;
2767 my $gs = Git::SVN->_new;
2768 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
2769 $gs->refname);
2770 push @cmd, '-r' unless $non_recursive;
2771 push @cmd, qw/--raw --name-status/ if $verbose;
2772 push @cmd, '--color' if log_use_color();
2773 return @cmd unless defined $r_max;
2774 if ($r_max == $r_min) {
2775 push @cmd, '--max-count=1';
2776 if (my $c = $gs->rev_db_get($r_max)) {
2777 push @cmd, $c;
2778 }
2779 } else {
2780 my ($c_min, $c_max);
2781 $c_max = $gs->rev_db_get($r_max);
2782 $c_min = $gs->rev_db_get($r_min);
2783 if (defined $c_min && defined $c_max) {
2784 if ($r_max > $r_max) {
2785 push @cmd, "$c_min..$c_max";
2786 } else {
2787 push @cmd, "$c_max..$c_min";
2788 }
2789 } elsif ($r_max > $r_min) {
2790 push @cmd, $c_max;
2791 } else {
2792 push @cmd, $c_min;
2793 }
2794 }
2795 return @cmd;
2796}
2797
2798# adapted from pager.c
2799sub config_pager {
2800 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
2801 if (!defined $pager) {
2802 $pager = 'less';
2803 } elsif (length $pager == 0 || $pager eq 'cat') {
2804 $pager = undef;
2805 }
2806}
2807
2808sub run_pager {
2809 return unless -t *STDOUT;
2810 pipe my $rfd, my $wfd or return;
2811 defined(my $pid = fork) or ::fatal "Can't fork: $!\n";
2812 if (!$pid) {
2813 open STDOUT, '>&', $wfd or
2814 ::fatal "Can't redirect to stdout: $!\n";
2815 return;
2816 }
2817 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!\n";
2818 $ENV{LESS} ||= 'FRSX';
2819 exec $pager or ::fatal "Can't run pager: $! ($pager)\n";
2820}
2821
21819a37
EW
2822sub tz_to_s_offset {
2823 my ($tz) = @_;
2824 $tz =~ s/(\d\d)$//;
2825 return ($1 * 60) + ($tz * 3600);
2826}
2827
f8c9d1d2
EW
2828sub get_author_info {
2829 my ($dest, $author, $t, $tz) = @_;
2830 $author =~ s/(?:^\s*|\s*$)//g;
2831 $dest->{a_raw} = $author;
2832 my $au;
1c8443b0 2833 if ($::_authors) {
f8c9d1d2
EW
2834 $au = $rusers{$author} || undef;
2835 }
2836 if (!$au) {
2837 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
2838 }
2839 $dest->{t} = $t;
2840 $dest->{tz} = $tz;
2841 $dest->{a} = $au;
2842 # Date::Parse isn't in the standard Perl distro :(
2843 if ($tz =~ s/^\+//) {
21819a37 2844 $t += tz_to_s_offset($tz);
f8c9d1d2 2845 } elsif ($tz =~ s/^\-//) {
21819a37 2846 $t -= tz_to_s_offset($tz);
f8c9d1d2
EW
2847 }
2848 $dest->{t_utc} = $t;
2849}
2850
2851sub process_commit {
2852 my ($c, $r_min, $r_max, $defer) = @_;
2853 if (defined $r_min && defined $r_max) {
2854 if ($r_min == $c->{r} && $r_min == $r_max) {
2855 show_commit($c);
2856 return 0;
2857 }
2858 return 1 if $r_min == $r_max;
2859 if ($r_min < $r_max) {
2860 # we need to reverse the print order
2861 return 0 if (defined $limit && --$limit < 0);
2862 push @$defer, $c;
2863 return 1;
2864 }
2865 if ($r_min != $r_max) {
2866 return 1 if ($r_min < $c->{r});
2867 return 1 if ($r_max > $c->{r});
2868 }
2869 }
2870 return 0 if (defined $limit && --$limit < 0);
2871 show_commit($c);
2872 return 1;
2873}
2874
2875sub show_commit {
2876 my $c = shift;
2877 if ($oneline) {
2878 my $x = "\n";
2879 if (my $l = $c->{l}) {
2880 while ($l->[0] =~ /^\s*$/) { shift @$l }
2881 $x = $l->[0];
2882 }
2883 $l_fmt ||= 'A' . length($c->{r});
2884 print 'r',pack($l_fmt, $c->{r}),' | ';
2885 print "$c->{c} | " if $show_commit;
2886 print $x;
2887 } else {
2888 show_commit_normal($c);
2889 }
2890}
2891
2892sub show_commit_changed_paths {
2893 my ($c) = @_;
2894 return unless $c->{changed};
2895 print "Changed paths:\n", @{$c->{changed}};
2896}
2897
2898sub show_commit_normal {
2899 my ($c) = @_;
2900 print '-' x72, "\nr$c->{r} | ";
2901 print "$c->{c} | " if $show_commit;
2902 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
2903 localtime($c->{t_utc})), ' | ';
2904 my $nr_line = 0;
2905
2906 if (my $l = $c->{l}) {
2907 while ($l->[$#$l] eq "\n" && $#$l > 0
2908 && $l->[($#$l - 1)] eq "\n") {
2909 pop @$l;
2910 }
2911 $nr_line = scalar @$l;
2912 if (!$nr_line) {
2913 print "1 line\n\n\n";
2914 } else {
2915 if ($nr_line == 1) {
2916 $nr_line = '1 line';
2917 } else {
2918 $nr_line .= ' lines';
2919 }
2920 print $nr_line, "\n";
2921 show_commit_changed_paths($c);
2922 print "\n";
2923 print $_ foreach @$l;
2924 }
2925 } else {
2926 print "1 line\n";
2927 show_commit_changed_paths($c);
2928 print "\n";
2929
2930 }
2931 foreach my $x (qw/raw diff/) {
2932 if ($c->{$x}) {
2933 print "\n";
2934 print $_ foreach @{$c->{$x}}
2935 }
2936 }
2937}
2938
2939sub cmd_show_log {
2940 my (@args) = @_;
2941 my ($r_min, $r_max);
2942 my $r_last = -1; # prevent dupes
2943 if (defined $TZ) {
2944 $ENV{TZ} = $TZ;
2945 } else {
2946 delete $ENV{TZ};
2947 }
2948 if (defined $::_revision) {
2949 if ($::_revision =~ /^(\d+):(\d+)$/) {
2950 ($r_min, $r_max) = ($1, $2);
2951 } elsif ($::_revision =~ /^\d+$/) {
2952 $r_min = $r_max = $::_revision;
2953 } else {
2954 ::fatal "-r$::_revision is not supported, use ",
2955 "standard \'git log\' arguments instead\n";
2956 }
2957 }
2958
2959 config_pager();
2960 @args = (git_svn_log_cmd($r_min, $r_max), @args);
2961 my $log = command_output_pipe(@args);
2962 run_pager();
2963 my (@k, $c, $d);
2964 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
2965 while (<$log>) {
2966 if (/^${esc_color}commit ($::sha1_short)/o) {
2967 my $cmt = $1;
2968 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
2969 $r_last = $c->{r};
2970 process_commit($c, $r_min, $r_max, \@k) or
2971 goto out;
2972 }
2973 $d = undef;
2974 $c = { c => $cmt };
2975 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
2976 get_author_info($c, $1, $2, $3);
2977 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
2978 # ignore
2979 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
2980 push @{$c->{raw}}, $_;
2981 } elsif (/^${esc_color}[ACRMDT]\t/) {
2982 # we could add $SVN->{svn_path} here, but that requires
2983 # remote access at the moment (repo_path_split)...
2984 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
2985 push @{$c->{changed}}, $_;
2986 } elsif (/^${esc_color}diff /o) {
2987 $d = 1;
2988 push @{$c->{diff}}, $_;
2989 } elsif ($d) {
2990 push @{$c->{diff}}, $_;
2991 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
2992 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
2993 } elsif (s/^${esc_color} //o) {
2994 push @{$c->{l}}, $_;
2995 }
2996 }
2997 if ($c && defined $c->{r} && $c->{r} != $r_last) {
2998 $r_last = $c->{r};
2999 process_commit($c, $r_min, $r_max, \@k);
3000 }
3001 if (@k) {
3002 my $swap = $r_max;
3003 $r_max = $r_min;
3004 $r_min = $swap;
3005 process_commit($_, $r_min, $r_max) foreach reverse @k;
3006 }
3007out:
c843c464 3008 close $log;
f8c9d1d2
EW
3009 print '-' x72,"\n" unless $incremental || $oneline;
3010}
3011
706587fc
EW
3012package Git::SVN::Migration;
3013# these version numbers do NOT correspond to actual version numbers
3014# of git nor git-svn. They are just relative.
3015#
3016# v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
3017#
3018# v1 layout: .git/$id/info/url, refs/remotes/$id
3019#
3020# v2 layout: .git/svn/$id/info/url, refs/remotes/$id
3021#
3022# v3 layout: .git/svn/$id, refs/remotes/$id
3023# - info/url may remain for backwards compatibility
3024# - this is what we migrate up to this layout automatically,
3025# - this will be used by git svn init on single branches
3026#
3027# v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
3028# - this is only created for newly multi-init-ed
3029# repositories. Similar in spirit to the
3030# --use-separate-remotes option in git-clone (now default)
3031# - we do not automatically migrate to this (following
3032# the example set by core git)
3033use strict;
3034use warnings;
3035use Carp qw/croak/;
3036use File::Path qw/mkpath/;
47e39c55
EW
3037use File::Basename qw/dirname basename/;
3038use vars qw/$_minimize/;
706587fc
EW
3039
3040sub migrate_from_v0 {
3041 my $git_dir = $ENV{GIT_DIR};
3042 return undef unless -d $git_dir;
3043 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3044 my $migrated = 0;
3045 while (<$fh>) {
3046 chomp;
3047 my ($id, $orig_ref) = ($_, $_);
3048 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
3049 next unless -f "$git_dir/$id/info/url";
3050 my $new_ref = "refs/remotes/$id";
3051 if (::verify_ref("$new_ref^0")) {
3052 print STDERR "W: $orig_ref is probably an old ",
3053 "branch used by an ancient version of ",
3054 "git-svn.\n",
3055 "However, $new_ref also exists.\n",
3056 "We will not be able ",
3057 "to use this branch until this ",
3058 "ambiguity is resolved.\n";
3059 next;
3060 }
3061 print STDERR "Migrating from v0 layout...\n" if !$migrated;
3062 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
3063 command_noisy('update-ref', $new_ref, $orig_ref);
3064 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
3065 $migrated++;
3066 }
3067 command_close_pipe($fh, $ctx);
3068 print STDERR "Done migrating from v0 layout...\n" if $migrated;
3069 $migrated;
3070}
3071
3072sub migrate_from_v1 {
3073 my $git_dir = $ENV{GIT_DIR};
3074 my $migrated = 0;
3075 return $migrated unless -d $git_dir;
3076 my $svn_dir = "$git_dir/svn";
3077
3078 # just in case somebody used 'svn' as their $id at some point...
3079 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
3080
3081 print STDERR "Migrating from a git-svn v1 layout...\n";
3082 mkpath([$svn_dir]);
3083 print STDERR "Data from a previous version of git-svn exists, but\n\t",
3084 "$svn_dir\n\t(required for this version ",
3085 "($::VERSION) of git-svn) does not. exist\n";
3086 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
3087 while (<$fh>) {
3088 my $x = $_;
3089 next unless $x =~ s#^refs/remotes/##;
3090 chomp $x;
3091 next unless -f "$git_dir/$x/info/url";
3092 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
3093 next unless $u;
3094 my $dn = dirname("$git_dir/svn/$x");
3095 mkpath([$dn]) unless -d $dn;
3096 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
3097 mkpath(["$git_dir/svn/svn"]);
3098 print STDERR " - $git_dir/$x/info => ",
3099 "$git_dir/svn/$x/info\n";
3100 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
3101 croak "$!: $x";
3102 # don't worry too much about these, they probably
3103 # don't exist with repos this old (save for index,
3104 # and we can easily regenerate that)
3105 foreach my $f (qw/unhandled.log index .rev_db/) {
3106 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
3107 }
3108 } else {
3109 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
3110 rename "$git_dir/$x", "$git_dir/svn/$x" or
3111 croak "$!: $x";
3112 }
3113 $migrated++;
3114 }
3115 command_close_pipe($fh, $ctx);
3116 print STDERR "Done migrating from a git-svn v1 layout\n";
3117 $migrated;
3118}
3119
3120sub read_old_urls {
3121 my ($l_map, $pfx, $path) = @_;
3122 my @dir;
3123 foreach (<$path/*>) {
3124 if (-r "$_/info/url") {
3125 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
3126 my $ref_id = $pfx . basename $_;
3127 my $url = ::file_to_s("$_/info/url");
3128 $l_map->{$ref_id} = $url;
3129 } elsif (-d $_) {
3130 push @dir, $_;
3131 }
3132 }
3133 foreach (@dir) {
3134 my $x = $_;
3135 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
3136 read_old_urls($l_map, $x, $_);
3137 }
3138}
3139
3140sub migrate_from_v2 {
3141 my @cfg = command(qw/config -l/);
3142 return if grep /^svn-remote\..+\.url=/, @cfg;
3143 my %l_map;
3144 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
3145 my $migrated = 0;
3146
3147 foreach my $ref_id (sort keys %l_map) {
471bc000
EW
3148 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
3149 if ($@) {
3150 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
3151 }
706587fc
EW
3152 $migrated++;
3153 }
3154 $migrated;
3155}
3156
47e39c55
EW
3157sub minimize_connections {
3158 my $r = Git::SVN::read_all_remotes();
3159 my $new_urls = {};
3160 my $root_repos = {};
3161 foreach my $repo_id (keys %$r) {
3162 my $url = $r->{$repo_id}->{url} or next;
3163 my $fetch = $r->{$repo_id}->{fetch} or next;
3164 my $ra = Git::SVN::Ra->new($url);
3165
3166 # skip existing cases where we already connect to the root
3167 if (($ra->{url} eq $ra->{repos_root}) ||
3168 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
3169 $repo_id)) {
3170 $root_repos->{$ra->{url}} = $repo_id;
3171 next;
3172 }
3173
3174 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
3175 my $root_path = $ra->{url};
4e9f6cc7 3176 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
47e39c55
EW
3177 foreach my $path (keys %$fetch) {
3178 my $ref_id = $fetch->{$path};
3179 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
3180
3181 # make sure we can read when connecting to
3182 # a higher level of a repository
3183 my ($last_rev, undef) = $gs->last_rev_commit;
3184 if (!defined $last_rev) {
3185 $last_rev = eval {
3186 $root_ra->get_latest_revnum;
3187 };
3188 next if $@;
3189 }
3190 my $new = $root_path;
3191 $new .= length $path ? "/$path" : '';
3192 eval {
3193 $root_ra->get_log([$new], $last_rev, $last_rev,
3194 0, 0, 1, sub { });
3195 };
3196 next if $@;
3197 $new_urls->{$ra->{repos_root}}->{$new} =
3198 { ref_id => $ref_id,
3199 old_repo_id => $repo_id,
3200 old_path => $path };
3201 }
3202 }
3203
3204 my @emptied;
3205 foreach my $url (keys %$new_urls) {
3206 # see if we can re-use an existing [svn-remote "repo_id"]
3207 # instead of creating a(n ugly) new section:
3208 my $repo_id = $root_repos->{$url} ||
3209 Git::SVN::sanitize_remote_name($url);
3210
3211 my $fetch = $new_urls->{$url};
3212 foreach my $path (keys %$fetch) {
3213 my $x = $fetch->{$path};
3214 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
3215 my $pfx = "svn-remote.$x->{old_repo_id}";
3216
3217 my $old_fetch = quotemeta("$x->{old_path}:".
3218 "refs/remotes/$x->{ref_id}");
8b8fc068 3219 command_noisy(qw/config --unset/,
47e39c55
EW
3220 "$pfx.fetch", '^'. $old_fetch . '$');
3221 delete $r->{$x->{old_repo_id}}->
3222 {fetch}->{$x->{old_path}};
3223 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
8b8fc068 3224 command_noisy(qw/config --unset/,
47e39c55
EW
3225 "$pfx.url");
3226 push @emptied, $x->{old_repo_id}
3227 }
3228 }
3229 }
3230 if (@emptied) {
3231 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
3232 "$ENV{GIT_DIR}/config";
3233 print STDERR <<EOF;
3234The following [svn-remote] sections in your config file ($file) are empty
3235and can be safely removed:
3236EOF
3237 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
3238 }
3239}
3240
706587fc
EW
3241sub migration_check {
3242 migrate_from_v0();
3243 migrate_from_v1();
3244 migrate_from_v2();
47e39c55 3245 minimize_connections() if $_minimize;
706587fc
EW
3246}
3247
ef3cfaad
EW
3248package Git::IndexInfo;
3249use strict;
3250use warnings;
3251use Git qw/command_input_pipe command_close_pipe/;
3252
3253sub new {
3254 my ($class) = @_;
3255 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
3256 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
3257}
3258
3259sub remove {
3260 my ($self, $path) = @_;
3261 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
3262 return ++$self->{nr};
3263 }
3264 undef;
3265}
3266
3267sub update {
3268 my ($self, $mode, $hash, $path) = @_;
3269 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
3270 return ++$self->{nr};
3271 }
3272 undef;
3273}
3274
3275sub DESTROY {
3276 my ($self) = @_;
3277 command_close_pipe($self->{gui}, $self->{ctx});
3278}
3279
4bb9ed04
EW
3280package Git::SVN::GlobSpec;
3281use strict;
3282use warnings;
3283
3284sub new {
3285 my ($class, $glob) = @_;
4bb9ed04
EW
3286 my $re = $glob;
3287 $re =~ s!/+$!!g; # no need for trailing slashes
4e9f6cc7 3288 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4bb9ed04
EW
3289 my ($left, $right) = ($1, $2);
3290 if ($nr > 1) {
e518192f
EW
3291 die "Only one '*' wildcard expansion ",
3292 "is supported (got $nr): '$glob'\n";
4bb9ed04 3293 } elsif ($nr == 0) {
e518192f 3294 die "One '*' is needed for glob: '$glob'\n";
4bb9ed04
EW
3295 }
3296 $re = quotemeta($left) . $re . quotemeta($right);
4e9f6cc7
EW
3297 if (length $left && !($left =~ s!/+$!!g)) {
3298 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
3299 }
3300 if (length $right && !($right =~ s!^/+!!g)) {
3301 die "Missing leading '/' on right side of: '$glob' ($right)\n";
3302 }
74a81227
EW
3303 my $left_re = qr/^\/\Q$left\E(\/|$)/;
3304 bless { left => $left, right => $right, left_regex => $left_re,
4bb9ed04
EW
3305 regex => qr/$re/, glob => $glob }, $class;
3306}
3307
3308sub full_path {
3309 my ($self, $path) = @_;
3310 return (length $self->{left} ? "$self->{left}/" : '') .
3311 $path . (length $self->{right} ? "/$self->{right}" : '');
3312}
3313
3397f9df
EW
3314__END__
3315
3316Data structures:
3317
4bb9ed04
EW
3318
3319$remotes = { # returned by read_all_remotes()
3320 'svn' => {
3321 # svn-remote.svn.url=https://svn.musicpd.org
3322 url => 'https://svn.musicpd.org',
3323 # svn-remote.svn.fetch=mpd/trunk:trunk
3324 fetch => {
3325 'mpd/trunk' => 'trunk',
3326 },
3327 # svn-remote.svn.tags=mpd/tags/*:tags/*
3328 tags => {
3329 path => {
3330 left => 'mpd/tags',
3331 right => '',
3332 regex => qr!mpd/tags/([^/]+)$!,
3333 glob => 'tags/*',
3334 },
3335 ref => {
3336 left => 'tags',
3337 right => '',
3338 regex => qr!tags/([^/]+)$!,
3339 glob => 'tags/*',
3340 },
3341 }
3342 }
3343};
3344
44320b9e 3345$log_entry hashref as returned by libsvn_log_entry()
3397f9df 3346{
44320b9e 3347 log => 'whitespace-formatted log entry
3397f9df
EW
3348', # trailing newline is preserved
3349 revision => '8', # integer
3350 date => '2004-02-24T17:01:44.108345Z', # commit date
3351 author => 'committer name'
3352};
3353
6e8548cc
EW
3354
3355# this is generated by generate_diff();
3397f9df
EW
3356@mods = array of diff-index line hashes, each element represents one line
3357 of diff-index output
3358
3359diff-index line ($m hash)
3360{
3361 mode_a => first column of diff-index output, no leading ':',
3362 mode_b => second column of diff-index output,
3363 sha1_b => sha1sum of the final blob,
ac8e0b91 3364 chg => change type [MCRADT],
3397f9df
EW
3365 file_a => original file name of a file (iff chg is 'C' or 'R')
3366 file_b => new/current file name of a file (any chg)
3367}
3368;
a5e0cedc 3369
a00439ac
EW
3370# retval of read_url_paths{,_all}();
3371$l_map = {
3372 # repository root url
3373 'https://svn.musicpd.org' => {
3374 # repository path # GIT_SVN_ID
3375 'mpd/trunk' => 'trunk',
3376 'mpd/tags/0.11.5' => 'tags/0.11.5',
3377 },
3378}
3379
a5e0cedc
EW
3380Notes:
3381 I don't trust the each() function on unless I created %hash myself
3382 because the internal iterator may not have started at base.