git-svn: extract reusable code into utility functions
[git/jrn.git] / git-svn.perl
blob98c980fa8fc97b3811f8edba2c67ea3a8e174631
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@@';
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 } || '';
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;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
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)";
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;
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 Git::SVN::Util),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_verbose);
69 $Git::SVN::_follow_parent = 1;
70 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
71 'config-dir=s' => \$Git::SVN::Ra::config_dir,
72 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
73 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
74 'authors-file|A=s' => \$_authors,
75 'repack:i' => \$Git::SVN::_repack,
76 'noMetadata' => \$Git::SVN::_no_metadata,
77 'useSvmProps' => \$Git::SVN::_use_svm_props,
78 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
79 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
80 'no-checkout' => \$_no_checkout,
81 'quiet|q' => \$_q,
82 'repack-flags|repack-args|repack-opts=s' =>
83 \$Git::SVN::_repack_flags,
84 %remote_opts );
86 my ($_trunk, $_tags, $_branches, $_stdlayout);
87 my %icv;
88 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
89 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
90 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
91 'stdlayout|s' => \$_stdlayout,
92 'minimize-url|m' => \$Git::SVN::_minimize_url,
93 'no-metadata' => sub { $icv{noMetadata} = 1 },
94 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
95 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
96 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
97 %remote_opts );
98 my %cmt_opts = ( 'edit|e' => \$_edit,
99 'rmdir' => \$SVN::Git::Editor::_rmdir,
100 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
101 'l=i' => \$SVN::Git::Editor::_rename_limit,
102 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
105 my %cmd = (
106 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
107 { 'revision|r=s' => \$_revision,
108 'fetch-all|all' => \$_fetch_all,
109 %fc_opts } ],
110 clone => [ \&cmd_clone, "Initialize and fetch revisions",
111 { 'revision|r=s' => \$_revision,
112 %fc_opts, %init_opts } ],
113 init => [ \&cmd_init, "Initialize a repo for tracking" .
114 " (requires URL argument)",
115 \%init_opts ],
116 'multi-init' => [ \&cmd_multi_init,
117 "Deprecated alias for ".
118 "'$0 init -T<trunk> -b<branches> -t<tags>'",
119 \%init_opts ],
120 dcommit => [ \&cmd_dcommit,
121 'Commit several diffs to merge with upstream',
122 { 'merge|m|M' => \$_merge,
123 'strategy|s=s' => \$_strategy,
124 'verbose|v' => \$_verbose,
125 'dry-run|n' => \$_dry_run,
126 'fetch-all|all' => \$_fetch_all,
127 'no-rebase' => \$_no_rebase,
128 %cmt_opts, %fc_opts } ],
129 'set-tree' => [ \&cmd_set_tree,
130 "Set an SVN repository to a git tree-ish",
131 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
132 'create-ignore' => [ \&cmd_create_ignore,
133 'Create a .gitignore per svn:ignore',
134 { 'revision|r=i' => \$_revision
135 } ],
136 'propget' => [ \&cmd_propget,
137 'Print the value of a property on a file or directory',
138 { 'revision|r=i' => \$_revision } ],
139 'proplist' => [ \&cmd_proplist,
140 'List all properties of a file or directory',
141 { 'revision|r=i' => \$_revision } ],
142 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
143 { 'revision|r=i' => \$_revision
144 } ],
145 'multi-fetch' => [ \&cmd_multi_fetch,
146 "Deprecated alias for $0 fetch --all",
147 { 'revision|r=s' => \$_revision, %fc_opts } ],
148 'migrate' => [ sub { },
149 # no-op, we automatically run this anyways,
150 'Migrate configuration/metadata/layout from
151 previous versions of git-svn',
152 { 'minimize' => \$Git::SVN::Migration::_minimize,
153 %remote_opts } ],
154 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
155 { 'limit=i' => \$Git::SVN::Log::limit,
156 'revision|r=s' => \$_revision,
157 'verbose|v' => \$Git::SVN::Log::verbose,
158 'incremental' => \$Git::SVN::Log::incremental,
159 'oneline' => \$Git::SVN::Log::oneline,
160 'show-commit' => \$Git::SVN::Log::show_commit,
161 'non-recursive' => \$Git::SVN::Log::non_recursive,
162 'authors-file|A=s' => \$_authors,
163 'color' => \$Git::SVN::Log::color,
164 'pager=s' => \$Git::SVN::Log::pager
165 } ],
166 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
167 {} ],
168 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
169 { 'merge|m|M' => \$_merge,
170 'verbose|v' => \$_verbose,
171 'strategy|s=s' => \$_strategy,
172 'local|l' => \$_local,
173 'fetch-all|all' => \$_fetch_all,
174 %fc_opts } ],
175 'commit-diff' => [ \&cmd_commit_diff,
176 'Commit a diff between two trees',
177 { 'message|m=s' => \$_message,
178 'file|F=s' => \$_file,
179 'revision|r=s' => \$_revision,
180 %cmt_opts } ],
183 my $cmd;
184 for (my $i = 0; $i < @ARGV; $i++) {
185 if (defined $cmd{$ARGV[$i]}) {
186 $cmd = $ARGV[$i];
187 splice @ARGV, $i, 1;
188 last;
192 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
194 read_repo_config(\%opts);
195 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
196 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
197 'minimize-connections' => \$Git::SVN::Migration::_minimize,
198 'id|i=s' => \$Git::SVN::default_ref_id,
199 'svn-remote|remote|R=s' => sub {
200 $Git::SVN::no_reuse_existing = 1;
201 $Git::SVN::default_repo_id = $_[1] });
202 exit 1 if (!$rv && $cmd && $cmd ne 'log');
204 usage(0) if $_help;
205 version() if $_version;
206 usage(1) unless defined $cmd;
207 load_authors() if $_authors;
209 # make sure we're always running
210 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
211 unless (-d $ENV{GIT_DIR}) {
212 if ($git_dir_user_set) {
213 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
214 "but it is not a directory\n";
216 my $git_dir = delete $ENV{GIT_DIR};
217 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
218 unless (length $cdup) {
219 die "Already at toplevel, but $git_dir ",
220 "not found '$cdup'\n";
222 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
223 unless (-d $git_dir) {
224 die "$git_dir still not found after going to ",
225 "'$cdup'\n";
227 $ENV{GIT_DIR} = $git_dir;
230 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
231 Git::SVN::Migration::migration_check();
233 Git::SVN::init_vars();
234 eval {
235 Git::SVN::verify_remotes_sanity();
236 $cmd{$cmd}->[0]->(@ARGV);
238 fatal $@ if $@;
239 post_fetch_checkout();
240 exit 0;
242 ####################### primary functions ######################
243 sub usage {
244 my $exit = shift || 0;
245 my $fd = $exit ? \*STDERR : \*STDOUT;
246 print $fd <<"";
247 git-svn - bidirectional operations between a single Subversion tree and git
248 Usage: $0 <command> [options] [arguments]\n
250 print $fd "Available commands:\n" unless $cmd;
252 foreach (sort keys %cmd) {
253 next if $cmd && $cmd ne $_;
254 next if /^multi-/; # don't show deprecated commands
255 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
256 foreach (sort keys %{$cmd{$_}->[2]}) {
257 # mixed-case options are for .git/config only
258 next if /[A-Z]/ && /^[a-z]+$/i;
259 # prints out arguments as they should be passed:
260 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
261 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
262 "--$_" : "-$_" }
263 split /\|/,$_)," $x\n";
266 print $fd <<"";
267 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
268 arbitrary identifier if you're tracking multiple SVN branches/repositories in
269 one git repository and want to keep them separate. See git-svn(1) for more
270 information.
272 exit $exit;
275 sub version {
276 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
277 exit 0;
280 sub do_git_init_db {
281 unless (-d $ENV{GIT_DIR}) {
282 my @init_db = ('init');
283 push @init_db, "--template=$_template" if defined $_template;
284 if (defined $_shared) {
285 if ($_shared =~ /[a-z]/) {
286 push @init_db, "--shared=$_shared";
287 } else {
288 push @init_db, "--shared";
291 command_noisy(@init_db);
293 my $set;
294 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
295 foreach my $i (keys %icv) {
296 die "'$set' and '$i' cannot both be set\n" if $set;
297 next unless defined $icv{$i};
298 command_noisy('config', "$pfx.$i", $icv{$i});
299 $set = $i;
303 sub init_subdir {
304 my $repo_path = shift or return;
305 mkpath([$repo_path]) unless -d $repo_path;
306 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
307 $ENV{GIT_DIR} = '.git';
310 sub cmd_clone {
311 my ($url, $path) = @_;
312 if (!defined $path &&
313 (defined $_trunk || defined $_branches || defined $_tags ||
314 defined $_stdlayout) &&
315 $url !~ m#^[a-z\+]+://#) {
316 $path = $url;
318 $path = basename($url) if !defined $path || !length $path;
319 cmd_init($url, $path);
320 Git::SVN::fetch_all($Git::SVN::default_repo_id);
323 sub cmd_init {
324 if (defined $_stdlayout) {
325 $_trunk = 'trunk' if (!defined $_trunk);
326 $_tags = 'tags' if (!defined $_tags);
327 $_branches = 'branches' if (!defined $_branches);
329 if (defined $_trunk || defined $_branches || defined $_tags) {
330 return cmd_multi_init(@_);
332 my $url = shift or die "SVN repository location required ",
333 "as a command-line argument\n";
334 init_subdir(@_);
335 do_git_init_db();
337 Git::SVN->init($url);
340 sub cmd_fetch {
341 if (grep /^\d+=./, @_) {
342 die "'<rev>=<commit>' fetch arguments are ",
343 "no longer supported.\n";
345 my ($remote) = @_;
346 if (@_ > 1) {
347 die "Usage: $0 fetch [--all] [svn-remote]\n";
349 $remote ||= $Git::SVN::default_repo_id;
350 if ($_fetch_all) {
351 cmd_multi_fetch();
352 } else {
353 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
357 sub cmd_set_tree {
358 my (@commits) = @_;
359 if ($_stdin || !@commits) {
360 print "Reading from stdin...\n";
361 @commits = ();
362 while (<STDIN>) {
363 if (/\b($sha1_short)\b/o) {
364 unshift @commits, $1;
368 my @revs;
369 foreach my $c (@commits) {
370 my @tmp = command('rev-parse',$c);
371 if (scalar @tmp == 1) {
372 push @revs, $tmp[0];
373 } elsif (scalar @tmp > 1) {
374 push @revs, reverse(command('rev-list',@tmp));
375 } else {
376 fatal "Failed to rev-parse $c";
379 my $gs = Git::SVN->new;
380 my ($r_last, $cmt_last) = $gs->last_rev_commit;
381 $gs->fetch;
382 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
383 fatal "There are new revisions that were fetched ",
384 "and need to be merged (or acknowledged) ",
385 "before committing.\nlast rev: $r_last\n",
386 " current: $gs->{last_rev}";
388 $gs->set_tree($_) foreach @revs;
389 print "Done committing ",scalar @revs," revisions to SVN\n";
392 sub cmd_dcommit {
393 my $head = shift;
394 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
395 'Cannot dcommit with a dirty index. Commit your changes first, '
396 . "or stash them with `git stash'.\n";
397 $head ||= 'HEAD';
398 my @refs;
399 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
400 print "Committing to $url ...\n";
401 unless ($gs) {
402 die "Unable to determine upstream SVN information from ",
403 "$head history\n";
405 my $last_rev;
406 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
407 if ($_no_rebase && scalar(@$linear_refs) > 1) {
408 warn "Attempting to commit more than one change while ",
409 "--no-rebase is enabled.\n",
410 "If these changes depend on each other, re-running ",
411 "without --no-rebase will be required."
413 while (1) {
414 my $d = shift @$linear_refs or last;
415 unless (defined $last_rev) {
416 (undef, $last_rev, undef) = cmt_metadata("$d~1");
417 unless (defined $last_rev) {
418 fatal "Unable to extract revision information ",
419 "from commit $d~1";
422 if ($_dry_run) {
423 print "diff-tree $d~1 $d\n";
424 } else {
425 my $cmt_rev;
426 my %ed_opts = ( r => $last_rev,
427 log => get_commit_entry($d)->{log},
428 ra => Git::SVN::Ra->new($gs->full_url),
429 config => SVN::Core::config_get_config(
430 $Git::SVN::Ra::config_dir
432 tree_a => "$d~1",
433 tree_b => $d,
434 editor_cb => sub {
435 print "Committed r$_[0]\n";
436 $cmt_rev = $_[0];
438 svn_path => '');
439 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
440 print "No changes\n$d~1 == $d\n";
441 } elsif ($parents->{$d} && @{$parents->{$d}}) {
442 $gs->{inject_parents_dcommit}->{$cmt_rev} =
443 $parents->{$d};
445 $_fetch_all ? $gs->fetch_all : $gs->fetch;
446 next if $_no_rebase;
448 # we always want to rebase against the current HEAD,
449 # not any head that was passed to us
450 my @diff = command('diff-tree', $d,
451 $gs->refname, '--');
452 my @finish;
453 if (@diff) {
454 @finish = rebase_cmd();
455 print STDERR "W: $d and ", $gs->refname,
456 " differ, using @finish:\n",
457 join("\n", @diff), "\n";
458 } else {
459 print "No changes between current HEAD and ",
460 $gs->refname,
461 "\nResetting to the latest ",
462 $gs->refname, "\n";
463 @finish = qw/reset --mixed/;
465 command_noisy(@finish, $gs->refname);
466 if (@diff) {
467 @refs = ();
468 my ($url_, $rev_, $uuid_, $gs_) =
469 working_head_info($head, \@refs);
470 my ($linear_refs_, $parents_) =
471 linearize_history($gs_, \@refs);
472 if (scalar(@$linear_refs) !=
473 scalar(@$linear_refs_)) {
474 fatal "# of revisions changed ",
475 "\nbefore:\n",
476 join("\n", @$linear_refs),
477 "\n\nafter:\n",
478 join("\n", @$linear_refs_), "\n",
479 'If you are attempting to commit ',
480 "merges, try running:\n\t",
481 'git rebase --interactive',
482 '--preserve-merges ',
483 $gs->refname,
484 "\nBefore dcommitting";
486 if ($url_ ne $url) {
487 fatal "URL mismatch after rebase: ",
488 "$url_ != $url";
490 if ($uuid_ ne $uuid) {
491 fatal "uuid mismatch after rebase: ",
492 "$uuid_ != $uuid";
494 # remap parents
495 my (%p, @l, $i);
496 for ($i = 0; $i < scalar @$linear_refs; $i++) {
497 my $new = $linear_refs_->[$i] or next;
498 $p{$new} =
499 $parents->{$linear_refs->[$i]};
500 push @l, $new;
502 $parents = \%p;
503 $linear_refs = \@l;
505 $last_rev = $cmt_rev;
510 sub cmd_find_rev {
511 my $revision_or_hash = shift;
512 my $result;
513 if ($revision_or_hash =~ /^r\d+$/) {
514 my $head = shift;
515 $head ||= 'HEAD';
516 my @refs;
517 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
518 unless ($gs) {
519 die "Unable to determine upstream SVN information from ",
520 "$head history\n";
522 my $desired_revision = substr($revision_or_hash, 1);
523 $result = $gs->rev_db_get($desired_revision);
524 } else {
525 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
526 $result = $rev;
528 print "$result\n" if $result;
531 sub cmd_rebase {
532 command_noisy(qw/update-index --refresh/);
533 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
534 unless ($gs) {
535 die "Unable to determine upstream SVN information from ",
536 "working tree history\n";
538 if (command(qw/diff-index HEAD --/)) {
539 print STDERR "Cannot rebase with uncommited changes:\n";
540 command_noisy('status');
541 exit 1;
543 unless ($_local) {
544 $_fetch_all ? $gs->fetch_all : $gs->fetch;
546 command_noisy(rebase_cmd(), $gs->refname);
549 sub cmd_show_ignore {
550 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
551 $gs ||= Git::SVN->new;
552 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
553 $gs->prop_walk($gs->{path}, $r, sub {
554 my ($gs, $path, $props) = @_;
555 print STDOUT "\n# $path\n";
556 my $s = $props->{'svn:ignore'} or return;
557 $s =~ s/[\r\n]+/\n/g;
558 chomp $s;
559 $s =~ s#^#$path#gm;
560 print STDOUT "$s\n";
564 sub cmd_create_ignore {
565 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
566 $gs ||= Git::SVN->new;
567 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
568 $gs->prop_walk($gs->{path}, $r, sub {
569 my ($gs, $path, $props) = @_;
570 # $path is of the form /path/to/dir/
571 my $ignore = '.' . $path . '.gitignore';
572 my $s = $props->{'svn:ignore'} or return;
573 open(GITIGNORE, '>', $ignore)
574 or fatal("Failed to open `$ignore' for writing: $!");
575 $s =~ s/[\r\n]+/\n/g;
576 chomp $s;
577 # Prefix all patterns so that the ignore doesn't apply
578 # to sub-directories.
579 $s =~ s#^#/#gm;
580 print GITIGNORE "$s\n";
581 close(GITIGNORE)
582 or fatal("Failed to close `$ignore': $!");
583 command_noisy('add', $ignore);
587 sub canonicalize_path {
588 my ($path) = @_;
589 # File::Spec->canonpath doesn't collapse x/../y into y (for a
590 # good reason), so let's do this manually.
591 $path =~ s#/+#/#g;
592 $path =~ s#/\.(?:/|$)#/#g;
593 $path =~ s#/[^/]+/\.\.##g;
594 $path =~ s#/$##g;
595 return $path;
598 # get_svnprops(PATH)
599 # ------------------
600 # Helper for cmd_propget and cmd_proplist below.
601 sub get_svnprops {
602 my $path = shift;
603 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
604 $gs ||= Git::SVN->new;
606 # prefix THE PATH by the sub-directory from which the user
607 # invoked us.
608 $path = $cmd_dir_prefix . $path;
609 fatal("No such file or directory: $path") unless -e $path;
610 my $is_dir = -d $path ? 1 : 0;
611 $path = $gs->{path} . '/' . $path;
613 # canonicalize the path (otherwise libsvn will abort or fail to
614 # find the file)
615 $path = canonicalize_path($path);
617 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
618 my $props;
619 if ($is_dir) {
620 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
622 else {
623 (undef, $props) = $gs->ra->get_file($path, $r, undef);
625 return $props;
628 # cmd_propget (PROP, PATH)
629 # ------------------------
630 # Print the SVN property PROP for PATH.
631 sub cmd_propget {
632 my ($prop, $path) = @_;
633 $path = '.' if not defined $path;
634 usage(1) if not defined $prop;
635 my $props = get_svnprops($path);
636 if (not defined $props->{$prop}) {
637 fatal("`$path' does not have a `$prop' SVN property.");
639 print $props->{$prop} . "\n";
642 # cmd_proplist (PATH)
643 # -------------------
644 # Print the list of SVN properties for PATH.
645 sub cmd_proplist {
646 my $path = shift;
647 $path = '.' if not defined $path;
648 my $props = get_svnprops($path);
649 print "Properties on '$path':\n";
650 foreach (sort keys %{$props}) {
651 print " $_\n";
655 sub cmd_multi_init {
656 my $url = shift;
657 unless (defined $_trunk || defined $_branches || defined $_tags) {
658 usage(1);
661 # there are currently some bugs that prevent multi-init/multi-fetch
662 # setups from working well without this.
663 $Git::SVN::_minimize_url = 1;
665 $_prefix = '' unless defined $_prefix;
666 if (defined $url) {
667 $url =~ s#/+$##;
668 init_subdir(@_);
670 do_git_init_db();
671 if (defined $_trunk) {
672 my $trunk_ref = $_prefix . 'trunk';
673 # try both old-style and new-style lookups:
674 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
675 unless ($gs_trunk) {
676 my ($trunk_url, $trunk_path) =
677 complete_svn_url($url, $_trunk);
678 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
679 undef, $trunk_ref);
682 return unless defined $_branches || defined $_tags;
683 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
684 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
685 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
688 sub cmd_multi_fetch {
689 my $remotes = Git::SVN::read_all_remotes();
690 foreach my $repo_id (sort keys %$remotes) {
691 if ($remotes->{$repo_id}->{url}) {
692 Git::SVN::fetch_all($repo_id, $remotes);
697 # this command is special because it requires no metadata
698 sub cmd_commit_diff {
699 my ($ta, $tb, $url) = @_;
700 my $usage = "Usage: $0 commit-diff -r<revision> ".
701 "<tree-ish> <tree-ish> [<URL>]";
702 fatal($usage) if (!defined $ta || !defined $tb);
703 my $svn_path;
704 if (!defined $url) {
705 my $gs = eval { Git::SVN->new };
706 if (!$gs) {
707 fatal("Needed URL or usable git-svn --id in ",
708 "the command-line\n", $usage);
710 $url = $gs->{url};
711 $svn_path = $gs->{path};
713 unless (defined $_revision) {
714 fatal("-r|--revision is a required argument\n", $usage);
716 if (defined $_message && defined $_file) {
717 fatal("Both --message/-m and --file/-F specified ",
718 "for the commit message.\n",
719 "I have no idea what you mean");
721 if (defined $_file) {
722 $_message = file_to_s($_file);
723 } else {
724 $_message ||= get_commit_entry($tb)->{log};
726 my $ra ||= Git::SVN::Ra->new($url);
727 $svn_path ||= $ra->{svn_path};
728 my $r = $_revision;
729 if ($r eq 'HEAD') {
730 $r = $ra->get_latest_revnum;
731 } elsif ($r !~ /^\d+$/) {
732 die "revision argument: $r not understood by git-svn\n";
734 my %ed_opts = ( r => $r,
735 log => $_message,
736 ra => $ra,
737 tree_a => $ta,
738 tree_b => $tb,
739 editor_cb => sub { print "Committed r$_[0]\n" },
740 svn_path => $svn_path );
741 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
742 print "No changes\n$ta == $tb\n";
746 ########################### utility functions #########################
748 sub rebase_cmd {
749 my @cmd = qw/rebase/;
750 push @cmd, '-v' if $_verbose;
751 push @cmd, qw/--merge/ if $_merge;
752 push @cmd, "--strategy=$_strategy" if $_strategy;
753 @cmd;
756 sub post_fetch_checkout {
757 return if $_no_checkout;
758 my $gs = $Git::SVN::_head or return;
759 return if verify_ref('refs/heads/master^0');
761 my $valid_head = verify_ref('HEAD^0');
762 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
763 return if ($valid_head || !verify_ref('HEAD^0'));
765 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
766 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
767 return if -f $index;
769 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
770 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
771 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
772 print STDERR "Checked out HEAD:\n ",
773 $gs->full_url, " r", $gs->last_rev, "\n";
776 sub complete_svn_url {
777 my ($url, $path) = @_;
778 $path =~ s#/+$##;
779 if ($path !~ m#^[a-z\+]+://#) {
780 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
781 fatal("E: '$path' is not a complete URL ",
782 "and a separate URL is not specified");
784 return ($url, $path);
786 return ($path, '');
789 sub complete_url_ls_init {
790 my ($ra, $repo_path, $switch, $pfx) = @_;
791 unless ($repo_path) {
792 print STDERR "W: $switch not specified\n";
793 return;
795 $repo_path =~ s#/+$##;
796 if ($repo_path =~ m#^[a-z\+]+://#) {
797 $ra = Git::SVN::Ra->new($repo_path);
798 $repo_path = '';
799 } else {
800 $repo_path =~ s#^/+##;
801 unless ($ra) {
802 fatal("E: '$repo_path' is not a complete URL ",
803 "and a separate URL is not specified");
806 my $url = $ra->{url};
807 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
808 my $k = "svn-remote.$gs->{repo_id}.url";
809 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
810 if ($orig_url && ($orig_url ne $gs->{url})) {
811 die "$k already set: $orig_url\n",
812 "wanted to set to: $gs->{url}\n";
814 command_oneline('config', $k, $gs->{url}) unless $orig_url;
815 my $remote_path = "$ra->{svn_path}/$repo_path/*";
816 $remote_path =~ s#/+#/#g;
817 $remote_path =~ s#^/##g;
818 my ($n) = ($switch =~ /^--(\w+)/);
819 if (length $pfx && $pfx !~ m#/$#) {
820 die "--prefix='$pfx' must have a trailing slash '/'\n";
822 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
823 "$remote_path:refs/remotes/$pfx*");
826 sub verify_ref {
827 my ($ref) = @_;
828 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
829 { STDERR => 0 }); };
832 sub get_tree_from_treeish {
833 my ($treeish) = @_;
834 # $treeish can be a symbolic ref, too:
835 my $type = command_oneline(qw/cat-file -t/, $treeish);
836 my $expected;
837 while ($type eq 'tag') {
838 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
840 if ($type eq 'commit') {
841 $expected = (grep /^tree /, command(qw/cat-file commit/,
842 $treeish))[0];
843 ($expected) = ($expected =~ /^tree ($sha1)$/o);
844 die "Unable to get tree from $treeish\n" unless $expected;
845 } elsif ($type eq 'tree') {
846 $expected = $treeish;
847 } else {
848 die "$treeish is a $type, expected tree, tag or commit\n";
850 return $expected;
853 sub get_commit_entry {
854 my ($treeish) = shift;
855 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
856 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
857 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
858 open my $log_fh, '>', $commit_editmsg or croak $!;
860 my $type = command_oneline(qw/cat-file -t/, $treeish);
861 if ($type eq 'commit' || $type eq 'tag') {
862 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
863 $type, $treeish);
864 my $in_msg = 0;
865 while (<$msg_fh>) {
866 if (!$in_msg) {
867 $in_msg = 1 if (/^\s*$/);
868 } elsif (/^git-svn-id: /) {
869 # skip this for now, we regenerate the
870 # correct one on re-fetch anyways
871 # TODO: set *:merge properties or like...
872 } else {
873 print $log_fh $_ or croak $!;
876 command_close_pipe($msg_fh, $ctx);
878 close $log_fh or croak $!;
880 if ($_edit || ($type eq 'tree')) {
881 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
882 # TODO: strip out spaces, comments, like git-commit.sh
883 system($editor, $commit_editmsg);
885 rename $commit_editmsg, $commit_msg or croak $!;
886 open $log_fh, '<', $commit_msg or croak $!;
887 { local $/; chomp($log_entry{log} = <$log_fh>); }
888 close $log_fh or croak $!;
889 unlink $commit_msg;
890 \%log_entry;
893 sub s_to_file {
894 my ($str, $file, $mode) = @_;
895 open my $fd,'>',$file or croak $!;
896 print $fd $str,"\n" or croak $!;
897 close $fd or croak $!;
898 chmod ($mode &~ umask, $file) if (defined $mode);
901 sub file_to_s {
902 my $file = shift;
903 open my $fd,'<',$file or croak "$!: file: $file\n";
904 local $/;
905 my $ret = <$fd>;
906 close $fd or croak $!;
907 $ret =~ s/\s*$//s;
908 return $ret;
911 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
912 sub load_authors {
913 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
914 my $log = $cmd eq 'log';
915 while (<$authors>) {
916 chomp;
917 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
918 my ($user, $name, $email) = ($1, $2, $3);
919 if ($log) {
920 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
921 } else {
922 $users{$user} = [$name, $email];
925 close $authors or croak $!;
928 # convert GetOpt::Long specs for use by git-config
929 sub read_repo_config {
930 return unless -d $ENV{GIT_DIR};
931 my $opts = shift;
932 my @config_only;
933 foreach my $o (keys %$opts) {
934 # if we have mixedCase and a long option-only, then
935 # it's a config-only variable that we don't need for
936 # the command-line.
937 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
938 my $v = $opts->{$o};
939 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
940 $key =~ s/-//g;
941 my $arg = 'git-config';
942 $arg .= ' --int' if ($o =~ /[:=]i$/);
943 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
944 if (ref $v eq 'ARRAY') {
945 chomp(my @tmp = `$arg --get-all svn.$key`);
946 @$v = @tmp if @tmp;
947 } else {
948 chomp(my $tmp = `$arg --get svn.$key`);
949 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
950 $$v = $tmp;
954 delete @$opts{@config_only} if @config_only;
957 sub extract_metadata {
958 my $id = shift or return (undef, undef, undef);
959 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
960 \s([a-f\d\-]+)$/x);
961 if (!defined $rev || !$uuid || !$url) {
962 # some of the original repositories I made had
963 # identifiers like this:
964 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
966 return ($url, $rev, $uuid);
969 sub cmt_metadata {
970 return extract_metadata((grep(/^git-svn-id: /,
971 command(qw/cat-file commit/, shift)))[-1]);
974 sub working_head_info {
975 my ($head, $refs) = @_;
976 my @args = ('log', '--no-color', '--first-parent');
977 my ($fh, $ctx) = command_output_pipe(@args, $head);
978 my $hash;
979 my %max;
980 while (<$fh>) {
981 if ( m{^commit ($::sha1)$} ) {
982 unshift @$refs, $hash if $hash and $refs;
983 $hash = $1;
984 next;
986 next unless s{^\s*(git-svn-id:)}{$1};
987 my ($url, $rev, $uuid) = extract_metadata($_);
988 if (defined $url && defined $rev) {
989 next if $max{$url} and $max{$url} < $rev;
990 if (my $gs = Git::SVN->find_by_url($url)) {
991 my $c = $gs->rev_db_get($rev);
992 if ($c && $c eq $hash) {
993 close $fh; # break the pipe
994 return ($url, $rev, $uuid, $gs);
995 } else {
996 $max{$url} ||= $gs->rev_db_max;
1001 command_close_pipe($fh, $ctx);
1002 (undef, undef, undef, undef);
1005 sub read_commit_parents {
1006 my ($parents, $c) = @_;
1007 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1008 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1009 @{$parents->{$c}} = split(/ /, $p);
1012 sub linearize_history {
1013 my ($gs, $refs) = @_;
1014 my %parents;
1015 foreach my $c (@$refs) {
1016 read_commit_parents(\%parents, $c);
1019 my @linear_refs;
1020 my %skip = ();
1021 my $last_svn_commit = $gs->last_commit;
1022 foreach my $c (reverse @$refs) {
1023 next if $c eq $last_svn_commit;
1024 last if $skip{$c};
1026 unshift @linear_refs, $c;
1027 $skip{$c} = 1;
1029 # we only want the first parent to diff against for linear
1030 # history, we save the rest to inject when we finalize the
1031 # svn commit
1032 my $fp_a = verify_ref("$c~1");
1033 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1034 if (!$fp_a || !$fp_b) {
1035 die "Commit $c\n",
1036 "has no parent commit, and therefore ",
1037 "nothing to diff against.\n",
1038 "You should be working from a repository ",
1039 "originally created by git-svn\n";
1041 if ($fp_a ne $fp_b) {
1042 die "$c~1 = $fp_a, however parsing commit $c ",
1043 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1046 foreach my $p (@{$parents{$c}}) {
1047 $skip{$p} = 1;
1050 (\@linear_refs, \%parents);
1053 package Git::SVN::Util;
1054 use strict;
1055 use warnings;
1056 use Digest::MD5;
1058 sub md5sum {
1059 my $arg = shift;
1060 my $ref = ref $arg;
1061 my $md5 = Digest::MD5->new();
1062 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1063 $md5->addfile($arg) or croak $!;
1064 } elsif ($ref eq 'SCALAR') {
1065 $md5->add($$arg) or croak $!;
1066 } elsif (!$ref) {
1067 $md5->add($arg) or croak $!;
1068 } else {
1069 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1071 return $md5->hexdigest();
1074 package Git::SVN;
1075 use strict;
1076 use warnings;
1077 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1078 $_repack $_repack_flags $_use_svm_props $_head
1079 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1080 use Carp qw/croak/;
1081 use File::Path qw/mkpath/;
1082 use File::Copy qw/copy/;
1083 use IPC::Open3;
1085 my $_repack_nr;
1086 # properties that we do not log:
1087 my %SKIP_PROP;
1088 BEGIN {
1089 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1090 svn:special svn:executable
1091 svn:entry:committed-rev
1092 svn:entry:last-author
1093 svn:entry:uuid
1094 svn:entry:committed-date/;
1096 # some options are read globally, but can be overridden locally
1097 # per [svn-remote "..."] section. Command-line options will *NOT*
1098 # override options set in an [svn-remote "..."] section
1099 no strict 'refs';
1100 for my $option (qw/follow_parent no_metadata use_svm_props
1101 use_svnsync_props/) {
1102 my $key = $option;
1103 $key =~ tr/_//d;
1104 my $prop = "-$option";
1105 *$option = sub {
1106 my ($self) = @_;
1107 return $self->{$prop} if exists $self->{$prop};
1108 my $k = "svn-remote.$self->{repo_id}.$key";
1109 eval { command_oneline(qw/config --get/, $k) };
1110 if ($@) {
1111 $self->{$prop} = ${"Git::SVN::_$option"};
1112 } else {
1113 my $v = command_oneline(qw/config --bool/,$k);
1114 $self->{$prop} = $v eq 'false' ? 0 : 1;
1116 return $self->{$prop};
1121 my %LOCKFILES;
1122 END { unlink keys %LOCKFILES if %LOCKFILES }
1124 sub resolve_local_globs {
1125 my ($url, $fetch, $glob_spec) = @_;
1126 return unless defined $glob_spec;
1127 my $ref = $glob_spec->{ref};
1128 my $path = $glob_spec->{path};
1129 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1130 next unless m#^refs/remotes/$ref->{regex}$#;
1131 my $p = $1;
1132 my $pathname = desanitize_refname($path->full_path($p));
1133 my $refname = desanitize_refname($ref->full_path($p));
1134 if (my $existing = $fetch->{$pathname}) {
1135 if ($existing ne $refname) {
1136 die "Refspec conflict:\n",
1137 "existing: refs/remotes/$existing\n",
1138 " globbed: refs/remotes/$refname\n";
1140 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1141 $u =~ s!^\Q$url\E(/|$)!! or die
1142 "refs/remotes/$refname: '$url' not found in '$u'\n";
1143 if ($pathname ne $u) {
1144 warn "W: Refspec glob conflict ",
1145 "(ref: refs/remotes/$refname):\n",
1146 "expected path: $pathname\n",
1147 " real path: $u\n",
1148 "Continuing ahead with $u\n";
1149 next;
1151 } else {
1152 $fetch->{$pathname} = $refname;
1157 sub parse_revision_argument {
1158 my ($base, $head) = @_;
1159 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1160 return ($base, $head);
1162 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1163 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1164 return ($head, $head) if ($::_revision eq 'HEAD');
1165 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1166 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1167 die "revision argument: $::_revision not understood by git-svn\n";
1170 sub fetch_all {
1171 my ($repo_id, $remotes) = @_;
1172 if (ref $repo_id) {
1173 my $gs = $repo_id;
1174 $repo_id = undef;
1175 $repo_id = $gs->{repo_id};
1177 $remotes ||= read_all_remotes();
1178 my $remote = $remotes->{$repo_id} or
1179 die "[svn-remote \"$repo_id\"] unknown\n";
1180 my $fetch = $remote->{fetch};
1181 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1182 my (@gs, @globs);
1183 my $ra = Git::SVN::Ra->new($url);
1184 my $uuid = $ra->get_uuid;
1185 my $head = $ra->get_latest_revnum;
1186 my $base = defined $fetch ? $head : 0;
1188 # read the max revs for wildcard expansion (branches/*, tags/*)
1189 foreach my $t (qw/branches tags/) {
1190 defined $remote->{$t} or next;
1191 push @globs, $remote->{$t};
1192 my $max_rev = eval { tmp_config(qw/--int --get/,
1193 "svn-remote.$repo_id.${t}-maxRev") };
1194 if (defined $max_rev && ($max_rev < $base)) {
1195 $base = $max_rev;
1196 } elsif (!defined $max_rev) {
1197 $base = 0;
1201 if ($fetch) {
1202 foreach my $p (sort keys %$fetch) {
1203 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1204 my $lr = $gs->rev_db_max;
1205 if (defined $lr) {
1206 $base = $lr if ($lr < $base);
1208 push @gs, $gs;
1212 ($base, $head) = parse_revision_argument($base, $head);
1213 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1216 sub read_all_remotes {
1217 my $r = {};
1218 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1219 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1220 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1221 $local_ref =~ s{^/}{};
1222 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1223 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1224 $r->{$1}->{url} = $2;
1225 } elsif (m!^(.+)\.(branches|tags)=
1226 (.*):refs/remotes/(.+)\s*$/!x) {
1227 my ($p, $g) = ($3, $4);
1228 my $rs = $r->{$1}->{$2} = {
1229 t => $2,
1230 remote => $1,
1231 path => Git::SVN::GlobSpec->new($p),
1232 ref => Git::SVN::GlobSpec->new($g) };
1233 if (length($rs->{ref}->{right}) != 0) {
1234 die "The '*' glob character must be the last ",
1235 "character of '$g'\n";
1242 sub init_vars {
1243 if (defined $_repack) {
1244 $_repack = 1000 if ($_repack <= 0);
1245 $_repack_nr = $_repack;
1246 $_repack_flags ||= '-d';
1250 sub verify_remotes_sanity {
1251 return unless -d $ENV{GIT_DIR};
1252 my %seen;
1253 foreach (command(qw/config -l/)) {
1254 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1255 if ($seen{$1}) {
1256 die "Remote ref refs/remote/$1 is tracked by",
1257 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1258 "Please resolve this ambiguity in ",
1259 "your git configuration file before ",
1260 "continuing\n";
1262 $seen{$1} = $_;
1267 # we allow more chars than remotes2config.sh...
1268 sub sanitize_remote_name {
1269 my ($name) = @_;
1270 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1271 $name;
1274 sub find_existing_remote {
1275 my ($url, $remotes) = @_;
1276 return undef if $no_reuse_existing;
1277 my $existing;
1278 foreach my $repo_id (keys %$remotes) {
1279 my $u = $remotes->{$repo_id}->{url} or next;
1280 next if $u ne $url;
1281 $existing = $repo_id;
1282 last;
1284 $existing;
1287 sub init_remote_config {
1288 my ($self, $url, $no_write) = @_;
1289 $url =~ s!/+$!!; # strip trailing slash
1290 my $r = read_all_remotes();
1291 my $existing = find_existing_remote($url, $r);
1292 if ($existing) {
1293 unless ($no_write) {
1294 print STDERR "Using existing ",
1295 "[svn-remote \"$existing\"]\n";
1297 $self->{repo_id} = $existing;
1298 } elsif ($_minimize_url) {
1299 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1300 $existing = find_existing_remote($min_url, $r);
1301 if ($existing) {
1302 unless ($no_write) {
1303 print STDERR "Using existing ",
1304 "[svn-remote \"$existing\"]\n";
1306 $self->{repo_id} = $existing;
1308 if ($min_url ne $url) {
1309 unless ($no_write) {
1310 print STDERR "Using higher level of URL: ",
1311 "$url => $min_url\n";
1313 my $old_path = $self->{path};
1314 $self->{path} = $url;
1315 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1316 if (length $old_path) {
1317 $self->{path} .= "/$old_path";
1319 $url = $min_url;
1322 my $orig_url;
1323 if (!$existing) {
1324 # verify that we aren't overwriting anything:
1325 $orig_url = eval {
1326 command_oneline('config', '--get',
1327 "svn-remote.$self->{repo_id}.url")
1329 if ($orig_url && ($orig_url ne $url)) {
1330 die "svn-remote.$self->{repo_id}.url already set: ",
1331 "$orig_url\nwanted to set to: $url\n";
1334 my ($xrepo_id, $xpath) = find_ref($self->refname);
1335 if (defined $xpath) {
1336 die "svn-remote.$xrepo_id.fetch already set to track ",
1337 "$xpath:refs/remotes/", $self->refname, "\n";
1339 unless ($no_write) {
1340 command_noisy('config',
1341 "svn-remote.$self->{repo_id}.url", $url);
1342 $self->{path} =~ s{^/}{};
1343 command_noisy('config', '--add',
1344 "svn-remote.$self->{repo_id}.fetch",
1345 "$self->{path}:".$self->refname);
1347 $self->{url} = $url;
1350 sub find_by_url { # repos_root and, path are optional
1351 my ($class, $full_url, $repos_root, $path) = @_;
1353 return undef unless defined $full_url;
1354 remove_username($full_url);
1355 remove_username($repos_root) if defined $repos_root;
1356 my $remotes = read_all_remotes();
1357 if (defined $full_url && defined $repos_root && !defined $path) {
1358 $path = $full_url;
1359 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1361 foreach my $repo_id (keys %$remotes) {
1362 my $u = $remotes->{$repo_id}->{url} or next;
1363 remove_username($u);
1364 next if defined $repos_root && $repos_root ne $u;
1366 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1367 foreach (qw/branches tags/) {
1368 resolve_local_globs($u, $fetch,
1369 $remotes->{$repo_id}->{$_});
1371 my $p = $path;
1372 unless (defined $p) {
1373 $p = $full_url;
1374 $p =~ s#^\Q$u\E(?:/|$)## or next;
1376 foreach my $f (keys %$fetch) {
1377 next if $f ne $p;
1378 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1381 undef;
1384 sub init {
1385 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1386 my $self = _new($class, $repo_id, $ref_id, $path);
1387 if (defined $url) {
1388 $self->init_remote_config($url, $no_write);
1390 $self;
1393 sub find_ref {
1394 my ($ref_id) = @_;
1395 foreach (command(qw/config -l/)) {
1396 next unless m!^svn-remote\.(.+)\.fetch=
1397 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1398 my ($repo_id, $path, $ref) = ($1, $2, $3);
1399 if ($ref eq $ref_id) {
1400 $path = '' if ($path =~ m#^\./?#);
1401 return ($repo_id, $path);
1404 (undef, undef, undef);
1407 sub new {
1408 my ($class, $ref_id, $repo_id, $path) = @_;
1409 if (defined $ref_id && !defined $repo_id && !defined $path) {
1410 ($repo_id, $path) = find_ref($ref_id);
1411 if (!defined $repo_id) {
1412 die "Could not find a \"svn-remote.*.fetch\" key ",
1413 "in the repository configuration matching: ",
1414 "refs/remotes/$ref_id\n";
1417 my $self = _new($class, $repo_id, $ref_id, $path);
1418 if (!defined $self->{path} || !length $self->{path}) {
1419 my $fetch = command_oneline('config', '--get',
1420 "svn-remote.$repo_id.fetch",
1421 ":refs/remotes/$ref_id\$") or
1422 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1423 "\":refs/remotes/$ref_id\$\" in config\n";
1424 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1426 $self->{url} = command_oneline('config', '--get',
1427 "svn-remote.$repo_id.url") or
1428 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1429 $self->rebuild;
1430 $self;
1433 sub refname {
1434 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1436 # It cannot end with a slash /, we'll throw up on this because
1437 # SVN can't have directories with a slash in their name, either:
1438 if ($refname =~ m{/$}) {
1439 die "ref: '$refname' ends with a trailing slash, this is ",
1440 "not permitted by git nor Subversion\n";
1443 # It cannot have ASCII control character space, tilde ~, caret ^,
1444 # colon :, question-mark ?, asterisk *, space, or open bracket [
1445 # anywhere.
1447 # Additionally, % must be escaped because it is used for escaping
1448 # and we want our escaped refname to be reversible
1449 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1451 # no slash-separated component can begin with a dot .
1452 # /.* becomes /%2E*
1453 $refname =~ s{/\.}{/%2E}g;
1455 # It cannot have two consecutive dots .. anywhere
1456 # .. becomes %2E%2E
1457 $refname =~ s{\.\.}{%2E%2E}g;
1459 return $refname;
1462 sub desanitize_refname {
1463 my ($refname) = @_;
1464 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1465 return $refname;
1468 sub svm_uuid {
1469 my ($self) = @_;
1470 return $self->{svm}->{uuid} if $self->svm;
1471 $self->ra;
1472 unless ($self->{svm}) {
1473 die "SVM UUID not cached, and reading remotely failed\n";
1475 $self->{svm}->{uuid};
1478 sub svm {
1479 my ($self) = @_;
1480 return $self->{svm} if $self->{svm};
1481 my $svm;
1482 # see if we have it in our config, first:
1483 eval {
1484 my $section = "svn-remote.$self->{repo_id}";
1485 $svm = {
1486 source => tmp_config('--get', "$section.svm-source"),
1487 uuid => tmp_config('--get', "$section.svm-uuid"),
1488 replace => tmp_config('--get', "$section.svm-replace"),
1491 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1492 $self->{svm} = $svm;
1494 $self->{svm};
1497 sub _set_svm_vars {
1498 my ($self, $ra) = @_;
1499 return $ra if $self->svm;
1501 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1502 "(svm:source, svm:uuid) ",
1503 "from the following URLs:\n" );
1504 sub read_svm_props {
1505 my ($self, $ra, $path, $r) = @_;
1506 my $props = ($ra->get_dir($path, $r))[2];
1507 my $src = $props->{'svm:source'};
1508 my $uuid = $props->{'svm:uuid'};
1509 return undef if (!$src || !$uuid);
1511 chomp($src, $uuid);
1513 $uuid =~ m{^[0-9a-f\-]{30,}$}
1514 or die "doesn't look right - svm:uuid is '$uuid'\n";
1516 # the '!' is used to mark the repos_root!/relative/path
1517 $src =~ s{/?!/?}{/};
1518 $src =~ s{/+$}{}; # no trailing slashes please
1519 # username is of no interest
1520 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1522 my $replace = $ra->{url};
1523 $replace .= "/$path" if length $path;
1525 my $section = "svn-remote.$self->{repo_id}";
1526 tmp_config("$section.svm-source", $src);
1527 tmp_config("$section.svm-replace", $replace);
1528 tmp_config("$section.svm-uuid", $uuid);
1529 $self->{svm} = {
1530 source => $src,
1531 uuid => $uuid,
1532 replace => $replace
1536 my $r = $ra->get_latest_revnum;
1537 my $path = $self->{path};
1538 my %tried;
1539 while (length $path) {
1540 unless ($tried{"$self->{url}/$path"}) {
1541 return $ra if $self->read_svm_props($ra, $path, $r);
1542 $tried{"$self->{url}/$path"} = 1;
1544 $path =~ s#/?[^/]+$##;
1546 die "Path: '$path' should be ''\n" if $path ne '';
1547 return $ra if $self->read_svm_props($ra, $path, $r);
1548 $tried{"$self->{url}/$path"} = 1;
1550 if ($ra->{repos_root} eq $self->{url}) {
1551 die @err, (map { " $_\n" } keys %tried), "\n";
1554 # nope, make sure we're connected to the repository root:
1555 my $ok;
1556 my @tried_b;
1557 $path = $ra->{svn_path};
1558 $ra = Git::SVN::Ra->new($ra->{repos_root});
1559 while (length $path) {
1560 unless ($tried{"$ra->{url}/$path"}) {
1561 $ok = $self->read_svm_props($ra, $path, $r);
1562 last if $ok;
1563 $tried{"$ra->{url}/$path"} = 1;
1565 $path =~ s#/?[^/]+$##;
1567 die "Path: '$path' should be ''\n" if $path ne '';
1568 $ok ||= $self->read_svm_props($ra, $path, $r);
1569 $tried{"$ra->{url}/$path"} = 1;
1570 if (!$ok) {
1571 die @err, (map { " $_\n" } keys %tried), "\n";
1573 Git::SVN::Ra->new($self->{url});
1576 sub svnsync {
1577 my ($self) = @_;
1578 return $self->{svnsync} if $self->{svnsync};
1580 if ($self->no_metadata) {
1581 die "Can't have both 'noMetadata' and ",
1582 "'useSvnsyncProps' options set!\n";
1584 if ($self->rewrite_root) {
1585 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1586 "options set!\n";
1589 my $svnsync;
1590 # see if we have it in our config, first:
1591 eval {
1592 my $section = "svn-remote.$self->{repo_id}";
1593 $svnsync = {
1594 url => tmp_config('--get', "$section.svnsync-url"),
1595 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1598 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1599 return $self->{svnsync} = $svnsync;
1602 my $err = "useSvnsyncProps set, but failed to read " .
1603 "svnsync property: svn:sync-from-";
1604 my $rp = $self->ra->rev_proplist(0);
1606 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1607 $url =~ m{^[a-z\+]+://} or
1608 die "doesn't look right - svn:sync-from-url is '$url'\n";
1610 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1611 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1612 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1614 my $section = "svn-remote.$self->{repo_id}";
1615 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1616 tmp_config('--add', "$section.svnsync-url", $url);
1617 return $self->{svnsync} = { url => $url, uuid => $uuid };
1620 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1621 # remote lookup (useful for 'git svn log').
1622 sub ra_uuid {
1623 my ($self) = @_;
1624 unless ($self->{ra_uuid}) {
1625 my $key = "svn-remote.$self->{repo_id}.uuid";
1626 my $uuid = eval { tmp_config('--get', $key) };
1627 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1628 $self->{ra_uuid} = $uuid;
1629 } else {
1630 die "ra_uuid called without URL\n" unless $self->{url};
1631 $self->{ra_uuid} = $self->ra->get_uuid;
1632 tmp_config('--add', $key, $self->{ra_uuid});
1635 $self->{ra_uuid};
1638 sub ra {
1639 my ($self) = shift;
1640 my $ra = Git::SVN::Ra->new($self->{url});
1641 if ($self->use_svm_props && !$self->{svm}) {
1642 if ($self->no_metadata) {
1643 die "Can't have both 'noMetadata' and ",
1644 "'useSvmProps' options set!\n";
1645 } elsif ($self->use_svnsync_props) {
1646 die "Can't have both 'useSvnsyncProps' and ",
1647 "'useSvmProps' options set!\n";
1649 $ra = $self->_set_svm_vars($ra);
1650 $self->{-want_revprops} = 1;
1652 $ra;
1655 sub rel_path {
1656 my ($self) = @_;
1657 my $repos_root = $self->ra->{repos_root};
1658 return $self->{path} if ($self->{url} eq $repos_root);
1659 my $url = $self->{url} .
1660 (length $self->{path} ? "/$self->{path}" : $self->{path});
1661 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1662 $url;
1665 # prop_walk(PATH, REV, SUB)
1666 # -------------------------
1667 # Recursively traverse PATH at revision REV and invoke SUB for each
1668 # directory that contains a SVN property. SUB will be invoked as
1669 # follows: &SUB(gs, path, props); where `gs' is this instance of
1670 # Git::SVN, `path' the path to the directory where the properties
1671 # `props' were found. The `path' will be relative to point of checkout,
1672 # that is, if url://repo/trunk is the current Git branch, and that
1673 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1674 # as `path' (note the trailing `/').
1675 sub prop_walk {
1676 my ($self, $path, $rev, $sub) = @_;
1678 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1679 $path =~ s#^/*#/#g;
1680 my $p = $path;
1681 # Strip the irrelevant part of the path.
1682 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1683 # Ensure the path is terminated by a `/'.
1684 $p =~ s#/*$#/#;
1686 # The properties contain all the internal SVN stuff nobody
1687 # (usually) cares about.
1688 my $interesting_props = 0;
1689 foreach (keys %{$props}) {
1690 # If it doesn't start with `svn:', it must be a
1691 # user-defined property.
1692 ++$interesting_props and next if $_ !~ /^svn:/;
1693 # FIXME: Fragile, if SVN adds new public properties,
1694 # this needs to be updated.
1695 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1696 |eol-style|mime-type
1697 |externals|needs-lock)$/x;
1699 &$sub($self, $p, $props) if $interesting_props;
1701 foreach (sort keys %$dirent) {
1702 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1703 $self->prop_walk($path . '/' . $_, $rev, $sub);
1707 sub last_rev { ($_[0]->last_rev_commit)[0] }
1708 sub last_commit { ($_[0]->last_rev_commit)[1] }
1710 # returns the newest SVN revision number and newest commit SHA1
1711 sub last_rev_commit {
1712 my ($self) = @_;
1713 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1714 return ($self->{last_rev}, $self->{last_commit});
1716 my $c = ::verify_ref($self->refname.'^0');
1717 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1718 my $rev = (::cmt_metadata($c))[1];
1719 if (defined $rev) {
1720 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1721 return ($rev, $c);
1724 my $db_path = $self->db_path;
1725 unless (-e $db_path) {
1726 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1727 return (undef, undef);
1729 my $offset = -41; # from tail
1730 my $rl;
1731 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1732 sysseek($fh, $offset, 2); # don't care for errors
1733 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1734 chomp $rl;
1735 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1736 $offset -= 41;
1737 sysseek($fh, $offset, 2); # don't care for errors
1738 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1739 chomp $rl;
1741 if ($c && $c ne $rl) {
1742 die "$db_path and ", $self->refname,
1743 " inconsistent!:\n$c != $rl\n";
1745 my $rev = sysseek($fh, 0, 1) or croak $!;
1746 $rev = ($rev - 41) / 41;
1747 close $fh or croak $!;
1748 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1749 return ($rev, $c);
1752 sub get_fetch_range {
1753 my ($self, $min, $max) = @_;
1754 $max ||= $self->ra->get_latest_revnum;
1755 $min ||= $self->rev_db_max;
1756 (++$min, $max);
1759 sub tmp_config {
1760 my (@args) = @_;
1761 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1762 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1763 if (! -f $config && -f $old_def_config) {
1764 rename $old_def_config, $config or
1765 die "Failed rename $old_def_config => $config: $!\n";
1767 my $old_config = $ENV{GIT_CONFIG};
1768 $ENV{GIT_CONFIG} = $config;
1769 $@ = undef;
1770 my @ret = eval {
1771 unless (-f $config) {
1772 mkfile($config);
1773 open my $fh, '>', $config or
1774 die "Can't open $config: $!\n";
1775 print $fh "; This file is used internally by ",
1776 "git-svn\n" or die
1777 "Couldn't write to $config: $!\n";
1778 print $fh "; You should not have to edit it\n" or
1779 die "Couldn't write to $config: $!\n";
1780 close $fh or die "Couldn't close $config: $!\n";
1782 command('config', @args);
1784 my $err = $@;
1785 if (defined $old_config) {
1786 $ENV{GIT_CONFIG} = $old_config;
1787 } else {
1788 delete $ENV{GIT_CONFIG};
1790 die $err if $err;
1791 wantarray ? @ret : $ret[0];
1794 sub tmp_index_do {
1795 my ($self, $sub) = @_;
1796 my $old_index = $ENV{GIT_INDEX_FILE};
1797 $ENV{GIT_INDEX_FILE} = $self->{index};
1798 $@ = undef;
1799 my @ret = eval {
1800 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1801 mkpath([$dir]) unless -d $dir;
1802 &$sub;
1804 my $err = $@;
1805 if (defined $old_index) {
1806 $ENV{GIT_INDEX_FILE} = $old_index;
1807 } else {
1808 delete $ENV{GIT_INDEX_FILE};
1810 die $err if $err;
1811 wantarray ? @ret : $ret[0];
1814 sub assert_index_clean {
1815 my ($self, $treeish) = @_;
1817 $self->tmp_index_do(sub {
1818 command_noisy('read-tree', $treeish) unless -e $self->{index};
1819 my $x = command_oneline('write-tree');
1820 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1821 /^tree ($::sha1)/mo);
1822 return if $y eq $x;
1824 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1825 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1826 command_noisy('read-tree', $treeish);
1827 $x = command_oneline('write-tree');
1828 if ($y ne $x) {
1829 ::fatal "trees ($treeish) $y != $x\n",
1830 "Something is seriously wrong...";
1835 sub get_commit_parents {
1836 my ($self, $log_entry) = @_;
1837 my (%seen, @ret, @tmp);
1838 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1839 if (my $ip = $self->{inject_parents}) {
1840 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1841 push @tmp, $commit;
1844 if (my $cur = ::verify_ref($self->refname.'^0')) {
1845 push @tmp, $cur;
1847 if (my $ipd = $self->{inject_parents_dcommit}) {
1848 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1849 push @tmp, @$commit;
1852 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1853 while (my $p = shift @tmp) {
1854 next if $seen{$p};
1855 $seen{$p} = 1;
1856 push @ret, $p;
1857 # MAXPARENT is defined to 16 in commit-tree.c:
1858 last if @ret >= 16;
1860 if (@tmp) {
1861 die "r$log_entry->{revision}: No room for parents:\n\t",
1862 join("\n\t", @tmp), "\n";
1864 @ret;
1867 sub rewrite_root {
1868 my ($self) = @_;
1869 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1870 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1871 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1872 if ($rwr) {
1873 $rwr =~ s#/+$##;
1874 if ($rwr !~ m#^[a-z\+]+://#) {
1875 die "$rwr is not a valid URL (key: $k)\n";
1878 $self->{-rewrite_root} = $rwr;
1881 sub metadata_url {
1882 my ($self) = @_;
1883 ($self->rewrite_root || $self->{url}) .
1884 (length $self->{path} ? '/' . $self->{path} : '');
1887 sub full_url {
1888 my ($self) = @_;
1889 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1892 sub do_git_commit {
1893 my ($self, $log_entry) = @_;
1894 my $lr = $self->last_rev;
1895 if (defined $lr && $lr >= $log_entry->{revision}) {
1896 die "Last fetched revision of ", $self->refname,
1897 " was r$lr, but we are about to fetch: ",
1898 "r$log_entry->{revision}!\n";
1900 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1901 croak "$log_entry->{revision} = $c already exists! ",
1902 "Why are we refetching it?\n";
1904 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1905 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1906 $log_entry->{email};
1907 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1909 my $tree = $log_entry->{tree};
1910 if (!defined $tree) {
1911 $tree = $self->tmp_index_do(sub {
1912 command_oneline('write-tree') });
1914 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1916 my @exec = ('git-commit-tree', $tree);
1917 foreach ($self->get_commit_parents($log_entry)) {
1918 push @exec, '-p', $_;
1920 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1921 or croak $!;
1922 print $msg_fh $log_entry->{log} or croak $!;
1923 unless ($self->no_metadata) {
1924 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1925 or croak $!;
1927 $msg_fh->flush == 0 or croak $!;
1928 close $msg_fh or croak $!;
1929 chomp(my $commit = do { local $/; <$out_fh> });
1930 close $out_fh or croak $!;
1931 waitpid $pid, 0;
1932 croak $? if $?;
1933 if ($commit !~ /^$::sha1$/o) {
1934 die "Failed to commit, invalid sha1: $commit\n";
1937 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1939 $self->{last_rev} = $log_entry->{revision};
1940 $self->{last_commit} = $commit;
1941 print "r$log_entry->{revision}";
1942 if (defined $log_entry->{svm_revision}) {
1943 print " (\@$log_entry->{svm_revision})";
1944 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1945 0, $self->svm_uuid);
1947 print " = $commit ($self->{ref_id})\n";
1948 if (defined $_repack && (--$_repack_nr == 0)) {
1949 $_repack_nr = $_repack;
1950 # repack doesn't use any arguments with spaces in them, does it?
1951 print "Running git repack $_repack_flags ...\n";
1952 command_noisy('repack', split(/\s+/, $_repack_flags));
1953 print "Done repacking\n";
1955 return $commit;
1958 sub match_paths {
1959 my ($self, $paths, $r) = @_;
1960 return 1 if $self->{path} eq '';
1961 if (my $path = $paths->{"/$self->{path}"}) {
1962 return ($path->{action} eq 'D') ? 0 : 1;
1964 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1965 if (grep /$self->{path_regex}/, keys %$paths) {
1966 return 1;
1968 my $c = '';
1969 foreach (split m#/#, $self->{path}) {
1970 $c .= "/$_";
1971 next unless ($paths->{$c} &&
1972 ($paths->{$c}->{action} =~ /^[AR]$/));
1973 if ($self->ra->check_path($self->{path}, $r) ==
1974 $SVN::Node::dir) {
1975 return 1;
1978 return 0;
1981 sub find_parent_branch {
1982 my ($self, $paths, $rev) = @_;
1983 return undef unless $self->follow_parent;
1984 unless (defined $paths) {
1985 my $err_handler = $SVN::Error::handler;
1986 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1987 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1988 $paths =
1989 Git::SVN::Ra::dup_changed_paths($_[0]) });
1990 $SVN::Error::handler = $err_handler;
1992 return undef unless defined $paths;
1994 # look for a parent from another branch:
1995 my @b_path_components = split m#/#, $self->rel_path;
1996 my @a_path_components;
1997 my $i;
1998 while (@b_path_components) {
1999 $i = $paths->{'/'.join('/', @b_path_components)};
2000 last if $i && defined $i->{copyfrom_path};
2001 unshift(@a_path_components, pop(@b_path_components));
2003 return undef unless defined $i && defined $i->{copyfrom_path};
2004 my $branch_from = $i->{copyfrom_path};
2005 if (@a_path_components) {
2006 print STDERR "branch_from: $branch_from => ";
2007 $branch_from .= '/'.join('/', @a_path_components);
2008 print STDERR $branch_from, "\n";
2010 my $r = $i->{copyfrom_rev};
2011 my $repos_root = $self->ra->{repos_root};
2012 my $url = $self->ra->{url};
2013 my $new_url = $repos_root . $branch_from;
2014 print STDERR "Found possible branch point: ",
2015 "$new_url => ", $self->full_url, ", $r\n";
2016 $branch_from =~ s#^/##;
2017 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2018 unless ($gs) {
2019 my $ref_id = $self->{ref_id};
2020 $ref_id =~ s/\@\d+$//;
2021 $ref_id .= "\@$r";
2022 # just grow a tail if we're not unique enough :x
2023 $ref_id .= '-' while find_ref($ref_id);
2024 print STDERR "Initializing parent: $ref_id\n";
2025 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
2027 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2028 if (!defined $r0 || !defined $parent) {
2029 my ($base, $head) = parse_revision_argument(0, $r);
2030 if ($base <= $r) {
2031 $gs->fetch($base, $r);
2033 ($r0, $parent) = $gs->last_rev_commit;
2035 if (defined $r0 && defined $parent) {
2036 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2037 my $ed;
2038 if ($self->ra->can_do_switch) {
2039 $self->assert_index_clean($parent);
2040 print STDERR "Following parent with do_switch\n";
2041 # do_switch works with svn/trunk >= r22312, but that
2042 # is not included with SVN 1.4.3 (the latest version
2043 # at the moment), so we can't rely on it
2044 $self->{last_commit} = $parent;
2045 $ed = SVN::Git::Fetcher->new($self);
2046 $gs->ra->gs_do_switch($r0, $rev, $gs,
2047 $self->full_url, $ed)
2048 or die "SVN connection failed somewhere...\n";
2049 } elsif ($self->ra->trees_match($new_url, $r0,
2050 $self->full_url, $rev)) {
2051 print STDERR "Trees match:\n",
2052 " $new_url\@$r0\n",
2053 " ${\$self->full_url}\@$rev\n",
2054 "Following parent with no changes\n";
2055 $self->tmp_index_do(sub {
2056 command_noisy('read-tree', $parent);
2058 $self->{last_commit} = $parent;
2059 } else {
2060 print STDERR "Following parent with do_update\n";
2061 $ed = SVN::Git::Fetcher->new($self);
2062 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2063 or die "SVN connection failed somewhere...\n";
2065 print STDERR "Successfully followed parent\n";
2066 return $self->make_log_entry($rev, [$parent], $ed);
2068 return undef;
2071 sub do_fetch {
2072 my ($self, $paths, $rev) = @_;
2073 my $ed;
2074 my ($last_rev, @parents);
2075 if (my $lc = $self->last_commit) {
2076 # we can have a branch that was deleted, then re-added
2077 # under the same name but copied from another path, in
2078 # which case we'll have multiple parents (we don't
2079 # want to break the original ref, nor lose copypath info):
2080 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2081 push @{$log_entry->{parents}}, $lc;
2082 return $log_entry;
2084 $ed = SVN::Git::Fetcher->new($self);
2085 $last_rev = $self->{last_rev};
2086 $ed->{c} = $lc;
2087 @parents = ($lc);
2088 } else {
2089 $last_rev = $rev;
2090 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2091 return $log_entry;
2093 $ed = SVN::Git::Fetcher->new($self);
2095 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2096 die "SVN connection failed somewhere...\n";
2098 $self->make_log_entry($rev, \@parents, $ed);
2101 sub get_untracked {
2102 my ($self, $ed) = @_;
2103 my @out;
2104 my $h = $ed->{empty};
2105 foreach (sort keys %$h) {
2106 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2107 push @out, " $act: " . uri_encode($_);
2108 warn "W: $act: $_\n";
2110 foreach my $t (qw/dir_prop file_prop/) {
2111 $h = $ed->{$t} or next;
2112 foreach my $path (sort keys %$h) {
2113 my $ppath = $path eq '' ? '.' : $path;
2114 foreach my $prop (sort keys %{$h->{$path}}) {
2115 next if $SKIP_PROP{$prop};
2116 my $v = $h->{$path}->{$prop};
2117 my $t_ppath_prop = "$t: " .
2118 uri_encode($ppath) . ' ' .
2119 uri_encode($prop);
2120 if (defined $v) {
2121 push @out, " +$t_ppath_prop " .
2122 uri_encode($v);
2123 } else {
2124 push @out, " -$t_ppath_prop";
2129 foreach my $t (qw/absent_file absent_directory/) {
2130 $h = $ed->{$t} or next;
2131 foreach my $parent (sort keys %$h) {
2132 foreach my $path (sort @{$h->{$parent}}) {
2133 push @out, " $t: " .
2134 uri_encode("$parent/$path");
2135 warn "W: $t: $parent/$path ",
2136 "Insufficient permissions?\n";
2140 \@out;
2143 sub parse_svn_date {
2144 my $date = shift || return '+0000 1970-01-01 00:00:00';
2145 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2146 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2147 croak "Unable to parse date: $date\n";
2148 "+0000 $Y-$m-$d $H:$M:$S";
2151 sub check_author {
2152 my ($author) = @_;
2153 if (!defined $author || length $author == 0) {
2154 $author = '(no author)';
2156 if (defined $::_authors && ! defined $::users{$author}) {
2157 die "Author: $author not defined in $::_authors file\n";
2159 $author;
2162 sub make_log_entry {
2163 my ($self, $rev, $parents, $ed) = @_;
2164 my $untracked = $self->get_untracked($ed);
2166 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2167 print $un "r$rev\n" or croak $!;
2168 print $un $_, "\n" foreach @$untracked;
2169 my %log_entry = ( parents => $parents || [], revision => $rev,
2170 log => '');
2172 my $headrev;
2173 my $logged = delete $self->{logged_rev_props};
2174 if (!$logged || $self->{-want_revprops}) {
2175 my $rp = $self->ra->rev_proplist($rev);
2176 foreach (sort keys %$rp) {
2177 my $v = $rp->{$_};
2178 if (/^svn:(author|date|log)$/) {
2179 $log_entry{$1} = $v;
2180 } elsif ($_ eq 'svm:headrev') {
2181 $headrev = $v;
2182 } else {
2183 print $un " rev_prop: ", uri_encode($_), ' ',
2184 uri_encode($v), "\n";
2187 } else {
2188 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2190 close $un or croak $!;
2192 $log_entry{date} = parse_svn_date($log_entry{date});
2193 $log_entry{log} .= "\n";
2194 my $author = $log_entry{author} = check_author($log_entry{author});
2195 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2196 : ($author, undef);
2197 if (defined $headrev && $self->use_svm_props) {
2198 if ($self->rewrite_root) {
2199 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2200 "options set!\n";
2202 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2203 # we don't want "SVM: initializing mirror for junk" ...
2204 return undef if $r == 0;
2205 my $svm = $self->svm;
2206 if ($uuid ne $svm->{uuid}) {
2207 die "UUID mismatch on SVM path:\n",
2208 "expected: $svm->{uuid}\n",
2209 " got: $uuid\n";
2211 my $full_url = $self->full_url;
2212 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2213 die "Failed to replace '$svm->{replace}' with ",
2214 "'$svm->{source}' in $full_url\n";
2215 # throw away username for storing in records
2216 remove_username($full_url);
2217 $log_entry{metadata} = "$full_url\@$r $uuid";
2218 $log_entry{svm_revision} = $r;
2219 $email ||= "$author\@$uuid"
2220 } elsif ($self->use_svnsync_props) {
2221 my $full_url = $self->svnsync->{url};
2222 $full_url .= "/$self->{path}" if length $self->{path};
2223 remove_username($full_url);
2224 my $uuid = $self->svnsync->{uuid};
2225 $log_entry{metadata} = "$full_url\@$rev $uuid";
2226 $email ||= "$author\@$uuid"
2227 } else {
2228 my $url = $self->metadata_url;
2229 remove_username($url);
2230 $log_entry{metadata} = "$url\@$rev " .
2231 $self->ra->get_uuid;
2232 $email ||= "$author\@" . $self->ra->get_uuid;
2234 $log_entry{name} = $name;
2235 $log_entry{email} = $email;
2236 \%log_entry;
2239 sub fetch {
2240 my ($self, $min_rev, $max_rev, @parents) = @_;
2241 my ($last_rev, $last_commit) = $self->last_rev_commit;
2242 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2243 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2246 sub set_tree_cb {
2247 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2248 $self->{inject_parents} = { $rev => $tree };
2249 $self->fetch(undef, undef);
2252 sub set_tree {
2253 my ($self, $tree) = (shift, shift);
2254 my $log_entry = ::get_commit_entry($tree);
2255 unless ($self->{last_rev}) {
2256 fatal("Must have an existing revision to commit");
2258 my %ed_opts = ( r => $self->{last_rev},
2259 log => $log_entry->{log},
2260 ra => $self->ra,
2261 tree_a => $self->{last_commit},
2262 tree_b => $tree,
2263 editor_cb => sub {
2264 $self->set_tree_cb($log_entry, $tree, @_) },
2265 svn_path => $self->{path} );
2266 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2267 print "No changes\nr$self->{last_rev} = $tree\n";
2271 sub rebuild {
2272 my ($self) = @_;
2273 my $db_path = $self->db_path;
2274 return if (-e $db_path && ! -z $db_path);
2275 return unless ::verify_ref($self->refname.'^0');
2276 if (-f $self->{db_root}) {
2277 rename $self->{db_root}, $db_path or die
2278 "rename $self->{db_root} => $db_path failed: $!\n";
2279 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2280 symlink $base, $self->{db_root} or die
2281 "symlink $base => $self->{db_root} failed: $!\n";
2282 return;
2284 print "Rebuilding $db_path ...\n";
2285 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2286 my $latest;
2287 my $full_url = $self->full_url;
2288 remove_username($full_url);
2289 my $svn_uuid;
2290 my $c;
2291 while (<$log>) {
2292 if ( m{^commit ($::sha1)$} ) {
2293 $c = $1;
2294 next;
2296 next unless s{^\s*(git-svn-id:)}{$1};
2297 my ($url, $rev, $uuid) = ::extract_metadata($_);
2298 remove_username($url);
2300 # ignore merges (from set-tree)
2301 next if (!defined $rev || !$uuid);
2303 # if we merged or otherwise started elsewhere, this is
2304 # how we break out of it
2305 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2306 ($full_url && $url && ($url ne $full_url))) {
2307 next;
2309 $latest ||= $rev;
2310 $svn_uuid ||= $uuid;
2312 $self->rev_db_set($rev, $c);
2313 print "r$rev = $c\n";
2315 command_close_pipe($log, $ctx);
2316 print "Done rebuilding $db_path\n";
2319 # rev_db:
2320 # Tie::File seems to be prone to offset errors if revisions get sparse,
2321 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2322 # one of my favorite modules is out :< Next up would be one of the DBM
2323 # modules, but I'm not sure which is most portable... So I'll just
2324 # go with something that's plain-text, but still capable of
2325 # being randomly accessed. So here's my ultra-simple fixed-width
2326 # database. All records are 40 characters + "\n", so it's easy to seek
2327 # to a revision: (41 * rev) is the byte offset.
2328 # A record of 40 0s denotes an empty revision.
2329 # And yes, it's still pretty fast (faster than Tie::File).
2330 # These files are disposable unless noMetadata or useSvmProps is set
2332 sub _rev_db_set {
2333 my ($fh, $rev, $commit) = @_;
2334 my $offset = $rev * 41;
2335 # assume that append is the common case:
2336 seek $fh, 0, 2 or croak $!;
2337 my $pos = tell $fh;
2338 if ($pos < $offset) {
2339 for (1 .. (($offset - $pos) / 41)) {
2340 print $fh (('0' x 40),"\n") or croak $!;
2343 seek $fh, $offset, 0 or croak $!;
2344 print $fh $commit,"\n" or croak $!;
2347 sub mkfile {
2348 my ($path) = @_;
2349 unless (-e $path) {
2350 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2351 mkpath([$dir]) unless -d $dir;
2352 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2353 close $fh or die "Couldn't close (create) $path: $!\n";
2357 sub rev_db_set {
2358 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2359 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2360 my $db = $self->db_path($uuid);
2361 my $db_lock = "$db.lock";
2362 my $sig;
2363 if ($update_ref) {
2364 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2365 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2367 mkfile($db);
2369 $LOCKFILES{$db_lock} = 1;
2370 my $sync;
2371 # both of these options make our .rev_db file very, very important
2372 # and we can't afford to lose it because rebuild() won't work
2373 if ($self->use_svm_props || $self->no_metadata) {
2374 $sync = 1;
2375 copy($db, $db_lock) or die "rev_db_set(@_): ",
2376 "Failed to copy: ",
2377 "$db => $db_lock ($!)\n";
2378 } else {
2379 rename $db, $db_lock or die "rev_db_set(@_): ",
2380 "Failed to rename: ",
2381 "$db => $db_lock ($!)\n";
2383 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2384 _rev_db_set($fh, $rev, $commit);
2385 if ($sync) {
2386 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2387 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2389 close $fh or croak $!;
2390 if ($update_ref) {
2391 $_head = $self;
2392 command_noisy('update-ref', '-m', "r$rev",
2393 $self->refname, $commit);
2395 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2396 "$db_lock => $db ($!)\n";
2397 delete $LOCKFILES{$db_lock};
2398 if ($update_ref) {
2399 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2400 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2401 kill $sig, $$ if defined $sig;
2405 sub rev_db_max {
2406 my ($self) = @_;
2407 $self->rebuild;
2408 my $db_path = $self->db_path;
2409 my @stat = stat $db_path or return 0;
2410 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2411 my $max = $stat[7] / 41;
2412 (($max > 0) ? $max - 1 : 0);
2415 sub rev_db_get {
2416 my ($self, $rev, $uuid) = @_;
2417 my $ret;
2418 my $offset = $rev * 41;
2419 my $db_path = $self->db_path($uuid);
2420 return undef unless -e $db_path;
2421 open my $fh, '<', $db_path or croak $!;
2422 if (sysseek($fh, $offset, 0) == $offset) {
2423 my $read = sysread($fh, $ret, 40);
2424 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2426 close $fh or croak $!;
2427 $ret;
2430 # Finds the first svn revision that exists on (if $eq_ok is true) or
2431 # before $rev for the current branch. It will not search any lower
2432 # than $min_rev. Returns the git commit hash and svn revision number
2433 # if found, else (undef, undef).
2434 sub find_rev_before {
2435 my ($self, $rev, $eq_ok, $min_rev) = @_;
2436 --$rev unless $eq_ok;
2437 $min_rev ||= 1;
2438 while ($rev >= $min_rev) {
2439 if (my $c = $self->rev_db_get($rev)) {
2440 return ($rev, $c);
2442 --$rev;
2444 return (undef, undef);
2447 # Finds the first svn revision that exists on (if $eq_ok is true) or
2448 # after $rev for the current branch. It will not search any higher
2449 # than $max_rev. Returns the git commit hash and svn revision number
2450 # if found, else (undef, undef).
2451 sub find_rev_after {
2452 my ($self, $rev, $eq_ok, $max_rev) = @_;
2453 ++$rev unless $eq_ok;
2454 $max_rev ||= $self->rev_db_max();
2455 while ($rev <= $max_rev) {
2456 if (my $c = $self->rev_db_get($rev)) {
2457 return ($rev, $c);
2459 ++$rev;
2461 return (undef, undef);
2464 sub _new {
2465 my ($class, $repo_id, $ref_id, $path) = @_;
2466 unless (defined $repo_id && length $repo_id) {
2467 $repo_id = $Git::SVN::default_repo_id;
2469 unless (defined $ref_id && length $ref_id) {
2470 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2472 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2473 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2474 $_[3] = $path = '' unless (defined $path);
2475 mkpath(["$ENV{GIT_DIR}/svn"]);
2476 bless {
2477 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2478 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2479 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2482 sub db_path {
2483 my ($self, $uuid) = @_;
2484 $uuid ||= $self->ra_uuid;
2485 "$self->{db_root}.$uuid";
2488 sub uri_encode {
2489 my ($f) = @_;
2490 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2494 sub remove_username {
2495 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2498 package Git::SVN::Prompt;
2499 use strict;
2500 use warnings;
2501 require SVN::Core;
2502 use vars qw/$_no_auth_cache $_username/;
2504 sub simple {
2505 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2506 $may_save = undef if $_no_auth_cache;
2507 $default_username = $_username if defined $_username;
2508 if (defined $default_username && length $default_username) {
2509 if (defined $realm && length $realm) {
2510 print STDERR "Authentication realm: $realm\n";
2511 STDERR->flush;
2513 $cred->username($default_username);
2514 } else {
2515 username($cred, $realm, $may_save, $pool);
2517 $cred->password(_read_password("Password for '" .
2518 $cred->username . "': ", $realm));
2519 $cred->may_save($may_save);
2520 $SVN::_Core::SVN_NO_ERROR;
2523 sub ssl_server_trust {
2524 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2525 $may_save = undef if $_no_auth_cache;
2526 print STDERR "Error validating server certificate for '$realm':\n";
2528 no warnings 'once';
2529 # All variables SVN::Auth::SSL::* are used only once,
2530 # so we're shutting up Perl warnings about this.
2531 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2532 print STDERR " - The certificate is not issued ",
2533 "by a trusted authority. Use the\n",
2534 " fingerprint to validate ",
2535 "the certificate manually!\n";
2537 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2538 print STDERR " - The certificate hostname ",
2539 "does not match.\n";
2541 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2542 print STDERR " - The certificate is not yet valid.\n";
2544 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2545 print STDERR " - The certificate has expired.\n";
2547 if ($failures & $SVN::Auth::SSL::OTHER) {
2548 print STDERR " - The certificate has ",
2549 "an unknown error.\n";
2551 } # no warnings 'once'
2552 printf STDERR
2553 "Certificate information:\n".
2554 " - Hostname: %s\n".
2555 " - Valid: from %s until %s\n".
2556 " - Issuer: %s\n".
2557 " - Fingerprint: %s\n",
2558 map $cert_info->$_, qw(hostname valid_from valid_until
2559 issuer_dname fingerprint);
2560 my $choice;
2561 prompt:
2562 print STDERR $may_save ?
2563 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2564 "(R)eject or accept (t)emporarily? ";
2565 STDERR->flush;
2566 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2567 if ($choice =~ /^t$/i) {
2568 $cred->may_save(undef);
2569 } elsif ($choice =~ /^r$/i) {
2570 return -1;
2571 } elsif ($may_save && $choice =~ /^p$/i) {
2572 $cred->may_save($may_save);
2573 } else {
2574 goto prompt;
2576 $cred->accepted_failures($failures);
2577 $SVN::_Core::SVN_NO_ERROR;
2580 sub ssl_client_cert {
2581 my ($cred, $realm, $may_save, $pool) = @_;
2582 $may_save = undef if $_no_auth_cache;
2583 print STDERR "Client certificate filename: ";
2584 STDERR->flush;
2585 chomp(my $filename = <STDIN>);
2586 $cred->cert_file($filename);
2587 $cred->may_save($may_save);
2588 $SVN::_Core::SVN_NO_ERROR;
2591 sub ssl_client_cert_pw {
2592 my ($cred, $realm, $may_save, $pool) = @_;
2593 $may_save = undef if $_no_auth_cache;
2594 $cred->password(_read_password("Password: ", $realm));
2595 $cred->may_save($may_save);
2596 $SVN::_Core::SVN_NO_ERROR;
2599 sub username {
2600 my ($cred, $realm, $may_save, $pool) = @_;
2601 $may_save = undef if $_no_auth_cache;
2602 if (defined $realm && length $realm) {
2603 print STDERR "Authentication realm: $realm\n";
2605 my $username;
2606 if (defined $_username) {
2607 $username = $_username;
2608 } else {
2609 print STDERR "Username: ";
2610 STDERR->flush;
2611 chomp($username = <STDIN>);
2613 $cred->username($username);
2614 $cred->may_save($may_save);
2615 $SVN::_Core::SVN_NO_ERROR;
2618 sub _read_password {
2619 my ($prompt, $realm) = @_;
2620 print STDERR $prompt;
2621 STDERR->flush;
2622 require Term::ReadKey;
2623 Term::ReadKey::ReadMode('noecho');
2624 my $password = '';
2625 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2626 last if $key =~ /[\012\015]/; # \n\r
2627 $password .= $key;
2629 Term::ReadKey::ReadMode('restore');
2630 print STDERR "\n";
2631 STDERR->flush;
2632 $password;
2635 package SVN::Git::Fetcher;
2636 use vars qw/@ISA/;
2637 use strict;
2638 use warnings;
2639 use Carp qw/croak/;
2640 use IO::File qw//;
2642 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2643 sub new {
2644 my ($class, $git_svn) = @_;
2645 my $self = SVN::Delta::Editor->new;
2646 bless $self, $class;
2647 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2648 $self->{empty} = {};
2649 $self->{dir_prop} = {};
2650 $self->{file_prop} = {};
2651 $self->{absent_dir} = {};
2652 $self->{absent_file} = {};
2653 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2654 $self;
2657 sub set_path_strip {
2658 my ($self, $path) = @_;
2659 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2662 sub open_root {
2663 { path => '' };
2666 sub open_directory {
2667 my ($self, $path, $pb, $rev) = @_;
2668 { path => $path };
2671 sub git_path {
2672 my ($self, $path) = @_;
2673 if ($self->{path_strip}) {
2674 $path =~ s!$self->{path_strip}!! or
2675 die "Failed to strip path '$path' ($self->{path_strip})\n";
2677 $path;
2680 sub delete_entry {
2681 my ($self, $path, $rev, $pb) = @_;
2683 my $gpath = $self->git_path($path);
2684 return undef if ($gpath eq '');
2686 # remove entire directories.
2687 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2688 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2689 -r --name-only -z/,
2690 $self->{c}, '--', $gpath);
2691 local $/ = "\0";
2692 while (<$ls>) {
2693 chomp;
2694 $self->{gii}->remove($_);
2695 print "\tD\t$_\n" unless $::_q;
2697 print "\tD\t$gpath/\n" unless $::_q;
2698 command_close_pipe($ls, $ctx);
2699 $self->{empty}->{$path} = 0
2700 } else {
2701 $self->{gii}->remove($gpath);
2702 print "\tD\t$gpath\n" unless $::_q;
2704 undef;
2707 sub open_file {
2708 my ($self, $path, $pb, $rev) = @_;
2709 my $gpath = $self->git_path($path);
2710 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2711 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2712 unless (defined $mode && defined $blob) {
2713 die "$path was not found in commit $self->{c} (r$rev)\n";
2715 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2716 pool => SVN::Pool->new, action => 'M' };
2719 sub add_file {
2720 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2721 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2722 delete $self->{empty}->{$dir};
2723 { path => $path, mode_a => 100644, mode_b => 100644,
2724 pool => SVN::Pool->new, action => 'A' };
2727 sub add_directory {
2728 my ($self, $path, $cp_path, $cp_rev) = @_;
2729 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2730 delete $self->{empty}->{$dir};
2731 $self->{empty}->{$path} = 1;
2732 { path => $path };
2735 sub change_dir_prop {
2736 my ($self, $db, $prop, $value) = @_;
2737 $self->{dir_prop}->{$db->{path}} ||= {};
2738 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2739 undef;
2742 sub absent_directory {
2743 my ($self, $path, $pb) = @_;
2744 $self->{absent_dir}->{$pb->{path}} ||= [];
2745 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2746 undef;
2749 sub absent_file {
2750 my ($self, $path, $pb) = @_;
2751 $self->{absent_file}->{$pb->{path}} ||= [];
2752 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2753 undef;
2756 sub change_file_prop {
2757 my ($self, $fb, $prop, $value) = @_;
2758 if ($prop eq 'svn:executable') {
2759 if ($fb->{mode_b} != 120000) {
2760 $fb->{mode_b} = defined $value ? 100755 : 100644;
2762 } elsif ($prop eq 'svn:special') {
2763 $fb->{mode_b} = defined $value ? 120000 : 100644;
2764 } else {
2765 $self->{file_prop}->{$fb->{path}} ||= {};
2766 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2768 undef;
2771 sub apply_textdelta {
2772 my ($self, $fb, $exp) = @_;
2773 my $fh = IO::File->new_tmpfile;
2774 $fh->autoflush(1);
2775 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2776 # (but $base does not,) so dup() it for reading in close_file
2777 open my $dup, '<&', $fh or croak $!;
2778 my $base = IO::File->new_tmpfile;
2779 $base->autoflush(1);
2780 if ($fb->{blob}) {
2781 defined (my $pid = fork) or croak $!;
2782 if (!$pid) {
2783 open STDOUT, '>&', $base or croak $!;
2784 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2785 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2787 waitpid $pid, 0;
2788 croak $? if $?;
2790 if (defined $exp) {
2791 seek $base, 0, 0 or croak $!;
2792 my $got = Git::SVN::Util::md5sum($base);
2793 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2794 "expected: $exp\n",
2795 " got: $got\n" if ($got ne $exp);
2798 seek $base, 0, 0 or croak $!;
2799 $fb->{fh} = $dup;
2800 $fb->{base} = $base;
2801 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2804 sub close_file {
2805 my ($self, $fb, $exp) = @_;
2806 my $hash;
2807 my $path = $self->git_path($fb->{path});
2808 if (my $fh = $fb->{fh}) {
2809 if (defined $exp) {
2810 seek($fh, 0, 0) or croak $!;
2811 my $got = Git::SVN::Util::md5sum($fh);
2812 if ($got ne $exp) {
2813 die "Checksum mismatch: $path\n",
2814 "expected: $exp\n got: $got\n";
2817 sysseek($fh, 0, 0) or croak $!;
2818 if ($fb->{mode_b} == 120000) {
2819 sysread($fh, my $buf, 5) == 5 or croak $!;
2820 $buf eq 'link ' or die "$path has mode 120000",
2821 "but is not a link\n";
2823 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2824 if (!$pid) {
2825 open STDIN, '<&', $fh or croak $!;
2826 exec qw/git-hash-object -w --stdin/ or croak $!;
2828 chomp($hash = do { local $/; <$out> });
2829 close $out or croak $!;
2830 close $fh or croak $!;
2831 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2832 close $fb->{base} or croak $!;
2833 } else {
2834 $hash = $fb->{blob} or die "no blob information\n";
2836 $fb->{pool}->clear;
2837 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2838 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2839 undef;
2842 sub abort_edit {
2843 my $self = shift;
2844 $self->{nr} = $self->{gii}->{nr};
2845 delete $self->{gii};
2846 $self->SUPER::abort_edit(@_);
2849 sub close_edit {
2850 my $self = shift;
2851 $self->{git_commit_ok} = 1;
2852 $self->{nr} = $self->{gii}->{nr};
2853 delete $self->{gii};
2854 $self->SUPER::close_edit(@_);
2857 package SVN::Git::Editor;
2858 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2859 use strict;
2860 use warnings;
2861 use Carp qw/croak/;
2862 use IO::File;
2864 sub new {
2865 my ($class, $opts) = @_;
2866 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2867 die "$_ required!\n" unless (defined $opts->{$_});
2870 my $pool = SVN::Pool->new;
2871 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2872 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2873 $opts->{r}, $mods);
2875 # $opts->{ra} functions should not be used after this:
2876 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2877 $opts->{editor_cb}, $pool);
2878 my $self = SVN::Delta::Editor->new(@ce, $pool);
2879 bless $self, $class;
2880 foreach (qw/svn_path r tree_a tree_b/) {
2881 $self->{$_} = $opts->{$_};
2883 $self->{url} = $opts->{ra}->{url};
2884 $self->{mods} = $mods;
2885 $self->{types} = $types;
2886 $self->{pool} = $pool;
2887 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2888 $self->{rm} = { };
2889 $self->{path_prefix} = length $self->{svn_path} ?
2890 "$self->{svn_path}/" : '';
2891 return $self;
2894 sub generate_diff {
2895 my ($tree_a, $tree_b) = @_;
2896 my @diff_tree = qw(diff-tree -z -r);
2897 if ($_cp_similarity) {
2898 push @diff_tree, "-C$_cp_similarity";
2899 } else {
2900 push @diff_tree, '-C';
2902 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2903 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2904 push @diff_tree, $tree_a, $tree_b;
2905 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2906 local $/ = "\0";
2907 my $state = 'meta';
2908 my @mods;
2909 while (<$diff_fh>) {
2910 chomp $_; # this gets rid of the trailing "\0"
2911 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2912 $::sha1\s($::sha1)\s
2913 ([MTCRAD])\d*$/xo) {
2914 push @mods, { mode_a => $1, mode_b => $2,
2915 sha1_b => $3, chg => $4 };
2916 if ($4 =~ /^(?:C|R)$/) {
2917 $state = 'file_a';
2918 } else {
2919 $state = 'file_b';
2921 } elsif ($state eq 'file_a') {
2922 my $x = $mods[$#mods] or croak "Empty array\n";
2923 if ($x->{chg} !~ /^(?:C|R)$/) {
2924 croak "Error parsing $_, $x->{chg}\n";
2926 $x->{file_a} = $_;
2927 $state = 'file_b';
2928 } elsif ($state eq 'file_b') {
2929 my $x = $mods[$#mods] or croak "Empty array\n";
2930 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2931 croak "Error parsing $_, $x->{chg}\n";
2933 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2934 croak "Error parsing $_, $x->{chg}\n";
2936 $x->{file_b} = $_;
2937 $state = 'meta';
2938 } else {
2939 croak "Error parsing $_\n";
2942 command_close_pipe($diff_fh, $ctx);
2943 \@mods;
2946 sub check_diff_paths {
2947 my ($ra, $pfx, $rev, $mods) = @_;
2948 my %types;
2949 $pfx .= '/' if length $pfx;
2951 sub type_diff_paths {
2952 my ($ra, $types, $path, $rev) = @_;
2953 my @p = split m#/+#, $path;
2954 my $c = shift @p;
2955 unless (defined $types->{$c}) {
2956 $types->{$c} = $ra->check_path($c, $rev);
2958 while (@p) {
2959 $c .= '/' . shift @p;
2960 next if defined $types->{$c};
2961 $types->{$c} = $ra->check_path($c, $rev);
2965 foreach my $m (@$mods) {
2966 foreach my $f (qw/file_a file_b/) {
2967 next unless defined $m->{$f};
2968 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2969 if (length $pfx.$dir && ! defined $types{$dir}) {
2970 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2974 \%types;
2977 sub split_path {
2978 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2981 sub repo_path {
2982 my ($self, $path) = @_;
2983 $self->{path_prefix}.(defined $path ? $path : '');
2986 sub url_path {
2987 my ($self, $path) = @_;
2988 if ($self->{url} =~ m#^https?://#) {
2989 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2991 $self->{url} . '/' . $self->repo_path($path);
2994 sub rmdirs {
2995 my ($self) = @_;
2996 my $rm = $self->{rm};
2997 delete $rm->{''}; # we never delete the url we're tracking
2998 return unless %$rm;
3000 foreach (keys %$rm) {
3001 my @d = split m#/#, $_;
3002 my $c = shift @d;
3003 $rm->{$c} = 1;
3004 while (@d) {
3005 $c .= '/' . shift @d;
3006 $rm->{$c} = 1;
3009 delete $rm->{$self->{svn_path}};
3010 delete $rm->{''}; # we never delete the url we're tracking
3011 return unless %$rm;
3013 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3014 $self->{tree_b});
3015 local $/ = "\0";
3016 while (<$fh>) {
3017 chomp;
3018 my @dn = split m#/#, $_;
3019 while (pop @dn) {
3020 delete $rm->{join '/', @dn};
3022 unless (%$rm) {
3023 close $fh;
3024 return;
3027 command_close_pipe($fh, $ctx);
3029 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3030 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3031 $self->close_directory($bat->{$d}, $p);
3032 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3033 print "\tD+\t$d/\n" unless $::_q;
3034 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3035 delete $bat->{$d};
3039 sub open_or_add_dir {
3040 my ($self, $full_path, $baton) = @_;
3041 my $t = $self->{types}->{$full_path};
3042 if (!defined $t) {
3043 die "$full_path not known in r$self->{r} or we have a bug!\n";
3046 no warnings 'once';
3047 # SVN::Node::none and SVN::Node::file are used only once,
3048 # so we're shutting up Perl's warnings about them.
3049 if ($t == $SVN::Node::none) {
3050 return $self->add_directory($full_path, $baton,
3051 undef, -1, $self->{pool});
3052 } elsif ($t == $SVN::Node::dir) {
3053 return $self->open_directory($full_path, $baton,
3054 $self->{r}, $self->{pool});
3055 } # no warnings 'once'
3056 print STDERR "$full_path already exists in repository at ",
3057 "r$self->{r} and it is not a directory (",
3058 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3059 } # no warnings 'once'
3060 exit 1;
3063 sub ensure_path {
3064 my ($self, $path) = @_;
3065 my $bat = $self->{bat};
3066 my $repo_path = $self->repo_path($path);
3067 return $bat->{''} unless (length $repo_path);
3068 my @p = split m#/+#, $repo_path;
3069 my $c = shift @p;
3070 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3071 while (@p) {
3072 my $c0 = $c;
3073 $c .= '/' . shift @p;
3074 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3076 return $bat->{$c};
3079 sub A {
3080 my ($self, $m) = @_;
3081 my ($dir, $file) = split_path($m->{file_b});
3082 my $pbat = $self->ensure_path($dir);
3083 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3084 undef, -1);
3085 print "\tA\t$m->{file_b}\n" unless $::_q;
3086 $self->chg_file($fbat, $m);
3087 $self->close_file($fbat,undef,$self->{pool});
3090 sub C {
3091 my ($self, $m) = @_;
3092 my ($dir, $file) = split_path($m->{file_b});
3093 my $pbat = $self->ensure_path($dir);
3094 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3095 $self->url_path($m->{file_a}), $self->{r});
3096 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3097 $self->chg_file($fbat, $m);
3098 $self->close_file($fbat,undef,$self->{pool});
3101 sub delete_entry {
3102 my ($self, $path, $pbat) = @_;
3103 my $rpath = $self->repo_path($path);
3104 my ($dir, $file) = split_path($rpath);
3105 $self->{rm}->{$dir} = 1;
3106 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3109 sub R {
3110 my ($self, $m) = @_;
3111 my ($dir, $file) = split_path($m->{file_b});
3112 my $pbat = $self->ensure_path($dir);
3113 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3114 $self->url_path($m->{file_a}), $self->{r});
3115 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3116 $self->chg_file($fbat, $m);
3117 $self->close_file($fbat,undef,$self->{pool});
3119 ($dir, $file) = split_path($m->{file_a});
3120 $pbat = $self->ensure_path($dir);
3121 $self->delete_entry($m->{file_a}, $pbat);
3124 sub M {
3125 my ($self, $m) = @_;
3126 my ($dir, $file) = split_path($m->{file_b});
3127 my $pbat = $self->ensure_path($dir);
3128 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3129 $pbat,$self->{r},$self->{pool});
3130 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3131 $self->chg_file($fbat, $m);
3132 $self->close_file($fbat,undef,$self->{pool});
3135 sub T { shift->M(@_) }
3137 sub change_file_prop {
3138 my ($self, $fbat, $pname, $pval) = @_;
3139 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3142 sub chg_file {
3143 my ($self, $fbat, $m) = @_;
3144 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3145 $self->change_file_prop($fbat,'svn:executable','*');
3146 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3147 $self->change_file_prop($fbat,'svn:executable',undef);
3149 my $fh = IO::File->new_tmpfile or croak $!;
3150 if ($m->{mode_b} =~ /^120/) {
3151 print $fh 'link ' or croak $!;
3152 $self->change_file_prop($fbat,'svn:special','*');
3153 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3154 $self->change_file_prop($fbat,'svn:special',undef);
3156 defined(my $pid = fork) or croak $!;
3157 if (!$pid) {
3158 open STDOUT, '>&', $fh or croak $!;
3159 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3161 waitpid $pid, 0;
3162 croak $? if $?;
3163 $fh->flush == 0 or croak $!;
3164 seek $fh, 0, 0 or croak $!;
3166 my $exp = Git::SVN::Util::md5sum($fh);
3167 seek $fh, 0, 0 or croak $!;
3169 my $pool = SVN::Pool->new;
3170 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3171 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3172 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3173 $pool->clear;
3175 close $fh or croak $!;
3178 sub D {
3179 my ($self, $m) = @_;
3180 my ($dir, $file) = split_path($m->{file_b});
3181 my $pbat = $self->ensure_path($dir);
3182 print "\tD\t$m->{file_b}\n" unless $::_q;
3183 $self->delete_entry($m->{file_b}, $pbat);
3186 sub close_edit {
3187 my ($self) = @_;
3188 my ($p,$bat) = ($self->{pool}, $self->{bat});
3189 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3190 next if $_ eq '';
3191 $self->close_directory($bat->{$_}, $p);
3193 $self->close_directory($bat->{''}, $p);
3194 $self->SUPER::close_edit($p);
3195 $p->clear;
3198 sub abort_edit {
3199 my ($self) = @_;
3200 $self->SUPER::abort_edit($self->{pool});
3203 sub DESTROY {
3204 my $self = shift;
3205 $self->SUPER::DESTROY(@_);
3206 $self->{pool}->clear;
3209 # this drives the editor
3210 sub apply_diff {
3211 my ($self) = @_;
3212 my $mods = $self->{mods};
3213 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3214 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3215 my $f = $m->{chg};
3216 if (defined $o{$f}) {
3217 $self->$f($m);
3218 } else {
3219 fatal("Invalid change type: $f");
3222 $self->rmdirs if $_rmdir;
3223 if (@$mods == 0) {
3224 $self->abort_edit;
3225 } else {
3226 $self->close_edit;
3228 return scalar @$mods;
3231 package Git::SVN::Ra;
3232 use vars qw/@ISA $config_dir $_log_window_size/;
3233 use strict;
3234 use warnings;
3235 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3237 BEGIN {
3238 # enforce temporary pool usage for some simple functions
3239 no strict 'refs';
3240 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3241 my $SUPER = "SUPER::$f";
3242 *$f = sub {
3243 my $self = shift;
3244 my $pool = SVN::Pool->new;
3245 my @ret = $self->$SUPER(@_,$pool);
3246 $pool->clear;
3247 wantarray ? @ret : $ret[0];
3252 sub _auth_providers () {
3254 SVN::Client::get_simple_provider(),
3255 SVN::Client::get_ssl_server_trust_file_provider(),
3256 SVN::Client::get_simple_prompt_provider(
3257 \&Git::SVN::Prompt::simple, 2),
3258 SVN::Client::get_ssl_client_cert_file_provider(),
3259 SVN::Client::get_ssl_client_cert_prompt_provider(
3260 \&Git::SVN::Prompt::ssl_client_cert, 2),
3261 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3262 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3263 SVN::Client::get_username_provider(),
3264 SVN::Client::get_ssl_server_trust_prompt_provider(
3265 \&Git::SVN::Prompt::ssl_server_trust),
3266 SVN::Client::get_username_prompt_provider(
3267 \&Git::SVN::Prompt::username, 2)
3271 sub escape_uri_only {
3272 my ($uri) = @_;
3273 my @tmp;
3274 foreach (split m{/}, $uri) {
3275 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3276 push @tmp, $_;
3278 join('/', @tmp);
3281 sub escape_url {
3282 my ($url) = @_;
3283 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3284 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3285 $url = "$scheme://$domain$uri";
3287 $url;
3290 sub new {
3291 my ($class, $url) = @_;
3292 $url =~ s!/+$!!;
3293 return $RA if ($RA && $RA->{url} eq $url);
3295 SVN::_Core::svn_config_ensure($config_dir, undef);
3296 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3297 my $config = SVN::Core::config_get_config($config_dir);
3298 $RA = undef;
3299 my $dont_store_passwords = 1;
3300 my $conf_t = ${$config}{'config'};
3302 no warnings 'once';
3303 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3304 # produces warnings that variables are used only once.
3305 # I had not found the better way to shut them up, so
3306 # the warnings of type 'once' are disabled in this block.
3307 if (SVN::_Core::svn_config_get_bool($conf_t,
3308 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3309 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3310 1) == 0) {
3311 SVN::_Core::svn_auth_set_parameter($baton,
3312 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3313 bless (\$dont_store_passwords, "_p_void"));
3315 if (SVN::_Core::svn_config_get_bool($conf_t,
3316 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3317 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3318 1) == 0) {
3319 $Git::SVN::Prompt::_no_auth_cache = 1;
3321 } # no warnings 'once'
3322 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3323 config => $config,
3324 pool => SVN::Pool->new,
3325 auth_provider_callbacks => $callbacks);
3326 $self->{url} = $url;
3327 $self->{svn_path} = $url;
3328 $self->{repos_root} = $self->get_repos_root;
3329 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3330 $self->{cache} = { check_path => { r => 0, data => {} },
3331 get_dir => { r => 0, data => {} } };
3332 $RA = bless $self, $class;
3335 sub check_path {
3336 my ($self, $path, $r) = @_;
3337 my $cache = $self->{cache}->{check_path};
3338 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3339 return $cache->{data}->{$path};
3341 my $pool = SVN::Pool->new;
3342 my $t = $self->SUPER::check_path($path, $r, $pool);
3343 $pool->clear;
3344 if ($r != $cache->{r}) {
3345 %{$cache->{data}} = ();
3346 $cache->{r} = $r;
3348 $cache->{data}->{$path} = $t;
3351 sub get_dir {
3352 my ($self, $dir, $r) = @_;
3353 my $cache = $self->{cache}->{get_dir};
3354 if ($r == $cache->{r}) {
3355 if (my $x = $cache->{data}->{$dir}) {
3356 return wantarray ? @$x : $x->[0];
3359 my $pool = SVN::Pool->new;
3360 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3361 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3362 $pool->clear;
3363 if ($r != $cache->{r}) {
3364 %{$cache->{data}} = ();
3365 $cache->{r} = $r;
3367 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3368 wantarray ? (\%dirents, $r, $props) : \%dirents;
3371 sub DESTROY {
3372 # do not call the real DESTROY since we store ourselves in $RA
3375 sub get_log {
3376 my ($self, @args) = @_;
3377 my $pool = SVN::Pool->new;
3378 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3379 my $ret = $self->SUPER::get_log(@args, $pool);
3380 $pool->clear;
3381 $ret;
3384 sub trees_match {
3385 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3386 my $ctx = SVN::Client->new(auth => _auth_providers);
3387 my $out = IO::File->new_tmpfile;
3389 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3390 # $ctx->diff(), so we'll create a default one
3391 my $pool = SVN::Pool->new_default_sub;
3393 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3394 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3395 $out->flush;
3396 my $ret = (($out->stat)[7] == 0);
3397 close $out or croak $!;
3399 $ret;
3402 sub get_commit_editor {
3403 my ($self, $log, $cb, $pool) = @_;
3404 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3405 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3408 sub gs_do_update {
3409 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3410 my $new = ($rev_a == $rev_b);
3411 my $path = $gs->{path};
3413 if ($new && -e $gs->{index}) {
3414 unlink $gs->{index} or die
3415 "Couldn't unlink index: $gs->{index}: $!\n";
3417 my $pool = SVN::Pool->new;
3418 $editor->set_path_strip($path);
3419 my (@pc) = split m#/#, $path;
3420 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3421 1, $editor, $pool);
3422 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3424 # Since we can't rely on svn_ra_reparent being available, we'll
3425 # just have to do some magic with set_path to make it so
3426 # we only want a partial path.
3427 my $sp = '';
3428 my $final = join('/', @pc);
3429 while (@pc) {
3430 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3431 $sp .= '/' if length $sp;
3432 $sp .= shift @pc;
3434 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3436 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3438 $reporter->finish_report($pool);
3439 $pool->clear;
3440 $editor->{git_commit_ok};
3443 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3444 # svn_ra_reparent didn't work before 1.4)
3445 sub gs_do_switch {
3446 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3447 my $path = $gs->{path};
3448 my $pool = SVN::Pool->new;
3450 my $full_url = $self->{url};
3451 my $old_url = $full_url;
3452 $full_url .= '/' . escape_uri_only($path) if length $path;
3453 my ($ra, $reparented);
3454 if ($old_url ne $full_url) {
3455 if ($old_url !~ m#^svn(\+ssh)?://#) {
3456 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3457 $pool);
3458 $self->{url} = $full_url;
3459 $reparented = 1;
3460 } else {
3461 $_[0] = undef;
3462 $self = undef;
3463 $RA = undef;
3464 $ra = Git::SVN::Ra->new($full_url);
3465 $ra_invalid = 1;
3468 $ra ||= $self;
3469 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3470 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3471 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3472 $reporter->finish_report($pool);
3474 if ($reparented) {
3475 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3476 $self->{url} = $old_url;
3479 $pool->clear;
3480 $editor->{git_commit_ok};
3483 sub longest_common_path {
3484 my ($gsv, $globs) = @_;
3485 my %common;
3486 my $common_max = scalar @$gsv;
3488 foreach my $gs (@$gsv) {
3489 my @tmp = split m#/#, $gs->{path};
3490 my $p = '';
3491 foreach (@tmp) {
3492 $p .= length($p) ? "/$_" : $_;
3493 $common{$p} ||= 0;
3494 $common{$p}++;
3497 $globs ||= [];
3498 $common_max += scalar @$globs;
3499 foreach my $glob (@$globs) {
3500 my @tmp = split m#/#, $glob->{path}->{left};
3501 my $p = '';
3502 foreach (@tmp) {
3503 $p .= length($p) ? "/$_" : $_;
3504 $common{$p} ||= 0;
3505 $common{$p}++;
3509 my $longest_path = '';
3510 foreach (sort {length $b <=> length $a} keys %common) {
3511 if ($common{$_} == $common_max) {
3512 $longest_path = $_;
3513 last;
3516 $longest_path;
3519 sub gs_fetch_loop_common {
3520 my ($self, $base, $head, $gsv, $globs) = @_;
3521 return if ($base > $head);
3522 my $inc = $_log_window_size;
3523 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3524 my $longest_path = longest_common_path($gsv, $globs);
3525 my $ra_url = $self->{url};
3526 while (1) {
3527 my %revs;
3528 my $err;
3529 my $err_handler = $SVN::Error::handler;
3530 $SVN::Error::handler = sub {
3531 ($err) = @_;
3532 skip_unknown_revs($err);
3534 sub _cb {
3535 my ($paths, $r, $author, $date, $log) = @_;
3536 [ dup_changed_paths($paths),
3537 { author => $author, date => $date, log => $log } ];
3539 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3540 sub { $revs{$_[1]} = _cb(@_) });
3541 if ($err && $max >= $head) {
3542 print STDERR "Path '$longest_path' ",
3543 "was probably deleted:\n",
3544 $err->expanded_message,
3545 "\nWill attempt to follow ",
3546 "revisions r$min .. r$max ",
3547 "committed before the deletion\n";
3548 my $hi = $max;
3549 while (--$hi >= $min) {
3550 my $ok;
3551 $self->get_log([$longest_path], $min, $hi,
3552 0, 1, 1, sub {
3553 $ok ||= $_[1];
3554 $revs{$_[1]} = _cb(@_) });
3555 if ($ok) {
3556 print STDERR "r$min .. r$ok OK\n";
3557 last;
3561 $SVN::Error::handler = $err_handler;
3563 my %exists = map { $_->{path} => $_ } @$gsv;
3564 foreach my $r (sort {$a <=> $b} keys %revs) {
3565 my ($paths, $logged) = @{$revs{$r}};
3567 foreach my $gs ($self->match_globs(\%exists, $paths,
3568 $globs, $r)) {
3569 if ($gs->rev_db_max >= $r) {
3570 next;
3572 next unless $gs->match_paths($paths, $r);
3573 $gs->{logged_rev_props} = $logged;
3574 if (my $last_commit = $gs->last_commit) {
3575 $gs->assert_index_clean($last_commit);
3577 my $log_entry = $gs->do_fetch($paths, $r);
3578 if ($log_entry) {
3579 $gs->do_git_commit($log_entry);
3582 foreach my $g (@$globs) {
3583 my $k = "svn-remote.$g->{remote}." .
3584 "$g->{t}-maxRev";
3585 Git::SVN::tmp_config($k, $r);
3587 if ($ra_invalid) {
3588 $_[0] = undef;
3589 $self = undef;
3590 $RA = undef;
3591 $self = Git::SVN::Ra->new($ra_url);
3592 $ra_invalid = undef;
3595 # pre-fill the .rev_db since it'll eventually get filled in
3596 # with '0' x40 if something new gets committed
3597 foreach my $gs (@$gsv) {
3598 next if defined $gs->rev_db_get($max);
3599 $gs->rev_db_set($max, 0 x40);
3601 foreach my $g (@$globs) {
3602 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3603 Git::SVN::tmp_config($k, $max);
3605 last if $max >= $head;
3606 $min = $max + 1;
3607 $max += $inc;
3608 $max = $head if ($max > $head);
3612 sub match_globs {
3613 my ($self, $exists, $paths, $globs, $r) = @_;
3615 sub get_dir_check {
3616 my ($self, $exists, $g, $r) = @_;
3617 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3618 return unless scalar @x == 3;
3619 my $dirents = $x[0];
3620 foreach my $de (keys %$dirents) {
3621 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3622 my $p = $g->{path}->full_path($de);
3623 next if $exists->{$p};
3624 next if (length $g->{path}->{right} &&
3625 ($self->check_path($p, $r) !=
3626 $SVN::Node::dir));
3627 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3628 $g->{ref}->full_path($de), 1);
3631 foreach my $g (@$globs) {
3632 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3633 if ($path->{action} =~ /^[AR]$/) {
3634 get_dir_check($self, $exists, $g, $r);
3637 foreach (keys %$paths) {
3638 if (/$g->{path}->{left_regex}/ &&
3639 !/$g->{path}->{regex}/) {
3640 next if $paths->{$_}->{action} !~ /^[AR]$/;
3641 get_dir_check($self, $exists, $g, $r);
3643 next unless /$g->{path}->{regex}/;
3644 my $p = $1;
3645 my $pathname = $g->{path}->full_path($p);
3646 next if $exists->{$pathname};
3647 next if ($self->check_path($pathname, $r) !=
3648 $SVN::Node::dir);
3649 $exists->{$pathname} = Git::SVN->init(
3650 $self->{url}, $pathname, undef,
3651 $g->{ref}->full_path($p), 1);
3653 my $c = '';
3654 foreach (split m#/#, $g->{path}->{left}) {
3655 $c .= "/$_";
3656 next unless ($paths->{$c} &&
3657 ($paths->{$c}->{action} =~ /^[AR]$/));
3658 get_dir_check($self, $exists, $g, $r);
3661 values %$exists;
3664 sub minimize_url {
3665 my ($self) = @_;
3666 return $self->{url} if ($self->{url} eq $self->{repos_root});
3667 my $url = $self->{repos_root};
3668 my @components = split(m!/!, $self->{svn_path});
3669 my $c = '';
3670 do {
3671 $url .= "/$c" if length $c;
3672 eval { (ref $self)->new($url)->get_latest_revnum };
3673 } while ($@ && ($c = shift @components));
3674 $url;
3677 sub can_do_switch {
3678 my $self = shift;
3679 unless (defined $can_do_switch) {
3680 my $pool = SVN::Pool->new;
3681 my $rep = eval {
3682 $self->do_switch(1, '', 0, $self->{url},
3683 SVN::Delta::Editor->new, $pool);
3685 if ($@) {
3686 $can_do_switch = 0;
3687 } else {
3688 $rep->abort_report($pool);
3689 $can_do_switch = 1;
3691 $pool->clear;
3693 $can_do_switch;
3696 sub skip_unknown_revs {
3697 my ($err) = @_;
3698 my $errno = $err->apr_err();
3699 # Maybe the branch we're tracking didn't
3700 # exist when the repo started, so it's
3701 # not an error if it doesn't, just continue
3703 # Wonderfully consistent library, eh?
3704 # 160013 - svn:// and file://
3705 # 175002 - http(s)://
3706 # 175007 - http(s):// (this repo required authorization, too...)
3707 # More codes may be discovered later...
3708 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3709 my $err_key = $err->expanded_message;
3710 # revision numbers change every time, filter them out
3711 $err_key =~ s/\d+/\0/g;
3712 $err_key = "$errno\0$err_key";
3713 unless ($ignored_err{$err_key}) {
3714 warn "W: Ignoring error from SVN, path probably ",
3715 "does not exist: ($errno): ",
3716 $err->expanded_message,"\n";
3717 $ignored_err{$err_key} = 1;
3719 return;
3721 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3724 # svn_log_changed_path_t objects passed to get_log are likely to be
3725 # overwritten even if only the refs are copied to an external variable,
3726 # so we should dup the structures in their entirety. Using an externally
3727 # passed pool (instead of our temporary and quickly cleared pool in
3728 # Git::SVN::Ra) does not help matters at all...
3729 sub dup_changed_paths {
3730 my ($paths) = @_;
3731 return undef unless $paths;
3732 my %ret;
3733 foreach my $p (keys %$paths) {
3734 my $i = $paths->{$p};
3735 my %s = map { $_ => $i->$_ }
3736 qw/copyfrom_path copyfrom_rev action/;
3737 $ret{$p} = \%s;
3739 \%ret;
3742 package Git::SVN::Log;
3743 use strict;
3744 use warnings;
3745 use POSIX qw/strftime/;
3746 use constant commit_log_separator => ('-' x 72) . "\n";
3747 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3748 %rusers $show_commit $incremental/;
3749 my $l_fmt;
3751 sub cmt_showable {
3752 my ($c) = @_;
3753 return 1 if defined $c->{r};
3755 # big commit message got truncated by the 16k pretty buffer in rev-list
3756 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3757 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3758 @{$c->{l}} = ();
3759 my @log = command(qw/cat-file commit/, $c->{c});
3761 # shift off the headers
3762 shift @log while ($log[0] ne '');
3763 shift @log;
3765 # TODO: make $c->{l} not have a trailing newline in the future
3766 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3768 (undef, $c->{r}, undef) = ::extract_metadata(
3769 (grep(/^git-svn-id: /, @log))[-1]);
3771 return defined $c->{r};
3774 sub log_use_color {
3775 return 1 if $color;
3776 my ($dc, $dcvar);
3777 $dcvar = 'color.diff';
3778 $dc = `git-config --get $dcvar`;
3779 if ($dc eq '') {
3780 # nothing at all; fallback to "diff.color"
3781 $dcvar = 'diff.color';
3782 $dc = `git-config --get $dcvar`;
3784 chomp($dc);
3785 if ($dc eq 'auto') {
3786 my $pc;
3787 $pc = `git-config --get color.pager`;
3788 if ($pc eq '') {
3789 # does not have it -- fallback to pager.color
3790 $pc = `git-config --bool --get pager.color`;
3792 else {
3793 $pc = `git-config --bool --get color.pager`;
3794 if ($?) {
3795 $pc = 'false';
3798 chomp($pc);
3799 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3800 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3802 return 0;
3804 return 0 if $dc eq 'never';
3805 return 1 if $dc eq 'always';
3806 chomp($dc = `git-config --bool --get $dcvar`);
3807 return ($dc eq 'true');
3810 sub git_svn_log_cmd {
3811 my ($r_min, $r_max, @args) = @_;
3812 my $head = 'HEAD';
3813 my (@files, @log_opts);
3814 foreach my $x (@args) {
3815 if ($x eq '--' || @files) {
3816 push @files, $x;
3817 } else {
3818 if (::verify_ref("$x^0")) {
3819 $head = $x;
3820 } else {
3821 push @log_opts, $x;
3826 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3827 $gs ||= Git::SVN->_new;
3828 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3829 $gs->refname);
3830 push @cmd, '-r' unless $non_recursive;
3831 push @cmd, qw/--raw --name-status/ if $verbose;
3832 push @cmd, '--color' if log_use_color();
3833 push @cmd, @log_opts;
3834 if (defined $r_max && $r_max == $r_min) {
3835 push @cmd, '--max-count=1';
3836 if (my $c = $gs->rev_db_get($r_max)) {
3837 push @cmd, $c;
3839 } elsif (defined $r_max) {
3840 if ($r_max < $r_min) {
3841 ($r_min, $r_max) = ($r_max, $r_min);
3843 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
3844 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
3845 # If there are no commits in the range, both $c_max and $c_min
3846 # will be undefined. If there is at least 1 commit in the
3847 # range, both will be defined.
3848 return () if !defined $c_min || !defined $c_max;
3849 if ($c_min eq $c_max) {
3850 push @cmd, '--max-count=1', $c_min;
3851 } else {
3852 push @cmd, '--boundary', "$c_min..$c_max";
3855 return (@cmd, @files);
3858 # adapted from pager.c
3859 sub config_pager {
3860 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3861 if (!defined $pager) {
3862 $pager = 'less';
3863 } elsif (length $pager == 0 || $pager eq 'cat') {
3864 $pager = undef;
3868 sub run_pager {
3869 return unless -t *STDOUT && defined $pager;
3870 pipe my $rfd, my $wfd or return;
3871 defined(my $pid = fork) or ::fatal "Can't fork: $!";
3872 if (!$pid) {
3873 open STDOUT, '>&', $wfd or
3874 ::fatal "Can't redirect to stdout: $!";
3875 return;
3877 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
3878 $ENV{LESS} ||= 'FRSX';
3879 exec $pager or ::fatal "Can't run pager: $! ($pager)";
3882 sub format_svn_date {
3883 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
3886 sub parse_git_date {
3887 my ($t, $tz) = @_;
3888 # Date::Parse isn't in the standard Perl distro :(
3889 if ($tz =~ s/^\+//) {
3890 $t += tz_to_s_offset($tz);
3891 } elsif ($tz =~ s/^\-//) {
3892 $t -= tz_to_s_offset($tz);
3894 return $t;
3897 sub set_local_timezone {
3898 if (defined $TZ) {
3899 $ENV{TZ} = $TZ;
3900 } else {
3901 delete $ENV{TZ};
3905 sub tz_to_s_offset {
3906 my ($tz) = @_;
3907 $tz =~ s/(\d\d)$//;
3908 return ($1 * 60) + ($tz * 3600);
3911 sub get_author_info {
3912 my ($dest, $author, $t, $tz) = @_;
3913 $author =~ s/(?:^\s*|\s*$)//g;
3914 $dest->{a_raw} = $author;
3915 my $au;
3916 if ($::_authors) {
3917 $au = $rusers{$author} || undef;
3919 if (!$au) {
3920 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3922 $dest->{t} = $t;
3923 $dest->{tz} = $tz;
3924 $dest->{a} = $au;
3925 $dest->{t_utc} = parse_git_date($t, $tz);
3928 sub process_commit {
3929 my ($c, $r_min, $r_max, $defer) = @_;
3930 if (defined $r_min && defined $r_max) {
3931 if ($r_min == $c->{r} && $r_min == $r_max) {
3932 show_commit($c);
3933 return 0;
3935 return 1 if $r_min == $r_max;
3936 if ($r_min < $r_max) {
3937 # we need to reverse the print order
3938 return 0 if (defined $limit && --$limit < 0);
3939 push @$defer, $c;
3940 return 1;
3942 if ($r_min != $r_max) {
3943 return 1 if ($r_min < $c->{r});
3944 return 1 if ($r_max > $c->{r});
3947 return 0 if (defined $limit && --$limit < 0);
3948 show_commit($c);
3949 return 1;
3952 sub show_commit {
3953 my $c = shift;
3954 if ($oneline) {
3955 my $x = "\n";
3956 if (my $l = $c->{l}) {
3957 while ($l->[0] =~ /^\s*$/) { shift @$l }
3958 $x = $l->[0];
3960 $l_fmt ||= 'A' . length($c->{r});
3961 print 'r',pack($l_fmt, $c->{r}),' | ';
3962 print "$c->{c} | " if $show_commit;
3963 print $x;
3964 } else {
3965 show_commit_normal($c);
3969 sub show_commit_changed_paths {
3970 my ($c) = @_;
3971 return unless $c->{changed};
3972 print "Changed paths:\n", @{$c->{changed}};
3975 sub show_commit_normal {
3976 my ($c) = @_;
3977 print commit_log_separator, "r$c->{r} | ";
3978 print "$c->{c} | " if $show_commit;
3979 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
3980 my $nr_line = 0;
3982 if (my $l = $c->{l}) {
3983 while ($l->[$#$l] eq "\n" && $#$l > 0
3984 && $l->[($#$l - 1)] eq "\n") {
3985 pop @$l;
3987 $nr_line = scalar @$l;
3988 if (!$nr_line) {
3989 print "1 line\n\n\n";
3990 } else {
3991 if ($nr_line == 1) {
3992 $nr_line = '1 line';
3993 } else {
3994 $nr_line .= ' lines';
3996 print $nr_line, "\n";
3997 show_commit_changed_paths($c);
3998 print "\n";
3999 print $_ foreach @$l;
4001 } else {
4002 print "1 line\n";
4003 show_commit_changed_paths($c);
4004 print "\n";
4007 foreach my $x (qw/raw stat diff/) {
4008 if ($c->{$x}) {
4009 print "\n";
4010 print $_ foreach @{$c->{$x}}
4015 sub cmd_show_log {
4016 my (@args) = @_;
4017 my ($r_min, $r_max);
4018 my $r_last = -1; # prevent dupes
4019 set_local_timezone();
4020 if (defined $::_revision) {
4021 if ($::_revision =~ /^(\d+):(\d+)$/) {
4022 ($r_min, $r_max) = ($1, $2);
4023 } elsif ($::_revision =~ /^\d+$/) {
4024 $r_min = $r_max = $::_revision;
4025 } else {
4026 ::fatal "-r$::_revision is not supported, use ",
4027 "standard 'git log' arguments instead";
4031 config_pager();
4032 @args = git_svn_log_cmd($r_min, $r_max, @args);
4033 if (!@args) {
4034 print commit_log_separator unless $incremental || $oneline;
4035 return;
4037 my $log = command_output_pipe(@args);
4038 run_pager();
4039 my (@k, $c, $d, $stat);
4040 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4041 while (<$log>) {
4042 if (/^${esc_color}commit -?($::sha1_short)/o) {
4043 my $cmt = $1;
4044 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4045 $r_last = $c->{r};
4046 process_commit($c, $r_min, $r_max, \@k) or
4047 goto out;
4049 $d = undef;
4050 $c = { c => $cmt };
4051 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4052 get_author_info($c, $1, $2, $3);
4053 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4054 # ignore
4055 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4056 push @{$c->{raw}}, $_;
4057 } elsif (/^${esc_color}[ACRMDT]\t/) {
4058 # we could add $SVN->{svn_path} here, but that requires
4059 # remote access at the moment (repo_path_split)...
4060 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4061 push @{$c->{changed}}, $_;
4062 } elsif (/^${esc_color}diff /o) {
4063 $d = 1;
4064 push @{$c->{diff}}, $_;
4065 } elsif ($d) {
4066 push @{$c->{diff}}, $_;
4067 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4068 $esc_color*[\+\-]*$esc_color$/x) {
4069 $stat = 1;
4070 push @{$c->{stat}}, $_;
4071 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4072 push @{$c->{stat}}, $_;
4073 $stat = undef;
4074 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4075 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4076 } elsif (s/^${esc_color} //o) {
4077 push @{$c->{l}}, $_;
4080 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4081 $r_last = $c->{r};
4082 process_commit($c, $r_min, $r_max, \@k);
4084 if (@k) {
4085 ($r_min, $r_max) = ($r_max, $r_min);
4086 process_commit($_, $r_min, $r_max) foreach reverse @k;
4088 out:
4089 close $log;
4090 print commit_log_separator unless $incremental || $oneline;
4093 package Git::SVN::Migration;
4094 # these version numbers do NOT correspond to actual version numbers
4095 # of git nor git-svn. They are just relative.
4097 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4099 # v1 layout: .git/$id/info/url, refs/remotes/$id
4101 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4103 # v3 layout: .git/svn/$id, refs/remotes/$id
4104 # - info/url may remain for backwards compatibility
4105 # - this is what we migrate up to this layout automatically,
4106 # - this will be used by git svn init on single branches
4107 # v3.1 layout (auto migrated):
4108 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4109 # for backwards compatibility
4111 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4112 # - this is only created for newly multi-init-ed
4113 # repositories. Similar in spirit to the
4114 # --use-separate-remotes option in git-clone (now default)
4115 # - we do not automatically migrate to this (following
4116 # the example set by core git)
4117 use strict;
4118 use warnings;
4119 use Carp qw/croak/;
4120 use File::Path qw/mkpath/;
4121 use File::Basename qw/dirname basename/;
4122 use vars qw/$_minimize/;
4124 sub migrate_from_v0 {
4125 my $git_dir = $ENV{GIT_DIR};
4126 return undef unless -d $git_dir;
4127 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4128 my $migrated = 0;
4129 while (<$fh>) {
4130 chomp;
4131 my ($id, $orig_ref) = ($_, $_);
4132 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4133 next unless -f "$git_dir/$id/info/url";
4134 my $new_ref = "refs/remotes/$id";
4135 if (::verify_ref("$new_ref^0")) {
4136 print STDERR "W: $orig_ref is probably an old ",
4137 "branch used by an ancient version of ",
4138 "git-svn.\n",
4139 "However, $new_ref also exists.\n",
4140 "We will not be able ",
4141 "to use this branch until this ",
4142 "ambiguity is resolved.\n";
4143 next;
4145 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4146 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4147 command_noisy('update-ref', $new_ref, $orig_ref);
4148 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4149 $migrated++;
4151 command_close_pipe($fh, $ctx);
4152 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4153 $migrated;
4156 sub migrate_from_v1 {
4157 my $git_dir = $ENV{GIT_DIR};
4158 my $migrated = 0;
4159 return $migrated unless -d $git_dir;
4160 my $svn_dir = "$git_dir/svn";
4162 # just in case somebody used 'svn' as their $id at some point...
4163 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4165 print STDERR "Migrating from a git-svn v1 layout...\n";
4166 mkpath([$svn_dir]);
4167 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4168 "$svn_dir\n\t(required for this version ",
4169 "($::VERSION) of git-svn) does not. exist\n";
4170 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4171 while (<$fh>) {
4172 my $x = $_;
4173 next unless $x =~ s#^refs/remotes/##;
4174 chomp $x;
4175 next unless -f "$git_dir/$x/info/url";
4176 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4177 next unless $u;
4178 my $dn = dirname("$git_dir/svn/$x");
4179 mkpath([$dn]) unless -d $dn;
4180 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4181 mkpath(["$git_dir/svn/svn"]);
4182 print STDERR " - $git_dir/$x/info => ",
4183 "$git_dir/svn/$x/info\n";
4184 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4185 croak "$!: $x";
4186 # don't worry too much about these, they probably
4187 # don't exist with repos this old (save for index,
4188 # and we can easily regenerate that)
4189 foreach my $f (qw/unhandled.log index .rev_db/) {
4190 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4192 } else {
4193 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4194 rename "$git_dir/$x", "$git_dir/svn/$x" or
4195 croak "$!: $x";
4197 $migrated++;
4199 command_close_pipe($fh, $ctx);
4200 print STDERR "Done migrating from a git-svn v1 layout\n";
4201 $migrated;
4204 sub read_old_urls {
4205 my ($l_map, $pfx, $path) = @_;
4206 my @dir;
4207 foreach (<$path/*>) {
4208 if (-r "$_/info/url") {
4209 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4210 my $ref_id = $pfx . basename $_;
4211 my $url = ::file_to_s("$_/info/url");
4212 $l_map->{$ref_id} = $url;
4213 } elsif (-d $_) {
4214 push @dir, $_;
4217 foreach (@dir) {
4218 my $x = $_;
4219 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4220 read_old_urls($l_map, $x, $_);
4224 sub migrate_from_v2 {
4225 my @cfg = command(qw/config -l/);
4226 return if grep /^svn-remote\..+\.url=/, @cfg;
4227 my %l_map;
4228 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4229 my $migrated = 0;
4231 foreach my $ref_id (sort keys %l_map) {
4232 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4233 if ($@) {
4234 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4236 $migrated++;
4238 $migrated;
4241 sub minimize_connections {
4242 my $r = Git::SVN::read_all_remotes();
4243 my $new_urls = {};
4244 my $root_repos = {};
4245 foreach my $repo_id (keys %$r) {
4246 my $url = $r->{$repo_id}->{url} or next;
4247 my $fetch = $r->{$repo_id}->{fetch} or next;
4248 my $ra = Git::SVN::Ra->new($url);
4250 # skip existing cases where we already connect to the root
4251 if (($ra->{url} eq $ra->{repos_root}) ||
4252 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4253 $repo_id)) {
4254 $root_repos->{$ra->{url}} = $repo_id;
4255 next;
4258 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4259 my $root_path = $ra->{url};
4260 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4261 foreach my $path (keys %$fetch) {
4262 my $ref_id = $fetch->{$path};
4263 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4265 # make sure we can read when connecting to
4266 # a higher level of a repository
4267 my ($last_rev, undef) = $gs->last_rev_commit;
4268 if (!defined $last_rev) {
4269 $last_rev = eval {
4270 $root_ra->get_latest_revnum;
4272 next if $@;
4274 my $new = $root_path;
4275 $new .= length $path ? "/$path" : '';
4276 eval {
4277 $root_ra->get_log([$new], $last_rev, $last_rev,
4278 0, 0, 1, sub { });
4280 next if $@;
4281 $new_urls->{$ra->{repos_root}}->{$new} =
4282 { ref_id => $ref_id,
4283 old_repo_id => $repo_id,
4284 old_path => $path };
4288 my @emptied;
4289 foreach my $url (keys %$new_urls) {
4290 # see if we can re-use an existing [svn-remote "repo_id"]
4291 # instead of creating a(n ugly) new section:
4292 my $repo_id = $root_repos->{$url} ||
4293 Git::SVN::sanitize_remote_name($url);
4295 my $fetch = $new_urls->{$url};
4296 foreach my $path (keys %$fetch) {
4297 my $x = $fetch->{$path};
4298 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4299 my $pfx = "svn-remote.$x->{old_repo_id}";
4301 my $old_fetch = quotemeta("$x->{old_path}:".
4302 "refs/remotes/$x->{ref_id}");
4303 command_noisy(qw/config --unset/,
4304 "$pfx.fetch", '^'. $old_fetch . '$');
4305 delete $r->{$x->{old_repo_id}}->
4306 {fetch}->{$x->{old_path}};
4307 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4308 command_noisy(qw/config --unset/,
4309 "$pfx.url");
4310 push @emptied, $x->{old_repo_id}
4314 if (@emptied) {
4315 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4316 "$ENV{GIT_DIR}/config";
4317 print STDERR <<EOF;
4318 The following [svn-remote] sections in your config file ($file) are empty
4319 and can be safely removed:
4321 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4325 sub migration_check {
4326 migrate_from_v0();
4327 migrate_from_v1();
4328 migrate_from_v2();
4329 minimize_connections() if $_minimize;
4332 package Git::IndexInfo;
4333 use strict;
4334 use warnings;
4335 use Git qw/command_input_pipe command_close_pipe/;
4337 sub new {
4338 my ($class) = @_;
4339 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4340 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4343 sub remove {
4344 my ($self, $path) = @_;
4345 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4346 return ++$self->{nr};
4348 undef;
4351 sub update {
4352 my ($self, $mode, $hash, $path) = @_;
4353 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4354 return ++$self->{nr};
4356 undef;
4359 sub DESTROY {
4360 my ($self) = @_;
4361 command_close_pipe($self->{gui}, $self->{ctx});
4364 package Git::SVN::GlobSpec;
4365 use strict;
4366 use warnings;
4368 sub new {
4369 my ($class, $glob) = @_;
4370 my $re = $glob;
4371 $re =~ s!/+$!!g; # no need for trailing slashes
4372 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4373 my ($left, $right) = ($1, $2);
4374 if ($nr > 1) {
4375 die "Only one '*' wildcard expansion ",
4376 "is supported (got $nr): '$glob'\n";
4377 } elsif ($nr == 0) {
4378 die "One '*' is needed for glob: '$glob'\n";
4380 $re = quotemeta($left) . $re . quotemeta($right);
4381 if (length $left && !($left =~ s!/+$!!g)) {
4382 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4384 if (length $right && !($right =~ s!^/+!!g)) {
4385 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4387 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4388 bless { left => $left, right => $right, left_regex => $left_re,
4389 regex => qr/$re/, glob => $glob }, $class;
4392 sub full_path {
4393 my ($self, $path) = @_;
4394 return (length $self->{left} ? "$self->{left}/" : '') .
4395 $path . (length $self->{right} ? "/$self->{right}" : '');
4398 __END__
4400 Data structures:
4403 $remotes = { # returned by read_all_remotes()
4404 'svn' => {
4405 # svn-remote.svn.url=https://svn.musicpd.org
4406 url => 'https://svn.musicpd.org',
4407 # svn-remote.svn.fetch=mpd/trunk:trunk
4408 fetch => {
4409 'mpd/trunk' => 'trunk',
4411 # svn-remote.svn.tags=mpd/tags/*:tags/*
4412 tags => {
4413 path => {
4414 left => 'mpd/tags',
4415 right => '',
4416 regex => qr!mpd/tags/([^/]+)$!,
4417 glob => 'tags/*',
4419 ref => {
4420 left => 'tags',
4421 right => '',
4422 regex => qr!tags/([^/]+)$!,
4423 glob => 'tags/*',
4429 $log_entry hashref as returned by libsvn_log_entry()
4431 log => 'whitespace-formatted log entry
4432 ', # trailing newline is preserved
4433 revision => '8', # integer
4434 date => '2004-02-24T17:01:44.108345Z', # commit date
4435 author => 'committer name'
4439 # this is generated by generate_diff();
4440 @mods = array of diff-index line hashes, each element represents one line
4441 of diff-index output
4443 diff-index line ($m hash)
4445 mode_a => first column of diff-index output, no leading ':',
4446 mode_b => second column of diff-index output,
4447 sha1_b => sha1sum of the final blob,
4448 chg => change type [MCRADT],
4449 file_a => original file name of a file (iff chg is 'C' or 'R')
4450 file_b => new/current file name of a file (any chg)
4454 # retval of read_url_paths{,_all}();
4455 $l_map = {
4456 # repository root url
4457 'https://svn.musicpd.org' => {
4458 # repository path # GIT_SVN_ID
4459 'mpd/trunk' => 'trunk',
4460 'mpd/tags/0.11.5' => 'tags/0.11.5',
4464 Notes:
4465 I don't trust the each() function on unless I created %hash myself
4466 because the internal iterator may not have started at base.