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