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