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