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