git-p4: Fix typo in --detect-labels
[git/gitweb.git] / git-svn.perl
blob5b1deeab942aa2a63a6cbe6a92792dbbe6f17d01
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 __PACKAGE__) {
53 *{"${package}::$_"} = \&{"Git::$_"};
58 my ($SVN);
60 $sha1 = qr/[a-f\d]{40}/;
61 $sha1_short = qr/[a-f\d]{4,40}/;
62 my ($_stdin, $_help, $_edit,
63 $_message, $_file,
64 $_template, $_shared,
65 $_version, $_fetch_all, $_no_rebase,
66 $_merge, $_strategy, $_dry_run, $_local,
67 $_prefix, $_no_checkout, $_verbose);
68 $Git::SVN::_follow_parent = 1;
69 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
70 'config-dir=s' => \$Git::SVN::Ra::config_dir,
71 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
72 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
73 'authors-file|A=s' => \$_authors,
74 'repack:i' => \$Git::SVN::_repack,
75 'noMetadata' => \$Git::SVN::_no_metadata,
76 'useSvmProps' => \$Git::SVN::_use_svm_props,
77 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
78 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
79 'no-checkout' => \$_no_checkout,
80 'quiet|q' => \$_q,
81 'repack-flags|repack-args|repack-opts=s' =>
82 \$Git::SVN::_repack_flags,
83 %remote_opts );
85 my ($_trunk, $_tags, $_branches, $_stdlayout);
86 my %icv;
87 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
88 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
89 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
90 'stdlayout|s' => \$_stdlayout,
91 'minimize-url|m' => \$Git::SVN::_minimize_url,
92 'no-metadata' => sub { $icv{noMetadata} = 1 },
93 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
94 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
95 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
96 %remote_opts );
97 my %cmt_opts = ( 'edit|e' => \$_edit,
98 'rmdir' => \$SVN::Git::Editor::_rmdir,
99 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
100 'l=i' => \$SVN::Git::Editor::_rename_limit,
101 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
104 my %cmd = (
105 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
106 { 'revision|r=s' => \$_revision,
107 'fetch-all|all' => \$_fetch_all,
108 %fc_opts } ],
109 clone => [ \&cmd_clone, "Initialize and fetch revisions",
110 { 'revision|r=s' => \$_revision,
111 %fc_opts, %init_opts } ],
112 init => [ \&cmd_init, "Initialize a repo for tracking" .
113 " (requires URL argument)",
114 \%init_opts ],
115 'multi-init' => [ \&cmd_multi_init,
116 "Deprecated alias for ".
117 "'$0 init -T<trunk> -b<branches> -t<tags>'",
118 \%init_opts ],
119 dcommit => [ \&cmd_dcommit,
120 'Commit several diffs to merge with upstream',
121 { 'merge|m|M' => \$_merge,
122 'strategy|s=s' => \$_strategy,
123 'verbose|v' => \$_verbose,
124 'dry-run|n' => \$_dry_run,
125 'fetch-all|all' => \$_fetch_all,
126 'no-rebase' => \$_no_rebase,
127 %cmt_opts, %fc_opts } ],
128 'set-tree' => [ \&cmd_set_tree,
129 "Set an SVN repository to a git tree-ish",
130 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
131 'create-ignore' => [ \&cmd_create_ignore,
132 'Create a .gitignore per svn:ignore',
133 { 'revision|r=i' => \$_revision
134 } ],
135 'propget' => [ \&cmd_propget,
136 'Print the value of a property on a file or directory',
137 { 'revision|r=i' => \$_revision } ],
138 'proplist' => [ \&cmd_proplist,
139 'List all properties of a file or directory',
140 { 'revision|r=i' => \$_revision } ],
141 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
142 { 'revision|r=i' => \$_revision
143 } ],
144 'multi-fetch' => [ \&cmd_multi_fetch,
145 "Deprecated alias for $0 fetch --all",
146 { 'revision|r=s' => \$_revision, %fc_opts } ],
147 'migrate' => [ sub { },
148 # no-op, we automatically run this anyways,
149 'Migrate configuration/metadata/layout from
150 previous versions of git-svn',
151 { 'minimize' => \$Git::SVN::Migration::_minimize,
152 %remote_opts } ],
153 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
154 { 'limit=i' => \$Git::SVN::Log::limit,
155 'revision|r=s' => \$_revision,
156 'verbose|v' => \$Git::SVN::Log::verbose,
157 'incremental' => \$Git::SVN::Log::incremental,
158 'oneline' => \$Git::SVN::Log::oneline,
159 'show-commit' => \$Git::SVN::Log::show_commit,
160 'non-recursive' => \$Git::SVN::Log::non_recursive,
161 'authors-file|A=s' => \$_authors,
162 'color' => \$Git::SVN::Log::color,
163 'pager=s' => \$Git::SVN::Log::pager
164 } ],
165 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
166 {} ],
167 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
168 { 'merge|m|M' => \$_merge,
169 'verbose|v' => \$_verbose,
170 'strategy|s=s' => \$_strategy,
171 'local|l' => \$_local,
172 'fetch-all|all' => \$_fetch_all,
173 %fc_opts } ],
174 'commit-diff' => [ \&cmd_commit_diff,
175 'Commit a diff between two trees',
176 { 'message|m=s' => \$_message,
177 'file|F=s' => \$_file,
178 'revision|r=s' => \$_revision,
179 %cmt_opts } ],
182 my $cmd;
183 for (my $i = 0; $i < @ARGV; $i++) {
184 if (defined $cmd{$ARGV[$i]}) {
185 $cmd = $ARGV[$i];
186 splice @ARGV, $i, 1;
187 last;
191 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
193 read_repo_config(\%opts);
194 Getopt::Long::Configure('pass_through') if ($cmd && $cmd eq 'log');
195 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
196 'minimize-connections' => \$Git::SVN::Migration::_minimize,
197 'id|i=s' => \$Git::SVN::default_ref_id,
198 'svn-remote|remote|R=s' => sub {
199 $Git::SVN::no_reuse_existing = 1;
200 $Git::SVN::default_repo_id = $_[1] });
201 exit 1 if (!$rv && $cmd && $cmd ne 'log');
203 usage(0) if $_help;
204 version() if $_version;
205 usage(1) unless defined $cmd;
206 load_authors() if $_authors;
208 # make sure we're always running
209 unless ($cmd =~ /(?:clone|init|multi-init)$/) {
210 unless (-d $ENV{GIT_DIR}) {
211 if ($git_dir_user_set) {
212 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
213 "but it is not a directory\n";
215 my $git_dir = delete $ENV{GIT_DIR};
216 chomp(my $cdup = command_oneline(qw/rev-parse --show-cdup/));
217 unless (length $cdup) {
218 die "Already at toplevel, but $git_dir ",
219 "not found '$cdup'\n";
221 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
222 unless (-d $git_dir) {
223 die "$git_dir still not found after going to ",
224 "'$cdup'\n";
226 $ENV{GIT_DIR} = $git_dir;
229 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
230 Git::SVN::Migration::migration_check();
232 Git::SVN::init_vars();
233 eval {
234 Git::SVN::verify_remotes_sanity();
235 $cmd{$cmd}->[0]->(@ARGV);
237 fatal $@ if $@;
238 post_fetch_checkout();
239 exit 0;
241 ####################### primary functions ######################
242 sub usage {
243 my $exit = shift || 0;
244 my $fd = $exit ? \*STDERR : \*STDOUT;
245 print $fd <<"";
246 git-svn - bidirectional operations between a single Subversion tree and git
247 Usage: $0 <command> [options] [arguments]\n
249 print $fd "Available commands:\n" unless $cmd;
251 foreach (sort keys %cmd) {
252 next if $cmd && $cmd ne $_;
253 next if /^multi-/; # don't show deprecated commands
254 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
255 foreach (sort keys %{$cmd{$_}->[2]}) {
256 # mixed-case options are for .git/config only
257 next if /[A-Z]/ && /^[a-z]+$/i;
258 # prints out arguments as they should be passed:
259 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
260 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
261 "--$_" : "-$_" }
262 split /\|/,$_)," $x\n";
265 print $fd <<"";
266 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
267 arbitrary identifier if you're tracking multiple SVN branches/repositories in
268 one git repository and want to keep them separate. See git-svn(1) for more
269 information.
271 exit $exit;
274 sub version {
275 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
276 exit 0;
279 sub do_git_init_db {
280 unless (-d $ENV{GIT_DIR}) {
281 my @init_db = ('init');
282 push @init_db, "--template=$_template" if defined $_template;
283 if (defined $_shared) {
284 if ($_shared =~ /[a-z]/) {
285 push @init_db, "--shared=$_shared";
286 } else {
287 push @init_db, "--shared";
290 command_noisy(@init_db);
292 my $set;
293 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
294 foreach my $i (keys %icv) {
295 die "'$set' and '$i' cannot both be set\n" if $set;
296 next unless defined $icv{$i};
297 command_noisy('config', "$pfx.$i", $icv{$i});
298 $set = $i;
302 sub init_subdir {
303 my $repo_path = shift or return;
304 mkpath([$repo_path]) unless -d $repo_path;
305 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
306 $ENV{GIT_DIR} = '.git';
309 sub cmd_clone {
310 my ($url, $path) = @_;
311 if (!defined $path &&
312 (defined $_trunk || defined $_branches || defined $_tags ||
313 defined $_stdlayout) &&
314 $url !~ m#^[a-z\+]+://#) {
315 $path = $url;
317 $path = basename($url) if !defined $path || !length $path;
318 cmd_init($url, $path);
319 Git::SVN::fetch_all($Git::SVN::default_repo_id);
322 sub cmd_init {
323 if (defined $_stdlayout) {
324 $_trunk = 'trunk' if (!defined $_trunk);
325 $_tags = 'tags' if (!defined $_tags);
326 $_branches = 'branches' if (!defined $_branches);
328 if (defined $_trunk || defined $_branches || defined $_tags) {
329 return cmd_multi_init(@_);
331 my $url = shift or die "SVN repository location required ",
332 "as a command-line argument\n";
333 init_subdir(@_);
334 do_git_init_db();
336 Git::SVN->init($url);
339 sub cmd_fetch {
340 if (grep /^\d+=./, @_) {
341 die "'<rev>=<commit>' fetch arguments are ",
342 "no longer supported.\n";
344 my ($remote) = @_;
345 if (@_ > 1) {
346 die "Usage: $0 fetch [--all] [svn-remote]\n";
348 $remote ||= $Git::SVN::default_repo_id;
349 if ($_fetch_all) {
350 cmd_multi_fetch();
351 } else {
352 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
356 sub cmd_set_tree {
357 my (@commits) = @_;
358 if ($_stdin || !@commits) {
359 print "Reading from stdin...\n";
360 @commits = ();
361 while (<STDIN>) {
362 if (/\b($sha1_short)\b/o) {
363 unshift @commits, $1;
367 my @revs;
368 foreach my $c (@commits) {
369 my @tmp = command('rev-parse',$c);
370 if (scalar @tmp == 1) {
371 push @revs, $tmp[0];
372 } elsif (scalar @tmp > 1) {
373 push @revs, reverse(command('rev-list',@tmp));
374 } else {
375 fatal "Failed to rev-parse $c";
378 my $gs = Git::SVN->new;
379 my ($r_last, $cmt_last) = $gs->last_rev_commit;
380 $gs->fetch;
381 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
382 fatal "There are new revisions that were fetched ",
383 "and need to be merged (or acknowledged) ",
384 "before committing.\nlast rev: $r_last\n",
385 " current: $gs->{last_rev}";
387 $gs->set_tree($_) foreach @revs;
388 print "Done committing ",scalar @revs," revisions to SVN\n";
391 sub cmd_dcommit {
392 my $head = shift;
393 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
394 'Cannot dcommit with a dirty index. Commit your changes first, '
395 . "or stash them with `git stash'.\n";
396 $head ||= 'HEAD';
397 my @refs;
398 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
399 print "Committing to $url ...\n";
400 unless ($gs) {
401 die "Unable to determine upstream SVN information from ",
402 "$head history\n";
404 my $last_rev;
405 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
406 if ($_no_rebase && scalar(@$linear_refs) > 1) {
407 warn "Attempting to commit more than one change while ",
408 "--no-rebase is enabled.\n",
409 "If these changes depend on each other, re-running ",
410 "without --no-rebase will be required."
412 while (1) {
413 my $d = shift @$linear_refs or last;
414 unless (defined $last_rev) {
415 (undef, $last_rev, undef) = cmt_metadata("$d~1");
416 unless (defined $last_rev) {
417 fatal "Unable to extract revision information ",
418 "from commit $d~1";
421 if ($_dry_run) {
422 print "diff-tree $d~1 $d\n";
423 } else {
424 my $cmt_rev;
425 my %ed_opts = ( r => $last_rev,
426 log => get_commit_entry($d)->{log},
427 ra => Git::SVN::Ra->new($gs->full_url),
428 config => SVN::Core::config_get_config(
429 $Git::SVN::Ra::config_dir
431 tree_a => "$d~1",
432 tree_b => $d,
433 editor_cb => sub {
434 print "Committed r$_[0]\n";
435 $cmt_rev = $_[0];
437 svn_path => '');
438 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
439 print "No changes\n$d~1 == $d\n";
440 } elsif ($parents->{$d} && @{$parents->{$d}}) {
441 $gs->{inject_parents_dcommit}->{$cmt_rev} =
442 $parents->{$d};
444 $_fetch_all ? $gs->fetch_all : $gs->fetch;
445 next if $_no_rebase;
447 # we always want to rebase against the current HEAD,
448 # not any head that was passed to us
449 my @diff = command('diff-tree', $d,
450 $gs->refname, '--');
451 my @finish;
452 if (@diff) {
453 @finish = rebase_cmd();
454 print STDERR "W: $d and ", $gs->refname,
455 " differ, using @finish:\n",
456 join("\n", @diff), "\n";
457 } else {
458 print "No changes between current HEAD and ",
459 $gs->refname,
460 "\nResetting to the latest ",
461 $gs->refname, "\n";
462 @finish = qw/reset --mixed/;
464 command_noisy(@finish, $gs->refname);
465 if (@diff) {
466 @refs = ();
467 my ($url_, $rev_, $uuid_, $gs_) =
468 working_head_info($head, \@refs);
469 my ($linear_refs_, $parents_) =
470 linearize_history($gs_, \@refs);
471 if (scalar(@$linear_refs) !=
472 scalar(@$linear_refs_)) {
473 fatal "# of revisions changed ",
474 "\nbefore:\n",
475 join("\n", @$linear_refs),
476 "\n\nafter:\n",
477 join("\n", @$linear_refs_), "\n",
478 'If you are attempting to commit ',
479 "merges, try running:\n\t",
480 'git rebase --interactive',
481 '--preserve-merges ',
482 $gs->refname,
483 "\nBefore dcommitting";
485 if ($url_ ne $url) {
486 fatal "URL mismatch after rebase: ",
487 "$url_ != $url";
489 if ($uuid_ ne $uuid) {
490 fatal "uuid mismatch after rebase: ",
491 "$uuid_ != $uuid";
493 # remap parents
494 my (%p, @l, $i);
495 for ($i = 0; $i < scalar @$linear_refs; $i++) {
496 my $new = $linear_refs_->[$i] or next;
497 $p{$new} =
498 $parents->{$linear_refs->[$i]};
499 push @l, $new;
501 $parents = \%p;
502 $linear_refs = \@l;
504 $last_rev = $cmt_rev;
509 sub cmd_find_rev {
510 my $revision_or_hash = shift;
511 my $result;
512 if ($revision_or_hash =~ /^r\d+$/) {
513 my $head = shift;
514 $head ||= 'HEAD';
515 my @refs;
516 my (undef, undef, undef, $gs) = working_head_info($head, \@refs);
517 unless ($gs) {
518 die "Unable to determine upstream SVN information from ",
519 "$head history\n";
521 my $desired_revision = substr($revision_or_hash, 1);
522 $result = $gs->rev_db_get($desired_revision);
523 } else {
524 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
525 $result = $rev;
527 print "$result\n" if $result;
530 sub cmd_rebase {
531 command_noisy(qw/update-index --refresh/);
532 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
533 unless ($gs) {
534 die "Unable to determine upstream SVN information from ",
535 "working tree history\n";
537 if (command(qw/diff-index HEAD --/)) {
538 print STDERR "Cannot rebase with uncommited changes:\n";
539 command_noisy('status');
540 exit 1;
542 unless ($_local) {
543 $_fetch_all ? $gs->fetch_all : $gs->fetch;
545 command_noisy(rebase_cmd(), $gs->refname);
548 sub cmd_show_ignore {
549 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
550 $gs ||= Git::SVN->new;
551 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
552 $gs->prop_walk($gs->{path}, $r, sub {
553 my ($gs, $path, $props) = @_;
554 print STDOUT "\n# $path\n";
555 my $s = $props->{'svn:ignore'} or return;
556 $s =~ s/[\r\n]+/\n/g;
557 chomp $s;
558 $s =~ s#^#$path#gm;
559 print STDOUT "$s\n";
563 sub cmd_create_ignore {
564 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
565 $gs ||= Git::SVN->new;
566 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
567 $gs->prop_walk($gs->{path}, $r, sub {
568 my ($gs, $path, $props) = @_;
569 # $path is of the form /path/to/dir/
570 my $ignore = '.' . $path . '.gitignore';
571 my $s = $props->{'svn:ignore'} or return;
572 open(GITIGNORE, '>', $ignore)
573 or fatal("Failed to open `$ignore' for writing: $!");
574 $s =~ s/[\r\n]+/\n/g;
575 chomp $s;
576 # Prefix all patterns so that the ignore doesn't apply
577 # to sub-directories.
578 $s =~ s#^#/#gm;
579 print GITIGNORE "$s\n";
580 close(GITIGNORE)
581 or fatal("Failed to close `$ignore': $!");
582 command_noisy('add', $ignore);
586 # get_svnprops(PATH)
587 # ------------------
588 # Helper for cmd_propget and cmd_proplist below.
589 sub get_svnprops {
590 my $path = shift;
591 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
592 $gs ||= Git::SVN->new;
594 # prefix THE PATH by the sub-directory from which the user
595 # invoked us.
596 $path = $cmd_dir_prefix . $path;
597 fatal("No such file or directory: $path") unless -e $path;
598 my $is_dir = -d $path ? 1 : 0;
599 $path = $gs->{path} . '/' . $path;
601 # canonicalize the path (otherwise libsvn will abort or fail to
602 # find the file)
603 # File::Spec->canonpath doesn't collapse x/../y into y (for a
604 # good reason), so let's do this manually.
605 $path =~ s#/+#/#g;
606 $path =~ s#/\.(?:/|$)#/#g;
607 $path =~ s#/[^/]+/\.\.##g;
608 $path =~ s#/$##g;
610 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
611 my $props;
612 if ($is_dir) {
613 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
615 else {
616 (undef, $props) = $gs->ra->get_file($path, $r, undef);
618 return $props;
621 # cmd_propget (PROP, PATH)
622 # ------------------------
623 # Print the SVN property PROP for PATH.
624 sub cmd_propget {
625 my ($prop, $path) = @_;
626 $path = '.' if not defined $path;
627 usage(1) if not defined $prop;
628 my $props = get_svnprops($path);
629 if (not defined $props->{$prop}) {
630 fatal("`$path' does not have a `$prop' SVN property.");
632 print $props->{$prop} . "\n";
635 # cmd_proplist (PATH)
636 # -------------------
637 # Print the list of SVN properties for PATH.
638 sub cmd_proplist {
639 my $path = shift;
640 $path = '.' if not defined $path;
641 my $props = get_svnprops($path);
642 print "Properties on '$path':\n";
643 foreach (sort keys %{$props}) {
644 print " $_\n";
648 sub cmd_multi_init {
649 my $url = shift;
650 unless (defined $_trunk || defined $_branches || defined $_tags) {
651 usage(1);
654 # there are currently some bugs that prevent multi-init/multi-fetch
655 # setups from working well without this.
656 $Git::SVN::_minimize_url = 1;
658 $_prefix = '' unless defined $_prefix;
659 if (defined $url) {
660 $url =~ s#/+$##;
661 init_subdir(@_);
663 do_git_init_db();
664 if (defined $_trunk) {
665 my $trunk_ref = $_prefix . 'trunk';
666 # try both old-style and new-style lookups:
667 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
668 unless ($gs_trunk) {
669 my ($trunk_url, $trunk_path) =
670 complete_svn_url($url, $_trunk);
671 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
672 undef, $trunk_ref);
675 return unless defined $_branches || defined $_tags;
676 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
677 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
678 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
681 sub cmd_multi_fetch {
682 my $remotes = Git::SVN::read_all_remotes();
683 foreach my $repo_id (sort keys %$remotes) {
684 if ($remotes->{$repo_id}->{url}) {
685 Git::SVN::fetch_all($repo_id, $remotes);
690 # this command is special because it requires no metadata
691 sub cmd_commit_diff {
692 my ($ta, $tb, $url) = @_;
693 my $usage = "Usage: $0 commit-diff -r<revision> ".
694 "<tree-ish> <tree-ish> [<URL>]";
695 fatal($usage) if (!defined $ta || !defined $tb);
696 my $svn_path;
697 if (!defined $url) {
698 my $gs = eval { Git::SVN->new };
699 if (!$gs) {
700 fatal("Needed URL or usable git-svn --id in ",
701 "the command-line\n", $usage);
703 $url = $gs->{url};
704 $svn_path = $gs->{path};
706 unless (defined $_revision) {
707 fatal("-r|--revision is a required argument\n", $usage);
709 if (defined $_message && defined $_file) {
710 fatal("Both --message/-m and --file/-F specified ",
711 "for the commit message.\n",
712 "I have no idea what you mean");
714 if (defined $_file) {
715 $_message = file_to_s($_file);
716 } else {
717 $_message ||= get_commit_entry($tb)->{log};
719 my $ra ||= Git::SVN::Ra->new($url);
720 $svn_path ||= $ra->{svn_path};
721 my $r = $_revision;
722 if ($r eq 'HEAD') {
723 $r = $ra->get_latest_revnum;
724 } elsif ($r !~ /^\d+$/) {
725 die "revision argument: $r not understood by git-svn\n";
727 my %ed_opts = ( r => $r,
728 log => $_message,
729 ra => $ra,
730 tree_a => $ta,
731 tree_b => $tb,
732 editor_cb => sub { print "Committed r$_[0]\n" },
733 svn_path => $svn_path );
734 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
735 print "No changes\n$ta == $tb\n";
739 ########################### utility functions #########################
741 sub rebase_cmd {
742 my @cmd = qw/rebase/;
743 push @cmd, '-v' if $_verbose;
744 push @cmd, qw/--merge/ if $_merge;
745 push @cmd, "--strategy=$_strategy" if $_strategy;
746 @cmd;
749 sub post_fetch_checkout {
750 return if $_no_checkout;
751 my $gs = $Git::SVN::_head or return;
752 return if verify_ref('refs/heads/master^0');
754 my $valid_head = verify_ref('HEAD^0');
755 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
756 return if ($valid_head || !verify_ref('HEAD^0'));
758 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
759 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
760 return if -f $index;
762 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
763 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
764 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
765 print STDERR "Checked out HEAD:\n ",
766 $gs->full_url, " r", $gs->last_rev, "\n";
769 sub complete_svn_url {
770 my ($url, $path) = @_;
771 $path =~ s#/+$##;
772 if ($path !~ m#^[a-z\+]+://#) {
773 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
774 fatal("E: '$path' is not a complete URL ",
775 "and a separate URL is not specified");
777 return ($url, $path);
779 return ($path, '');
782 sub complete_url_ls_init {
783 my ($ra, $repo_path, $switch, $pfx) = @_;
784 unless ($repo_path) {
785 print STDERR "W: $switch not specified\n";
786 return;
788 $repo_path =~ s#/+$##;
789 if ($repo_path =~ m#^[a-z\+]+://#) {
790 $ra = Git::SVN::Ra->new($repo_path);
791 $repo_path = '';
792 } else {
793 $repo_path =~ s#^/+##;
794 unless ($ra) {
795 fatal("E: '$repo_path' is not a complete URL ",
796 "and a separate URL is not specified");
799 my $url = $ra->{url};
800 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
801 my $k = "svn-remote.$gs->{repo_id}.url";
802 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
803 if ($orig_url && ($orig_url ne $gs->{url})) {
804 die "$k already set: $orig_url\n",
805 "wanted to set to: $gs->{url}\n";
807 command_oneline('config', $k, $gs->{url}) unless $orig_url;
808 my $remote_path = "$ra->{svn_path}/$repo_path/*";
809 $remote_path =~ s#/+#/#g;
810 $remote_path =~ s#^/##g;
811 my ($n) = ($switch =~ /^--(\w+)/);
812 if (length $pfx && $pfx !~ m#/$#) {
813 die "--prefix='$pfx' must have a trailing slash '/'\n";
815 command_noisy('config', "svn-remote.$gs->{repo_id}.$n",
816 "$remote_path:refs/remotes/$pfx*");
819 sub verify_ref {
820 my ($ref) = @_;
821 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
822 { STDERR => 0 }); };
825 sub get_tree_from_treeish {
826 my ($treeish) = @_;
827 # $treeish can be a symbolic ref, too:
828 my $type = command_oneline(qw/cat-file -t/, $treeish);
829 my $expected;
830 while ($type eq 'tag') {
831 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
833 if ($type eq 'commit') {
834 $expected = (grep /^tree /, command(qw/cat-file commit/,
835 $treeish))[0];
836 ($expected) = ($expected =~ /^tree ($sha1)$/o);
837 die "Unable to get tree from $treeish\n" unless $expected;
838 } elsif ($type eq 'tree') {
839 $expected = $treeish;
840 } else {
841 die "$treeish is a $type, expected tree, tag or commit\n";
843 return $expected;
846 sub get_commit_entry {
847 my ($treeish) = shift;
848 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
849 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
850 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
851 open my $log_fh, '>', $commit_editmsg or croak $!;
853 my $type = command_oneline(qw/cat-file -t/, $treeish);
854 if ($type eq 'commit' || $type eq 'tag') {
855 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
856 $type, $treeish);
857 my $in_msg = 0;
858 while (<$msg_fh>) {
859 if (!$in_msg) {
860 $in_msg = 1 if (/^\s*$/);
861 } elsif (/^git-svn-id: /) {
862 # skip this for now, we regenerate the
863 # correct one on re-fetch anyways
864 # TODO: set *:merge properties or like...
865 } else {
866 print $log_fh $_ or croak $!;
869 command_close_pipe($msg_fh, $ctx);
871 close $log_fh or croak $!;
873 if ($_edit || ($type eq 'tree')) {
874 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
875 # TODO: strip out spaces, comments, like git-commit.sh
876 system($editor, $commit_editmsg);
878 rename $commit_editmsg, $commit_msg or croak $!;
879 open $log_fh, '<', $commit_msg or croak $!;
880 { local $/; chomp($log_entry{log} = <$log_fh>); }
881 close $log_fh or croak $!;
882 unlink $commit_msg;
883 \%log_entry;
886 sub s_to_file {
887 my ($str, $file, $mode) = @_;
888 open my $fd,'>',$file or croak $!;
889 print $fd $str,"\n" or croak $!;
890 close $fd or croak $!;
891 chmod ($mode &~ umask, $file) if (defined $mode);
894 sub file_to_s {
895 my $file = shift;
896 open my $fd,'<',$file or croak "$!: file: $file\n";
897 local $/;
898 my $ret = <$fd>;
899 close $fd or croak $!;
900 $ret =~ s/\s*$//s;
901 return $ret;
904 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
905 sub load_authors {
906 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
907 my $log = $cmd eq 'log';
908 while (<$authors>) {
909 chomp;
910 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
911 my ($user, $name, $email) = ($1, $2, $3);
912 if ($log) {
913 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
914 } else {
915 $users{$user} = [$name, $email];
918 close $authors or croak $!;
921 # convert GetOpt::Long specs for use by git-config
922 sub read_repo_config {
923 return unless -d $ENV{GIT_DIR};
924 my $opts = shift;
925 my @config_only;
926 foreach my $o (keys %$opts) {
927 # if we have mixedCase and a long option-only, then
928 # it's a config-only variable that we don't need for
929 # the command-line.
930 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
931 my $v = $opts->{$o};
932 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
933 $key =~ s/-//g;
934 my $arg = 'git-config';
935 $arg .= ' --int' if ($o =~ /[:=]i$/);
936 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
937 if (ref $v eq 'ARRAY') {
938 chomp(my @tmp = `$arg --get-all svn.$key`);
939 @$v = @tmp if @tmp;
940 } else {
941 chomp(my $tmp = `$arg --get svn.$key`);
942 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
943 $$v = $tmp;
947 delete @$opts{@config_only} if @config_only;
950 sub extract_metadata {
951 my $id = shift or return (undef, undef, undef);
952 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
953 \s([a-f\d\-]+)$/x);
954 if (!defined $rev || !$uuid || !$url) {
955 # some of the original repositories I made had
956 # identifiers like this:
957 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
959 return ($url, $rev, $uuid);
962 sub cmt_metadata {
963 return extract_metadata((grep(/^git-svn-id: /,
964 command(qw/cat-file commit/, shift)))[-1]);
967 sub working_head_info {
968 my ($head, $refs) = @_;
969 my @args = ('log', '--no-color', '--first-parent');
970 my ($fh, $ctx) = command_output_pipe(@args, $head);
971 my $hash;
972 my %max;
973 while (<$fh>) {
974 if ( m{^commit ($::sha1)$} ) {
975 unshift @$refs, $hash if $hash and $refs;
976 $hash = $1;
977 next;
979 next unless s{^\s*(git-svn-id:)}{$1};
980 my ($url, $rev, $uuid) = extract_metadata($_);
981 if (defined $url && defined $rev) {
982 next if $max{$url} and $max{$url} < $rev;
983 if (my $gs = Git::SVN->find_by_url($url)) {
984 my $c = $gs->rev_db_get($rev);
985 if ($c && $c eq $hash) {
986 close $fh; # break the pipe
987 return ($url, $rev, $uuid, $gs);
988 } else {
989 $max{$url} ||= $gs->rev_db_max;
994 command_close_pipe($fh, $ctx);
995 (undef, undef, undef, undef);
998 sub read_commit_parents {
999 my ($parents, $c) = @_;
1000 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1001 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1002 @{$parents->{$c}} = split(/ /, $p);
1005 sub linearize_history {
1006 my ($gs, $refs) = @_;
1007 my %parents;
1008 foreach my $c (@$refs) {
1009 read_commit_parents(\%parents, $c);
1012 my @linear_refs;
1013 my %skip = ();
1014 my $last_svn_commit = $gs->last_commit;
1015 foreach my $c (reverse @$refs) {
1016 next if $c eq $last_svn_commit;
1017 last if $skip{$c};
1019 unshift @linear_refs, $c;
1020 $skip{$c} = 1;
1022 # we only want the first parent to diff against for linear
1023 # history, we save the rest to inject when we finalize the
1024 # svn commit
1025 my $fp_a = verify_ref("$c~1");
1026 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1027 if (!$fp_a || !$fp_b) {
1028 die "Commit $c\n",
1029 "has no parent commit, and therefore ",
1030 "nothing to diff against.\n",
1031 "You should be working from a repository ",
1032 "originally created by git-svn\n";
1034 if ($fp_a ne $fp_b) {
1035 die "$c~1 = $fp_a, however parsing commit $c ",
1036 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1039 foreach my $p (@{$parents{$c}}) {
1040 $skip{$p} = 1;
1043 (\@linear_refs, \%parents);
1046 package Git::SVN;
1047 use strict;
1048 use warnings;
1049 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1050 $_repack $_repack_flags $_use_svm_props $_head
1051 $_use_svnsync_props $no_reuse_existing $_minimize_url/;
1052 use Carp qw/croak/;
1053 use File::Path qw/mkpath/;
1054 use File::Copy qw/copy/;
1055 use IPC::Open3;
1057 my $_repack_nr;
1058 # properties that we do not log:
1059 my %SKIP_PROP;
1060 BEGIN {
1061 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1062 svn:special svn:executable
1063 svn:entry:committed-rev
1064 svn:entry:last-author
1065 svn:entry:uuid
1066 svn:entry:committed-date/;
1068 # some options are read globally, but can be overridden locally
1069 # per [svn-remote "..."] section. Command-line options will *NOT*
1070 # override options set in an [svn-remote "..."] section
1071 no strict 'refs';
1072 for my $option (qw/follow_parent no_metadata use_svm_props
1073 use_svnsync_props/) {
1074 my $key = $option;
1075 $key =~ tr/_//d;
1076 my $prop = "-$option";
1077 *$option = sub {
1078 my ($self) = @_;
1079 return $self->{$prop} if exists $self->{$prop};
1080 my $k = "svn-remote.$self->{repo_id}.$key";
1081 eval { command_oneline(qw/config --get/, $k) };
1082 if ($@) {
1083 $self->{$prop} = ${"Git::SVN::_$option"};
1084 } else {
1085 my $v = command_oneline(qw/config --bool/,$k);
1086 $self->{$prop} = $v eq 'false' ? 0 : 1;
1088 return $self->{$prop};
1093 my %LOCKFILES;
1094 END { unlink keys %LOCKFILES if %LOCKFILES }
1096 sub resolve_local_globs {
1097 my ($url, $fetch, $glob_spec) = @_;
1098 return unless defined $glob_spec;
1099 my $ref = $glob_spec->{ref};
1100 my $path = $glob_spec->{path};
1101 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1102 next unless m#^refs/remotes/$ref->{regex}$#;
1103 my $p = $1;
1104 my $pathname = desanitize_refname($path->full_path($p));
1105 my $refname = desanitize_refname($ref->full_path($p));
1106 if (my $existing = $fetch->{$pathname}) {
1107 if ($existing ne $refname) {
1108 die "Refspec conflict:\n",
1109 "existing: refs/remotes/$existing\n",
1110 " globbed: refs/remotes/$refname\n";
1112 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1113 $u =~ s!^\Q$url\E(/|$)!! or die
1114 "refs/remotes/$refname: '$url' not found in '$u'\n";
1115 if ($pathname ne $u) {
1116 warn "W: Refspec glob conflict ",
1117 "(ref: refs/remotes/$refname):\n",
1118 "expected path: $pathname\n",
1119 " real path: $u\n",
1120 "Continuing ahead with $u\n";
1121 next;
1123 } else {
1124 $fetch->{$pathname} = $refname;
1129 sub parse_revision_argument {
1130 my ($base, $head) = @_;
1131 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1132 return ($base, $head);
1134 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1135 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1136 return ($head, $head) if ($::_revision eq 'HEAD');
1137 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1138 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1139 die "revision argument: $::_revision not understood by git-svn\n";
1142 sub fetch_all {
1143 my ($repo_id, $remotes) = @_;
1144 if (ref $repo_id) {
1145 my $gs = $repo_id;
1146 $repo_id = undef;
1147 $repo_id = $gs->{repo_id};
1149 $remotes ||= read_all_remotes();
1150 my $remote = $remotes->{$repo_id} or
1151 die "[svn-remote \"$repo_id\"] unknown\n";
1152 my $fetch = $remote->{fetch};
1153 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1154 my (@gs, @globs);
1155 my $ra = Git::SVN::Ra->new($url);
1156 my $uuid = $ra->get_uuid;
1157 my $head = $ra->get_latest_revnum;
1158 my $base = defined $fetch ? $head : 0;
1160 # read the max revs for wildcard expansion (branches/*, tags/*)
1161 foreach my $t (qw/branches tags/) {
1162 defined $remote->{$t} or next;
1163 push @globs, $remote->{$t};
1164 my $max_rev = eval { tmp_config(qw/--int --get/,
1165 "svn-remote.$repo_id.${t}-maxRev") };
1166 if (defined $max_rev && ($max_rev < $base)) {
1167 $base = $max_rev;
1168 } elsif (!defined $max_rev) {
1169 $base = 0;
1173 if ($fetch) {
1174 foreach my $p (sort keys %$fetch) {
1175 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1176 my $lr = $gs->rev_db_max;
1177 if (defined $lr) {
1178 $base = $lr if ($lr < $base);
1180 push @gs, $gs;
1184 ($base, $head) = parse_revision_argument($base, $head);
1185 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1188 sub read_all_remotes {
1189 my $r = {};
1190 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1191 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*refs/remotes/(.+)\s*$!) {
1192 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1193 $local_ref =~ s{^/}{};
1194 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1195 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1196 $r->{$1}->{url} = $2;
1197 } elsif (m!^(.+)\.(branches|tags)=
1198 (.*):refs/remotes/(.+)\s*$/!x) {
1199 my ($p, $g) = ($3, $4);
1200 my $rs = $r->{$1}->{$2} = {
1201 t => $2,
1202 remote => $1,
1203 path => Git::SVN::GlobSpec->new($p),
1204 ref => Git::SVN::GlobSpec->new($g) };
1205 if (length($rs->{ref}->{right}) != 0) {
1206 die "The '*' glob character must be the last ",
1207 "character of '$g'\n";
1214 sub init_vars {
1215 if (defined $_repack) {
1216 $_repack = 1000 if ($_repack <= 0);
1217 $_repack_nr = $_repack;
1218 $_repack_flags ||= '-d';
1222 sub verify_remotes_sanity {
1223 return unless -d $ENV{GIT_DIR};
1224 my %seen;
1225 foreach (command(qw/config -l/)) {
1226 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1227 if ($seen{$1}) {
1228 die "Remote ref refs/remote/$1 is tracked by",
1229 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1230 "Please resolve this ambiguity in ",
1231 "your git configuration file before ",
1232 "continuing\n";
1234 $seen{$1} = $_;
1239 # we allow more chars than remotes2config.sh...
1240 sub sanitize_remote_name {
1241 my ($name) = @_;
1242 $name =~ tr{A-Za-z0-9:,/+-}{.}c;
1243 $name;
1246 sub find_existing_remote {
1247 my ($url, $remotes) = @_;
1248 return undef if $no_reuse_existing;
1249 my $existing;
1250 foreach my $repo_id (keys %$remotes) {
1251 my $u = $remotes->{$repo_id}->{url} or next;
1252 next if $u ne $url;
1253 $existing = $repo_id;
1254 last;
1256 $existing;
1259 sub init_remote_config {
1260 my ($self, $url, $no_write) = @_;
1261 $url =~ s!/+$!!; # strip trailing slash
1262 my $r = read_all_remotes();
1263 my $existing = find_existing_remote($url, $r);
1264 if ($existing) {
1265 unless ($no_write) {
1266 print STDERR "Using existing ",
1267 "[svn-remote \"$existing\"]\n";
1269 $self->{repo_id} = $existing;
1270 } elsif ($_minimize_url) {
1271 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1272 $existing = find_existing_remote($min_url, $r);
1273 if ($existing) {
1274 unless ($no_write) {
1275 print STDERR "Using existing ",
1276 "[svn-remote \"$existing\"]\n";
1278 $self->{repo_id} = $existing;
1280 if ($min_url ne $url) {
1281 unless ($no_write) {
1282 print STDERR "Using higher level of URL: ",
1283 "$url => $min_url\n";
1285 my $old_path = $self->{path};
1286 $self->{path} = $url;
1287 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1288 if (length $old_path) {
1289 $self->{path} .= "/$old_path";
1291 $url = $min_url;
1294 my $orig_url;
1295 if (!$existing) {
1296 # verify that we aren't overwriting anything:
1297 $orig_url = eval {
1298 command_oneline('config', '--get',
1299 "svn-remote.$self->{repo_id}.url")
1301 if ($orig_url && ($orig_url ne $url)) {
1302 die "svn-remote.$self->{repo_id}.url already set: ",
1303 "$orig_url\nwanted to set to: $url\n";
1306 my ($xrepo_id, $xpath) = find_ref($self->refname);
1307 if (defined $xpath) {
1308 die "svn-remote.$xrepo_id.fetch already set to track ",
1309 "$xpath:refs/remotes/", $self->refname, "\n";
1311 unless ($no_write) {
1312 command_noisy('config',
1313 "svn-remote.$self->{repo_id}.url", $url);
1314 $self->{path} =~ s{^/}{};
1315 command_noisy('config', '--add',
1316 "svn-remote.$self->{repo_id}.fetch",
1317 "$self->{path}:".$self->refname);
1319 $self->{url} = $url;
1322 sub find_by_url { # repos_root and, path are optional
1323 my ($class, $full_url, $repos_root, $path) = @_;
1325 return undef unless defined $full_url;
1326 remove_username($full_url);
1327 remove_username($repos_root) if defined $repos_root;
1328 my $remotes = read_all_remotes();
1329 if (defined $full_url && defined $repos_root && !defined $path) {
1330 $path = $full_url;
1331 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1333 foreach my $repo_id (keys %$remotes) {
1334 my $u = $remotes->{$repo_id}->{url} or next;
1335 remove_username($u);
1336 next if defined $repos_root && $repos_root ne $u;
1338 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1339 foreach (qw/branches tags/) {
1340 resolve_local_globs($u, $fetch,
1341 $remotes->{$repo_id}->{$_});
1343 my $p = $path;
1344 unless (defined $p) {
1345 $p = $full_url;
1346 $p =~ s#^\Q$u\E(?:/|$)## or next;
1348 foreach my $f (keys %$fetch) {
1349 next if $f ne $p;
1350 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1353 undef;
1356 sub init {
1357 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1358 my $self = _new($class, $repo_id, $ref_id, $path);
1359 if (defined $url) {
1360 $self->init_remote_config($url, $no_write);
1362 $self;
1365 sub find_ref {
1366 my ($ref_id) = @_;
1367 foreach (command(qw/config -l/)) {
1368 next unless m!^svn-remote\.(.+)\.fetch=
1369 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1370 my ($repo_id, $path, $ref) = ($1, $2, $3);
1371 if ($ref eq $ref_id) {
1372 $path = '' if ($path =~ m#^\./?#);
1373 return ($repo_id, $path);
1376 (undef, undef, undef);
1379 sub new {
1380 my ($class, $ref_id, $repo_id, $path) = @_;
1381 if (defined $ref_id && !defined $repo_id && !defined $path) {
1382 ($repo_id, $path) = find_ref($ref_id);
1383 if (!defined $repo_id) {
1384 die "Could not find a \"svn-remote.*.fetch\" key ",
1385 "in the repository configuration matching: ",
1386 "refs/remotes/$ref_id\n";
1389 my $self = _new($class, $repo_id, $ref_id, $path);
1390 if (!defined $self->{path} || !length $self->{path}) {
1391 my $fetch = command_oneline('config', '--get',
1392 "svn-remote.$repo_id.fetch",
1393 ":refs/remotes/$ref_id\$") or
1394 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1395 "\":refs/remotes/$ref_id\$\" in config\n";
1396 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1398 $self->{url} = command_oneline('config', '--get',
1399 "svn-remote.$repo_id.url") or
1400 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1401 $self->rebuild;
1402 $self;
1405 sub refname {
1406 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1408 # It cannot end with a slash /, we'll throw up on this because
1409 # SVN can't have directories with a slash in their name, either:
1410 if ($refname =~ m{/$}) {
1411 die "ref: '$refname' ends with a trailing slash, this is ",
1412 "not permitted by git nor Subversion\n";
1415 # It cannot have ASCII control character space, tilde ~, caret ^,
1416 # colon :, question-mark ?, asterisk *, space, or open bracket [
1417 # anywhere.
1419 # Additionally, % must be escaped because it is used for escaping
1420 # and we want our escaped refname to be reversible
1421 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1423 # no slash-separated component can begin with a dot .
1424 # /.* becomes /%2E*
1425 $refname =~ s{/\.}{/%2E}g;
1427 # It cannot have two consecutive dots .. anywhere
1428 # .. becomes %2E%2E
1429 $refname =~ s{\.\.}{%2E%2E}g;
1431 return $refname;
1434 sub desanitize_refname {
1435 my ($refname) = @_;
1436 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1437 return $refname;
1440 sub svm_uuid {
1441 my ($self) = @_;
1442 return $self->{svm}->{uuid} if $self->svm;
1443 $self->ra;
1444 unless ($self->{svm}) {
1445 die "SVM UUID not cached, and reading remotely failed\n";
1447 $self->{svm}->{uuid};
1450 sub svm {
1451 my ($self) = @_;
1452 return $self->{svm} if $self->{svm};
1453 my $svm;
1454 # see if we have it in our config, first:
1455 eval {
1456 my $section = "svn-remote.$self->{repo_id}";
1457 $svm = {
1458 source => tmp_config('--get', "$section.svm-source"),
1459 uuid => tmp_config('--get', "$section.svm-uuid"),
1460 replace => tmp_config('--get', "$section.svm-replace"),
1463 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1464 $self->{svm} = $svm;
1466 $self->{svm};
1469 sub _set_svm_vars {
1470 my ($self, $ra) = @_;
1471 return $ra if $self->svm;
1473 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1474 "(svm:source, svm:uuid) ",
1475 "from the following URLs:\n" );
1476 sub read_svm_props {
1477 my ($self, $ra, $path, $r) = @_;
1478 my $props = ($ra->get_dir($path, $r))[2];
1479 my $src = $props->{'svm:source'};
1480 my $uuid = $props->{'svm:uuid'};
1481 return undef if (!$src || !$uuid);
1483 chomp($src, $uuid);
1485 $uuid =~ m{^[0-9a-f\-]{30,}$}
1486 or die "doesn't look right - svm:uuid is '$uuid'\n";
1488 # the '!' is used to mark the repos_root!/relative/path
1489 $src =~ s{/?!/?}{/};
1490 $src =~ s{/+$}{}; # no trailing slashes please
1491 # username is of no interest
1492 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1494 my $replace = $ra->{url};
1495 $replace .= "/$path" if length $path;
1497 my $section = "svn-remote.$self->{repo_id}";
1498 tmp_config("$section.svm-source", $src);
1499 tmp_config("$section.svm-replace", $replace);
1500 tmp_config("$section.svm-uuid", $uuid);
1501 $self->{svm} = {
1502 source => $src,
1503 uuid => $uuid,
1504 replace => $replace
1508 my $r = $ra->get_latest_revnum;
1509 my $path = $self->{path};
1510 my %tried;
1511 while (length $path) {
1512 unless ($tried{"$self->{url}/$path"}) {
1513 return $ra if $self->read_svm_props($ra, $path, $r);
1514 $tried{"$self->{url}/$path"} = 1;
1516 $path =~ s#/?[^/]+$##;
1518 die "Path: '$path' should be ''\n" if $path ne '';
1519 return $ra if $self->read_svm_props($ra, $path, $r);
1520 $tried{"$self->{url}/$path"} = 1;
1522 if ($ra->{repos_root} eq $self->{url}) {
1523 die @err, (map { " $_\n" } keys %tried), "\n";
1526 # nope, make sure we're connected to the repository root:
1527 my $ok;
1528 my @tried_b;
1529 $path = $ra->{svn_path};
1530 $ra = Git::SVN::Ra->new($ra->{repos_root});
1531 while (length $path) {
1532 unless ($tried{"$ra->{url}/$path"}) {
1533 $ok = $self->read_svm_props($ra, $path, $r);
1534 last if $ok;
1535 $tried{"$ra->{url}/$path"} = 1;
1537 $path =~ s#/?[^/]+$##;
1539 die "Path: '$path' should be ''\n" if $path ne '';
1540 $ok ||= $self->read_svm_props($ra, $path, $r);
1541 $tried{"$ra->{url}/$path"} = 1;
1542 if (!$ok) {
1543 die @err, (map { " $_\n" } keys %tried), "\n";
1545 Git::SVN::Ra->new($self->{url});
1548 sub svnsync {
1549 my ($self) = @_;
1550 return $self->{svnsync} if $self->{svnsync};
1552 if ($self->no_metadata) {
1553 die "Can't have both 'noMetadata' and ",
1554 "'useSvnsyncProps' options set!\n";
1556 if ($self->rewrite_root) {
1557 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1558 "options set!\n";
1561 my $svnsync;
1562 # see if we have it in our config, first:
1563 eval {
1564 my $section = "svn-remote.$self->{repo_id}";
1565 $svnsync = {
1566 url => tmp_config('--get', "$section.svnsync-url"),
1567 uuid => tmp_config('--get', "$section.svnsync-uuid"),
1570 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1571 return $self->{svnsync} = $svnsync;
1574 my $err = "useSvnsyncProps set, but failed to read " .
1575 "svnsync property: svn:sync-from-";
1576 my $rp = $self->ra->rev_proplist(0);
1578 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1579 $url =~ m{^[a-z\+]+://} or
1580 die "doesn't look right - svn:sync-from-url is '$url'\n";
1582 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1583 $uuid =~ m{^[0-9a-f\-]{30,}$} or
1584 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1586 my $section = "svn-remote.$self->{repo_id}";
1587 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1588 tmp_config('--add', "$section.svnsync-url", $url);
1589 return $self->{svnsync} = { url => $url, uuid => $uuid };
1592 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1593 # remote lookup (useful for 'git svn log').
1594 sub ra_uuid {
1595 my ($self) = @_;
1596 unless ($self->{ra_uuid}) {
1597 my $key = "svn-remote.$self->{repo_id}.uuid";
1598 my $uuid = eval { tmp_config('--get', $key) };
1599 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1600 $self->{ra_uuid} = $uuid;
1601 } else {
1602 die "ra_uuid called without URL\n" unless $self->{url};
1603 $self->{ra_uuid} = $self->ra->get_uuid;
1604 tmp_config('--add', $key, $self->{ra_uuid});
1607 $self->{ra_uuid};
1610 sub ra {
1611 my ($self) = shift;
1612 my $ra = Git::SVN::Ra->new($self->{url});
1613 if ($self->use_svm_props && !$self->{svm}) {
1614 if ($self->no_metadata) {
1615 die "Can't have both 'noMetadata' and ",
1616 "'useSvmProps' options set!\n";
1617 } elsif ($self->use_svnsync_props) {
1618 die "Can't have both 'useSvnsyncProps' and ",
1619 "'useSvmProps' options set!\n";
1621 $ra = $self->_set_svm_vars($ra);
1622 $self->{-want_revprops} = 1;
1624 $ra;
1627 sub rel_path {
1628 my ($self) = @_;
1629 my $repos_root = $self->ra->{repos_root};
1630 return $self->{path} if ($self->{url} eq $repos_root);
1631 my $url = $self->{url} .
1632 (length $self->{path} ? "/$self->{path}" : $self->{path});
1633 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1634 $url;
1637 # prop_walk(PATH, REV, SUB)
1638 # -------------------------
1639 # Recursively traverse PATH at revision REV and invoke SUB for each
1640 # directory that contains a SVN property. SUB will be invoked as
1641 # follows: &SUB(gs, path, props); where `gs' is this instance of
1642 # Git::SVN, `path' the path to the directory where the properties
1643 # `props' were found. The `path' will be relative to point of checkout,
1644 # that is, if url://repo/trunk is the current Git branch, and that
1645 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1646 # as `path' (note the trailing `/').
1647 sub prop_walk {
1648 my ($self, $path, $rev, $sub) = @_;
1650 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1651 $path =~ s#^/*#/#g;
1652 my $p = $path;
1653 # Strip the irrelevant part of the path.
1654 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1655 # Ensure the path is terminated by a `/'.
1656 $p =~ s#/*$#/#;
1658 # The properties contain all the internal SVN stuff nobody
1659 # (usually) cares about.
1660 my $interesting_props = 0;
1661 foreach (keys %{$props}) {
1662 # If it doesn't start with `svn:', it must be a
1663 # user-defined property.
1664 ++$interesting_props and next if $_ !~ /^svn:/;
1665 # FIXME: Fragile, if SVN adds new public properties,
1666 # this needs to be updated.
1667 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1668 |eol-style|mime-type
1669 |externals|needs-lock)$/x;
1671 &$sub($self, $p, $props) if $interesting_props;
1673 foreach (sort keys %$dirent) {
1674 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1675 $self->prop_walk($path . '/' . $_, $rev, $sub);
1679 sub last_rev { ($_[0]->last_rev_commit)[0] }
1680 sub last_commit { ($_[0]->last_rev_commit)[1] }
1682 # returns the newest SVN revision number and newest commit SHA1
1683 sub last_rev_commit {
1684 my ($self) = @_;
1685 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1686 return ($self->{last_rev}, $self->{last_commit});
1688 my $c = ::verify_ref($self->refname.'^0');
1689 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1690 my $rev = (::cmt_metadata($c))[1];
1691 if (defined $rev) {
1692 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1693 return ($rev, $c);
1696 my $db_path = $self->db_path;
1697 unless (-e $db_path) {
1698 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1699 return (undef, undef);
1701 my $offset = -41; # from tail
1702 my $rl;
1703 open my $fh, '<', $db_path or croak "$db_path not readable: $!\n";
1704 sysseek($fh, $offset, 2); # don't care for errors
1705 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1706 chomp $rl;
1707 while (('0' x40) eq $rl && sysseek($fh, 0, 1) != 0) {
1708 $offset -= 41;
1709 sysseek($fh, $offset, 2); # don't care for errors
1710 sysread($fh, $rl, 41) == 41 or return (undef, undef);
1711 chomp $rl;
1713 if ($c && $c ne $rl) {
1714 die "$db_path and ", $self->refname,
1715 " inconsistent!:\n$c != $rl\n";
1717 my $rev = sysseek($fh, 0, 1) or croak $!;
1718 $rev = ($rev - 41) / 41;
1719 close $fh or croak $!;
1720 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1721 return ($rev, $c);
1724 sub get_fetch_range {
1725 my ($self, $min, $max) = @_;
1726 $max ||= $self->ra->get_latest_revnum;
1727 $min ||= $self->rev_db_max;
1728 (++$min, $max);
1731 sub tmp_config {
1732 my (@args) = @_;
1733 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
1734 my $config = "$ENV{GIT_DIR}/svn/.metadata";
1735 if (! -f $config && -f $old_def_config) {
1736 rename $old_def_config, $config or
1737 die "Failed rename $old_def_config => $config: $!\n";
1739 my $old_config = $ENV{GIT_CONFIG};
1740 $ENV{GIT_CONFIG} = $config;
1741 $@ = undef;
1742 my @ret = eval {
1743 unless (-f $config) {
1744 mkfile($config);
1745 open my $fh, '>', $config or
1746 die "Can't open $config: $!\n";
1747 print $fh "; This file is used internally by ",
1748 "git-svn\n" or die
1749 "Couldn't write to $config: $!\n";
1750 print $fh "; You should not have to edit it\n" or
1751 die "Couldn't write to $config: $!\n";
1752 close $fh or die "Couldn't close $config: $!\n";
1754 command('config', @args);
1756 my $err = $@;
1757 if (defined $old_config) {
1758 $ENV{GIT_CONFIG} = $old_config;
1759 } else {
1760 delete $ENV{GIT_CONFIG};
1762 die $err if $err;
1763 wantarray ? @ret : $ret[0];
1766 sub tmp_index_do {
1767 my ($self, $sub) = @_;
1768 my $old_index = $ENV{GIT_INDEX_FILE};
1769 $ENV{GIT_INDEX_FILE} = $self->{index};
1770 $@ = undef;
1771 my @ret = eval {
1772 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
1773 mkpath([$dir]) unless -d $dir;
1774 &$sub;
1776 my $err = $@;
1777 if (defined $old_index) {
1778 $ENV{GIT_INDEX_FILE} = $old_index;
1779 } else {
1780 delete $ENV{GIT_INDEX_FILE};
1782 die $err if $err;
1783 wantarray ? @ret : $ret[0];
1786 sub assert_index_clean {
1787 my ($self, $treeish) = @_;
1789 $self->tmp_index_do(sub {
1790 command_noisy('read-tree', $treeish) unless -e $self->{index};
1791 my $x = command_oneline('write-tree');
1792 my ($y) = (command(qw/cat-file commit/, $treeish) =~
1793 /^tree ($::sha1)/mo);
1794 return if $y eq $x;
1796 warn "Index mismatch: $y != $x\nrereading $treeish\n";
1797 unlink $self->{index} or die "unlink $self->{index}: $!\n";
1798 command_noisy('read-tree', $treeish);
1799 $x = command_oneline('write-tree');
1800 if ($y ne $x) {
1801 ::fatal "trees ($treeish) $y != $x\n",
1802 "Something is seriously wrong...";
1807 sub get_commit_parents {
1808 my ($self, $log_entry) = @_;
1809 my (%seen, @ret, @tmp);
1810 # legacy support for 'set-tree'; this is only used by set_tree_cb:
1811 if (my $ip = $self->{inject_parents}) {
1812 if (my $commit = delete $ip->{$log_entry->{revision}}) {
1813 push @tmp, $commit;
1816 if (my $cur = ::verify_ref($self->refname.'^0')) {
1817 push @tmp, $cur;
1819 if (my $ipd = $self->{inject_parents_dcommit}) {
1820 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
1821 push @tmp, @$commit;
1824 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
1825 while (my $p = shift @tmp) {
1826 next if $seen{$p};
1827 $seen{$p} = 1;
1828 push @ret, $p;
1829 # MAXPARENT is defined to 16 in commit-tree.c:
1830 last if @ret >= 16;
1832 if (@tmp) {
1833 die "r$log_entry->{revision}: No room for parents:\n\t",
1834 join("\n\t", @tmp), "\n";
1836 @ret;
1839 sub rewrite_root {
1840 my ($self) = @_;
1841 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
1842 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
1843 my $rwr = eval { command_oneline(qw/config --get/, $k) };
1844 if ($rwr) {
1845 $rwr =~ s#/+$##;
1846 if ($rwr !~ m#^[a-z\+]+://#) {
1847 die "$rwr is not a valid URL (key: $k)\n";
1850 $self->{-rewrite_root} = $rwr;
1853 sub metadata_url {
1854 my ($self) = @_;
1855 ($self->rewrite_root || $self->{url}) .
1856 (length $self->{path} ? '/' . $self->{path} : '');
1859 sub full_url {
1860 my ($self) = @_;
1861 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
1864 sub do_git_commit {
1865 my ($self, $log_entry) = @_;
1866 my $lr = $self->last_rev;
1867 if (defined $lr && $lr >= $log_entry->{revision}) {
1868 die "Last fetched revision of ", $self->refname,
1869 " was r$lr, but we are about to fetch: ",
1870 "r$log_entry->{revision}!\n";
1872 if (my $c = $self->rev_db_get($log_entry->{revision})) {
1873 croak "$log_entry->{revision} = $c already exists! ",
1874 "Why are we refetching it?\n";
1876 $ENV{GIT_AUTHOR_NAME} = $ENV{GIT_COMMITTER_NAME} = $log_entry->{name};
1877 $ENV{GIT_AUTHOR_EMAIL} = $ENV{GIT_COMMITTER_EMAIL} =
1878 $log_entry->{email};
1879 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
1881 my $tree = $log_entry->{tree};
1882 if (!defined $tree) {
1883 $tree = $self->tmp_index_do(sub {
1884 command_oneline('write-tree') });
1886 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
1888 my @exec = ('git-commit-tree', $tree);
1889 foreach ($self->get_commit_parents($log_entry)) {
1890 push @exec, '-p', $_;
1892 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
1893 or croak $!;
1894 print $msg_fh $log_entry->{log} or croak $!;
1895 unless ($self->no_metadata) {
1896 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
1897 or croak $!;
1899 $msg_fh->flush == 0 or croak $!;
1900 close $msg_fh or croak $!;
1901 chomp(my $commit = do { local $/; <$out_fh> });
1902 close $out_fh or croak $!;
1903 waitpid $pid, 0;
1904 croak $? if $?;
1905 if ($commit !~ /^$::sha1$/o) {
1906 die "Failed to commit, invalid sha1: $commit\n";
1909 $self->rev_db_set($log_entry->{revision}, $commit, 1);
1911 $self->{last_rev} = $log_entry->{revision};
1912 $self->{last_commit} = $commit;
1913 print "r$log_entry->{revision}";
1914 if (defined $log_entry->{svm_revision}) {
1915 print " (\@$log_entry->{svm_revision})";
1916 $self->rev_db_set($log_entry->{svm_revision}, $commit,
1917 0, $self->svm_uuid);
1919 print " = $commit ($self->{ref_id})\n";
1920 if (defined $_repack && (--$_repack_nr == 0)) {
1921 $_repack_nr = $_repack;
1922 # repack doesn't use any arguments with spaces in them, does it?
1923 print "Running git repack $_repack_flags ...\n";
1924 command_noisy('repack', split(/\s+/, $_repack_flags));
1925 print "Done repacking\n";
1927 return $commit;
1930 sub match_paths {
1931 my ($self, $paths, $r) = @_;
1932 return 1 if $self->{path} eq '';
1933 if (my $path = $paths->{"/$self->{path}"}) {
1934 return ($path->{action} eq 'D') ? 0 : 1;
1936 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
1937 if (grep /$self->{path_regex}/, keys %$paths) {
1938 return 1;
1940 my $c = '';
1941 foreach (split m#/#, $self->{path}) {
1942 $c .= "/$_";
1943 next unless ($paths->{$c} &&
1944 ($paths->{$c}->{action} =~ /^[AR]$/));
1945 if ($self->ra->check_path($self->{path}, $r) ==
1946 $SVN::Node::dir) {
1947 return 1;
1950 return 0;
1953 sub find_parent_branch {
1954 my ($self, $paths, $rev) = @_;
1955 return undef unless $self->follow_parent;
1956 unless (defined $paths) {
1957 my $err_handler = $SVN::Error::handler;
1958 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
1959 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
1960 $paths =
1961 Git::SVN::Ra::dup_changed_paths($_[0]) });
1962 $SVN::Error::handler = $err_handler;
1964 return undef unless defined $paths;
1966 # look for a parent from another branch:
1967 my @b_path_components = split m#/#, $self->rel_path;
1968 my @a_path_components;
1969 my $i;
1970 while (@b_path_components) {
1971 $i = $paths->{'/'.join('/', @b_path_components)};
1972 last if $i && defined $i->{copyfrom_path};
1973 unshift(@a_path_components, pop(@b_path_components));
1975 return undef unless defined $i && defined $i->{copyfrom_path};
1976 my $branch_from = $i->{copyfrom_path};
1977 if (@a_path_components) {
1978 print STDERR "branch_from: $branch_from => ";
1979 $branch_from .= '/'.join('/', @a_path_components);
1980 print STDERR $branch_from, "\n";
1982 my $r = $i->{copyfrom_rev};
1983 my $repos_root = $self->ra->{repos_root};
1984 my $url = $self->ra->{url};
1985 my $new_url = $repos_root . $branch_from;
1986 print STDERR "Found possible branch point: ",
1987 "$new_url => ", $self->full_url, ", $r\n";
1988 $branch_from =~ s#^/##;
1989 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
1990 unless ($gs) {
1991 my $ref_id = $self->{ref_id};
1992 $ref_id =~ s/\@\d+$//;
1993 $ref_id .= "\@$r";
1994 # just grow a tail if we're not unique enough :x
1995 $ref_id .= '-' while find_ref($ref_id);
1996 print STDERR "Initializing parent: $ref_id\n";
1997 $gs = Git::SVN->init($new_url, '', $ref_id, $ref_id, 1);
1999 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2000 if (!defined $r0 || !defined $parent) {
2001 my ($base, $head) = parse_revision_argument(0, $r);
2002 if ($base <= $r) {
2003 $gs->fetch($base, $r);
2005 ($r0, $parent) = $gs->last_rev_commit;
2007 if (defined $r0 && defined $parent) {
2008 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2009 my $ed;
2010 if ($self->ra->can_do_switch) {
2011 $self->assert_index_clean($parent);
2012 print STDERR "Following parent with do_switch\n";
2013 # do_switch works with svn/trunk >= r22312, but that
2014 # is not included with SVN 1.4.3 (the latest version
2015 # at the moment), so we can't rely on it
2016 $self->{last_commit} = $parent;
2017 $ed = SVN::Git::Fetcher->new($self);
2018 $gs->ra->gs_do_switch($r0, $rev, $gs,
2019 $self->full_url, $ed)
2020 or die "SVN connection failed somewhere...\n";
2021 } elsif ($self->ra->trees_match($new_url, $r0,
2022 $self->full_url, $rev)) {
2023 print STDERR "Trees match:\n",
2024 " $new_url\@$r0\n",
2025 " ${\$self->full_url}\@$rev\n",
2026 "Following parent with no changes\n";
2027 $self->tmp_index_do(sub {
2028 command_noisy('read-tree', $parent);
2030 $self->{last_commit} = $parent;
2031 } else {
2032 print STDERR "Following parent with do_update\n";
2033 $ed = SVN::Git::Fetcher->new($self);
2034 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2035 or die "SVN connection failed somewhere...\n";
2037 print STDERR "Successfully followed parent\n";
2038 return $self->make_log_entry($rev, [$parent], $ed);
2040 return undef;
2043 sub do_fetch {
2044 my ($self, $paths, $rev) = @_;
2045 my $ed;
2046 my ($last_rev, @parents);
2047 if (my $lc = $self->last_commit) {
2048 # we can have a branch that was deleted, then re-added
2049 # under the same name but copied from another path, in
2050 # which case we'll have multiple parents (we don't
2051 # want to break the original ref, nor lose copypath info):
2052 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2053 push @{$log_entry->{parents}}, $lc;
2054 return $log_entry;
2056 $ed = SVN::Git::Fetcher->new($self);
2057 $last_rev = $self->{last_rev};
2058 $ed->{c} = $lc;
2059 @parents = ($lc);
2060 } else {
2061 $last_rev = $rev;
2062 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2063 return $log_entry;
2065 $ed = SVN::Git::Fetcher->new($self);
2067 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2068 die "SVN connection failed somewhere...\n";
2070 $self->make_log_entry($rev, \@parents, $ed);
2073 sub get_untracked {
2074 my ($self, $ed) = @_;
2075 my @out;
2076 my $h = $ed->{empty};
2077 foreach (sort keys %$h) {
2078 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2079 push @out, " $act: " . uri_encode($_);
2080 warn "W: $act: $_\n";
2082 foreach my $t (qw/dir_prop file_prop/) {
2083 $h = $ed->{$t} or next;
2084 foreach my $path (sort keys %$h) {
2085 my $ppath = $path eq '' ? '.' : $path;
2086 foreach my $prop (sort keys %{$h->{$path}}) {
2087 next if $SKIP_PROP{$prop};
2088 my $v = $h->{$path}->{$prop};
2089 my $t_ppath_prop = "$t: " .
2090 uri_encode($ppath) . ' ' .
2091 uri_encode($prop);
2092 if (defined $v) {
2093 push @out, " +$t_ppath_prop " .
2094 uri_encode($v);
2095 } else {
2096 push @out, " -$t_ppath_prop";
2101 foreach my $t (qw/absent_file absent_directory/) {
2102 $h = $ed->{$t} or next;
2103 foreach my $parent (sort keys %$h) {
2104 foreach my $path (sort @{$h->{$parent}}) {
2105 push @out, " $t: " .
2106 uri_encode("$parent/$path");
2107 warn "W: $t: $parent/$path ",
2108 "Insufficient permissions?\n";
2112 \@out;
2115 sub parse_svn_date {
2116 my $date = shift || return '+0000 1970-01-01 00:00:00';
2117 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2118 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2119 croak "Unable to parse date: $date\n";
2120 "+0000 $Y-$m-$d $H:$M:$S";
2123 sub check_author {
2124 my ($author) = @_;
2125 if (!defined $author || length $author == 0) {
2126 $author = '(no author)';
2128 if (defined $::_authors && ! defined $::users{$author}) {
2129 die "Author: $author not defined in $::_authors file\n";
2131 $author;
2134 sub make_log_entry {
2135 my ($self, $rev, $parents, $ed) = @_;
2136 my $untracked = $self->get_untracked($ed);
2138 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2139 print $un "r$rev\n" or croak $!;
2140 print $un $_, "\n" foreach @$untracked;
2141 my %log_entry = ( parents => $parents || [], revision => $rev,
2142 log => '');
2144 my $headrev;
2145 my $logged = delete $self->{logged_rev_props};
2146 if (!$logged || $self->{-want_revprops}) {
2147 my $rp = $self->ra->rev_proplist($rev);
2148 foreach (sort keys %$rp) {
2149 my $v = $rp->{$_};
2150 if (/^svn:(author|date|log)$/) {
2151 $log_entry{$1} = $v;
2152 } elsif ($_ eq 'svm:headrev') {
2153 $headrev = $v;
2154 } else {
2155 print $un " rev_prop: ", uri_encode($_), ' ',
2156 uri_encode($v), "\n";
2159 } else {
2160 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2162 close $un or croak $!;
2164 $log_entry{date} = parse_svn_date($log_entry{date});
2165 $log_entry{log} .= "\n";
2166 my $author = $log_entry{author} = check_author($log_entry{author});
2167 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2168 : ($author, undef);
2169 if (defined $headrev && $self->use_svm_props) {
2170 if ($self->rewrite_root) {
2171 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2172 "options set!\n";
2174 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2175 # we don't want "SVM: initializing mirror for junk" ...
2176 return undef if $r == 0;
2177 my $svm = $self->svm;
2178 if ($uuid ne $svm->{uuid}) {
2179 die "UUID mismatch on SVM path:\n",
2180 "expected: $svm->{uuid}\n",
2181 " got: $uuid\n";
2183 my $full_url = $self->full_url;
2184 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2185 die "Failed to replace '$svm->{replace}' with ",
2186 "'$svm->{source}' in $full_url\n";
2187 # throw away username for storing in records
2188 remove_username($full_url);
2189 $log_entry{metadata} = "$full_url\@$r $uuid";
2190 $log_entry{svm_revision} = $r;
2191 $email ||= "$author\@$uuid"
2192 } elsif ($self->use_svnsync_props) {
2193 my $full_url = $self->svnsync->{url};
2194 $full_url .= "/$self->{path}" if length $self->{path};
2195 remove_username($full_url);
2196 my $uuid = $self->svnsync->{uuid};
2197 $log_entry{metadata} = "$full_url\@$rev $uuid";
2198 $email ||= "$author\@$uuid"
2199 } else {
2200 my $url = $self->metadata_url;
2201 remove_username($url);
2202 $log_entry{metadata} = "$url\@$rev " .
2203 $self->ra->get_uuid;
2204 $email ||= "$author\@" . $self->ra->get_uuid;
2206 $log_entry{name} = $name;
2207 $log_entry{email} = $email;
2208 \%log_entry;
2211 sub fetch {
2212 my ($self, $min_rev, $max_rev, @parents) = @_;
2213 my ($last_rev, $last_commit) = $self->last_rev_commit;
2214 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2215 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2218 sub set_tree_cb {
2219 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2220 $self->{inject_parents} = { $rev => $tree };
2221 $self->fetch(undef, undef);
2224 sub set_tree {
2225 my ($self, $tree) = (shift, shift);
2226 my $log_entry = ::get_commit_entry($tree);
2227 unless ($self->{last_rev}) {
2228 fatal("Must have an existing revision to commit");
2230 my %ed_opts = ( r => $self->{last_rev},
2231 log => $log_entry->{log},
2232 ra => $self->ra,
2233 tree_a => $self->{last_commit},
2234 tree_b => $tree,
2235 editor_cb => sub {
2236 $self->set_tree_cb($log_entry, $tree, @_) },
2237 svn_path => $self->{path} );
2238 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2239 print "No changes\nr$self->{last_rev} = $tree\n";
2243 sub rebuild {
2244 my ($self) = @_;
2245 my $db_path = $self->db_path;
2246 return if (-e $db_path && ! -z $db_path);
2247 return unless ::verify_ref($self->refname.'^0');
2248 if (-f $self->{db_root}) {
2249 rename $self->{db_root}, $db_path or die
2250 "rename $self->{db_root} => $db_path failed: $!\n";
2251 my ($dir, $base) = ($db_path =~ m#^(.*?)/?([^/]+)$#);
2252 symlink $base, $self->{db_root} or die
2253 "symlink $base => $self->{db_root} failed: $!\n";
2254 return;
2256 print "Rebuilding $db_path ...\n";
2257 my ($log, $ctx) = command_output_pipe("log", '--no-color', $self->refname);
2258 my $latest;
2259 my $full_url = $self->full_url;
2260 remove_username($full_url);
2261 my $svn_uuid;
2262 my $c;
2263 while (<$log>) {
2264 if ( m{^commit ($::sha1)$} ) {
2265 $c = $1;
2266 next;
2268 next unless s{^\s*(git-svn-id:)}{$1};
2269 my ($url, $rev, $uuid) = ::extract_metadata($_);
2270 remove_username($url);
2272 # ignore merges (from set-tree)
2273 next if (!defined $rev || !$uuid);
2275 # if we merged or otherwise started elsewhere, this is
2276 # how we break out of it
2277 if ((defined $svn_uuid && ($uuid ne $svn_uuid)) ||
2278 ($full_url && $url && ($url ne $full_url))) {
2279 next;
2281 $latest ||= $rev;
2282 $svn_uuid ||= $uuid;
2284 $self->rev_db_set($rev, $c);
2285 print "r$rev = $c\n";
2287 command_close_pipe($log, $ctx);
2288 print "Done rebuilding $db_path\n";
2291 # rev_db:
2292 # Tie::File seems to be prone to offset errors if revisions get sparse,
2293 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2294 # one of my favorite modules is out :< Next up would be one of the DBM
2295 # modules, but I'm not sure which is most portable... So I'll just
2296 # go with something that's plain-text, but still capable of
2297 # being randomly accessed. So here's my ultra-simple fixed-width
2298 # database. All records are 40 characters + "\n", so it's easy to seek
2299 # to a revision: (41 * rev) is the byte offset.
2300 # A record of 40 0s denotes an empty revision.
2301 # And yes, it's still pretty fast (faster than Tie::File).
2302 # These files are disposable unless noMetadata or useSvmProps is set
2304 sub _rev_db_set {
2305 my ($fh, $rev, $commit) = @_;
2306 my $offset = $rev * 41;
2307 # assume that append is the common case:
2308 seek $fh, 0, 2 or croak $!;
2309 my $pos = tell $fh;
2310 if ($pos < $offset) {
2311 for (1 .. (($offset - $pos) / 41)) {
2312 print $fh (('0' x 40),"\n") or croak $!;
2315 seek $fh, $offset, 0 or croak $!;
2316 print $fh $commit,"\n" or croak $!;
2319 sub mkfile {
2320 my ($path) = @_;
2321 unless (-e $path) {
2322 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2323 mkpath([$dir]) unless -d $dir;
2324 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2325 close $fh or die "Couldn't close (create) $path: $!\n";
2329 sub rev_db_set {
2330 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2331 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2332 my $db = $self->db_path($uuid);
2333 my $db_lock = "$db.lock";
2334 my $sig;
2335 if ($update_ref) {
2336 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2337 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2339 mkfile($db);
2341 $LOCKFILES{$db_lock} = 1;
2342 my $sync;
2343 # both of these options make our .rev_db file very, very important
2344 # and we can't afford to lose it because rebuild() won't work
2345 if ($self->use_svm_props || $self->no_metadata) {
2346 $sync = 1;
2347 copy($db, $db_lock) or die "rev_db_set(@_): ",
2348 "Failed to copy: ",
2349 "$db => $db_lock ($!)\n";
2350 } else {
2351 rename $db, $db_lock or die "rev_db_set(@_): ",
2352 "Failed to rename: ",
2353 "$db => $db_lock ($!)\n";
2355 open my $fh, '+<', $db_lock or die "Couldn't open $db_lock: $!\n";
2356 _rev_db_set($fh, $rev, $commit);
2357 if ($sync) {
2358 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2359 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2361 close $fh or croak $!;
2362 if ($update_ref) {
2363 $_head = $self;
2364 command_noisy('update-ref', '-m', "r$rev",
2365 $self->refname, $commit);
2367 rename $db_lock, $db or die "rev_db_set(@_): ", "Failed to rename: ",
2368 "$db_lock => $db ($!)\n";
2369 delete $LOCKFILES{$db_lock};
2370 if ($update_ref) {
2371 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2372 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2373 kill $sig, $$ if defined $sig;
2377 sub rev_db_max {
2378 my ($self) = @_;
2379 $self->rebuild;
2380 my $db_path = $self->db_path;
2381 my @stat = stat $db_path or return 0;
2382 ($stat[7] % 41) == 0 or die "$db_path inconsistent size: $stat[7]\n";
2383 my $max = $stat[7] / 41;
2384 (($max > 0) ? $max - 1 : 0);
2387 sub rev_db_get {
2388 my ($self, $rev, $uuid) = @_;
2389 my $ret;
2390 my $offset = $rev * 41;
2391 my $db_path = $self->db_path($uuid);
2392 return undef unless -e $db_path;
2393 open my $fh, '<', $db_path or croak $!;
2394 if (sysseek($fh, $offset, 0) == $offset) {
2395 my $read = sysread($fh, $ret, 40);
2396 $ret = undef if ($read != 40 || $ret eq ('0'x40));
2398 close $fh or croak $!;
2399 $ret;
2402 # Finds the first svn revision that exists on (if $eq_ok is true) or
2403 # before $rev for the current branch. It will not search any lower
2404 # than $min_rev. Returns the git commit hash and svn revision number
2405 # if found, else (undef, undef).
2406 sub find_rev_before {
2407 my ($self, $rev, $eq_ok, $min_rev) = @_;
2408 --$rev unless $eq_ok;
2409 $min_rev ||= 1;
2410 while ($rev >= $min_rev) {
2411 if (my $c = $self->rev_db_get($rev)) {
2412 return ($rev, $c);
2414 --$rev;
2416 return (undef, undef);
2419 # Finds the first svn revision that exists on (if $eq_ok is true) or
2420 # after $rev for the current branch. It will not search any higher
2421 # than $max_rev. Returns the git commit hash and svn revision number
2422 # if found, else (undef, undef).
2423 sub find_rev_after {
2424 my ($self, $rev, $eq_ok, $max_rev) = @_;
2425 ++$rev unless $eq_ok;
2426 $max_rev ||= $self->rev_db_max();
2427 while ($rev <= $max_rev) {
2428 if (my $c = $self->rev_db_get($rev)) {
2429 return ($rev, $c);
2431 ++$rev;
2433 return (undef, undef);
2436 sub _new {
2437 my ($class, $repo_id, $ref_id, $path) = @_;
2438 unless (defined $repo_id && length $repo_id) {
2439 $repo_id = $Git::SVN::default_repo_id;
2441 unless (defined $ref_id && length $ref_id) {
2442 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2444 $_[1] = $repo_id = sanitize_remote_name($repo_id);
2445 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2446 $_[3] = $path = '' unless (defined $path);
2447 mkpath(["$ENV{GIT_DIR}/svn"]);
2448 bless {
2449 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2450 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2451 db_root => "$dir/.rev_db", repo_id => $repo_id }, $class;
2454 sub db_path {
2455 my ($self, $uuid) = @_;
2456 $uuid ||= $self->ra_uuid;
2457 "$self->{db_root}.$uuid";
2460 sub uri_encode {
2461 my ($f) = @_;
2462 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2466 sub remove_username {
2467 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2470 package Git::SVN::Prompt;
2471 use strict;
2472 use warnings;
2473 require SVN::Core;
2474 use vars qw/$_no_auth_cache $_username/;
2476 sub simple {
2477 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2478 $may_save = undef if $_no_auth_cache;
2479 $default_username = $_username if defined $_username;
2480 if (defined $default_username && length $default_username) {
2481 if (defined $realm && length $realm) {
2482 print STDERR "Authentication realm: $realm\n";
2483 STDERR->flush;
2485 $cred->username($default_username);
2486 } else {
2487 username($cred, $realm, $may_save, $pool);
2489 $cred->password(_read_password("Password for '" .
2490 $cred->username . "': ", $realm));
2491 $cred->may_save($may_save);
2492 $SVN::_Core::SVN_NO_ERROR;
2495 sub ssl_server_trust {
2496 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2497 $may_save = undef if $_no_auth_cache;
2498 print STDERR "Error validating server certificate for '$realm':\n";
2500 no warnings 'once';
2501 # All variables SVN::Auth::SSL::* are used only once,
2502 # so we're shutting up Perl warnings about this.
2503 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2504 print STDERR " - The certificate is not issued ",
2505 "by a trusted authority. Use the\n",
2506 " fingerprint to validate ",
2507 "the certificate manually!\n";
2509 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2510 print STDERR " - The certificate hostname ",
2511 "does not match.\n";
2513 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2514 print STDERR " - The certificate is not yet valid.\n";
2516 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2517 print STDERR " - The certificate has expired.\n";
2519 if ($failures & $SVN::Auth::SSL::OTHER) {
2520 print STDERR " - The certificate has ",
2521 "an unknown error.\n";
2523 } # no warnings 'once'
2524 printf STDERR
2525 "Certificate information:\n".
2526 " - Hostname: %s\n".
2527 " - Valid: from %s until %s\n".
2528 " - Issuer: %s\n".
2529 " - Fingerprint: %s\n",
2530 map $cert_info->$_, qw(hostname valid_from valid_until
2531 issuer_dname fingerprint);
2532 my $choice;
2533 prompt:
2534 print STDERR $may_save ?
2535 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
2536 "(R)eject or accept (t)emporarily? ";
2537 STDERR->flush;
2538 $choice = lc(substr(<STDIN> || 'R', 0, 1));
2539 if ($choice =~ /^t$/i) {
2540 $cred->may_save(undef);
2541 } elsif ($choice =~ /^r$/i) {
2542 return -1;
2543 } elsif ($may_save && $choice =~ /^p$/i) {
2544 $cred->may_save($may_save);
2545 } else {
2546 goto prompt;
2548 $cred->accepted_failures($failures);
2549 $SVN::_Core::SVN_NO_ERROR;
2552 sub ssl_client_cert {
2553 my ($cred, $realm, $may_save, $pool) = @_;
2554 $may_save = undef if $_no_auth_cache;
2555 print STDERR "Client certificate filename: ";
2556 STDERR->flush;
2557 chomp(my $filename = <STDIN>);
2558 $cred->cert_file($filename);
2559 $cred->may_save($may_save);
2560 $SVN::_Core::SVN_NO_ERROR;
2563 sub ssl_client_cert_pw {
2564 my ($cred, $realm, $may_save, $pool) = @_;
2565 $may_save = undef if $_no_auth_cache;
2566 $cred->password(_read_password("Password: ", $realm));
2567 $cred->may_save($may_save);
2568 $SVN::_Core::SVN_NO_ERROR;
2571 sub username {
2572 my ($cred, $realm, $may_save, $pool) = @_;
2573 $may_save = undef if $_no_auth_cache;
2574 if (defined $realm && length $realm) {
2575 print STDERR "Authentication realm: $realm\n";
2577 my $username;
2578 if (defined $_username) {
2579 $username = $_username;
2580 } else {
2581 print STDERR "Username: ";
2582 STDERR->flush;
2583 chomp($username = <STDIN>);
2585 $cred->username($username);
2586 $cred->may_save($may_save);
2587 $SVN::_Core::SVN_NO_ERROR;
2590 sub _read_password {
2591 my ($prompt, $realm) = @_;
2592 print STDERR $prompt;
2593 STDERR->flush;
2594 require Term::ReadKey;
2595 Term::ReadKey::ReadMode('noecho');
2596 my $password = '';
2597 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
2598 last if $key =~ /[\012\015]/; # \n\r
2599 $password .= $key;
2601 Term::ReadKey::ReadMode('restore');
2602 print STDERR "\n";
2603 STDERR->flush;
2604 $password;
2607 package SVN::Git::Fetcher;
2608 use vars qw/@ISA/;
2609 use strict;
2610 use warnings;
2611 use Carp qw/croak/;
2612 use IO::File qw//;
2613 use Digest::MD5;
2615 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
2616 sub new {
2617 my ($class, $git_svn) = @_;
2618 my $self = SVN::Delta::Editor->new;
2619 bless $self, $class;
2620 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
2621 $self->{empty} = {};
2622 $self->{dir_prop} = {};
2623 $self->{file_prop} = {};
2624 $self->{absent_dir} = {};
2625 $self->{absent_file} = {};
2626 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
2627 $self;
2630 sub set_path_strip {
2631 my ($self, $path) = @_;
2632 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
2635 sub open_root {
2636 { path => '' };
2639 sub open_directory {
2640 my ($self, $path, $pb, $rev) = @_;
2641 { path => $path };
2644 sub git_path {
2645 my ($self, $path) = @_;
2646 if ($self->{path_strip}) {
2647 $path =~ s!$self->{path_strip}!! or
2648 die "Failed to strip path '$path' ($self->{path_strip})\n";
2650 $path;
2653 sub delete_entry {
2654 my ($self, $path, $rev, $pb) = @_;
2656 my $gpath = $self->git_path($path);
2657 return undef if ($gpath eq '');
2659 # remove entire directories.
2660 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
2661 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
2662 -r --name-only -z/,
2663 $self->{c}, '--', $gpath);
2664 local $/ = "\0";
2665 while (<$ls>) {
2666 chomp;
2667 $self->{gii}->remove($_);
2668 print "\tD\t$_\n" unless $::_q;
2670 print "\tD\t$gpath/\n" unless $::_q;
2671 command_close_pipe($ls, $ctx);
2672 $self->{empty}->{$path} = 0
2673 } else {
2674 $self->{gii}->remove($gpath);
2675 print "\tD\t$gpath\n" unless $::_q;
2677 undef;
2680 sub open_file {
2681 my ($self, $path, $pb, $rev) = @_;
2682 my $gpath = $self->git_path($path);
2683 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
2684 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
2685 unless (defined $mode && defined $blob) {
2686 die "$path was not found in commit $self->{c} (r$rev)\n";
2688 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
2689 pool => SVN::Pool->new, action => 'M' };
2692 sub add_file {
2693 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
2694 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2695 delete $self->{empty}->{$dir};
2696 { path => $path, mode_a => 100644, mode_b => 100644,
2697 pool => SVN::Pool->new, action => 'A' };
2700 sub add_directory {
2701 my ($self, $path, $cp_path, $cp_rev) = @_;
2702 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
2703 delete $self->{empty}->{$dir};
2704 $self->{empty}->{$path} = 1;
2705 { path => $path };
2708 sub change_dir_prop {
2709 my ($self, $db, $prop, $value) = @_;
2710 $self->{dir_prop}->{$db->{path}} ||= {};
2711 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
2712 undef;
2715 sub absent_directory {
2716 my ($self, $path, $pb) = @_;
2717 $self->{absent_dir}->{$pb->{path}} ||= [];
2718 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
2719 undef;
2722 sub absent_file {
2723 my ($self, $path, $pb) = @_;
2724 $self->{absent_file}->{$pb->{path}} ||= [];
2725 push @{$self->{absent_file}->{$pb->{path}}}, $path;
2726 undef;
2729 sub change_file_prop {
2730 my ($self, $fb, $prop, $value) = @_;
2731 if ($prop eq 'svn:executable') {
2732 if ($fb->{mode_b} != 120000) {
2733 $fb->{mode_b} = defined $value ? 100755 : 100644;
2735 } elsif ($prop eq 'svn:special') {
2736 $fb->{mode_b} = defined $value ? 120000 : 100644;
2737 } else {
2738 $self->{file_prop}->{$fb->{path}} ||= {};
2739 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
2741 undef;
2744 sub apply_textdelta {
2745 my ($self, $fb, $exp) = @_;
2746 my $fh = IO::File->new_tmpfile;
2747 $fh->autoflush(1);
2748 # $fh gets auto-closed() by SVN::TxDelta::apply(),
2749 # (but $base does not,) so dup() it for reading in close_file
2750 open my $dup, '<&', $fh or croak $!;
2751 my $base = IO::File->new_tmpfile;
2752 $base->autoflush(1);
2753 if ($fb->{blob}) {
2754 defined (my $pid = fork) or croak $!;
2755 if (!$pid) {
2756 open STDOUT, '>&', $base or croak $!;
2757 print STDOUT 'link ' if ($fb->{mode_a} == 120000);
2758 exec qw/git-cat-file blob/, $fb->{blob} or croak $!;
2760 waitpid $pid, 0;
2761 croak $? if $?;
2763 if (defined $exp) {
2764 seek $base, 0, 0 or croak $!;
2765 my $md5 = Digest::MD5->new;
2766 $md5->addfile($base);
2767 my $got = $md5->hexdigest;
2768 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
2769 "expected: $exp\n",
2770 " got: $got\n" if ($got ne $exp);
2773 seek $base, 0, 0 or croak $!;
2774 $fb->{fh} = $dup;
2775 $fb->{base} = $base;
2776 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
2779 sub close_file {
2780 my ($self, $fb, $exp) = @_;
2781 my $hash;
2782 my $path = $self->git_path($fb->{path});
2783 if (my $fh = $fb->{fh}) {
2784 if (defined $exp) {
2785 seek($fh, 0, 0) or croak $!;
2786 my $md5 = Digest::MD5->new;
2787 $md5->addfile($fh);
2788 my $got = $md5->hexdigest;
2789 if ($got ne $exp) {
2790 die "Checksum mismatch: $path\n",
2791 "expected: $exp\n got: $got\n";
2794 sysseek($fh, 0, 0) or croak $!;
2795 if ($fb->{mode_b} == 120000) {
2796 sysread($fh, my $buf, 5) == 5 or croak $!;
2797 $buf eq 'link ' or die "$path has mode 120000",
2798 "but is not a link\n";
2800 defined(my $pid = open my $out,'-|') or die "Can't fork: $!\n";
2801 if (!$pid) {
2802 open STDIN, '<&', $fh or croak $!;
2803 exec qw/git-hash-object -w --stdin/ or croak $!;
2805 chomp($hash = do { local $/; <$out> });
2806 close $out or croak $!;
2807 close $fh or croak $!;
2808 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
2809 close $fb->{base} or croak $!;
2810 } else {
2811 $hash = $fb->{blob} or die "no blob information\n";
2813 $fb->{pool}->clear;
2814 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
2815 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
2816 undef;
2819 sub abort_edit {
2820 my $self = shift;
2821 $self->{nr} = $self->{gii}->{nr};
2822 delete $self->{gii};
2823 $self->SUPER::abort_edit(@_);
2826 sub close_edit {
2827 my $self = shift;
2828 $self->{git_commit_ok} = 1;
2829 $self->{nr} = $self->{gii}->{nr};
2830 delete $self->{gii};
2831 $self->SUPER::close_edit(@_);
2834 package SVN::Git::Editor;
2835 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
2836 use strict;
2837 use warnings;
2838 use Carp qw/croak/;
2839 use IO::File;
2840 use Digest::MD5;
2842 sub new {
2843 my ($class, $opts) = @_;
2844 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
2845 die "$_ required!\n" unless (defined $opts->{$_});
2848 my $pool = SVN::Pool->new;
2849 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
2850 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
2851 $opts->{r}, $mods);
2853 # $opts->{ra} functions should not be used after this:
2854 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
2855 $opts->{editor_cb}, $pool);
2856 my $self = SVN::Delta::Editor->new(@ce, $pool);
2857 bless $self, $class;
2858 foreach (qw/svn_path r tree_a tree_b/) {
2859 $self->{$_} = $opts->{$_};
2861 $self->{url} = $opts->{ra}->{url};
2862 $self->{mods} = $mods;
2863 $self->{types} = $types;
2864 $self->{pool} = $pool;
2865 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
2866 $self->{rm} = { };
2867 $self->{path_prefix} = length $self->{svn_path} ?
2868 "$self->{svn_path}/" : '';
2869 return $self;
2872 sub generate_diff {
2873 my ($tree_a, $tree_b) = @_;
2874 my @diff_tree = qw(diff-tree -z -r);
2875 if ($_cp_similarity) {
2876 push @diff_tree, "-C$_cp_similarity";
2877 } else {
2878 push @diff_tree, '-C';
2880 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
2881 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
2882 push @diff_tree, $tree_a, $tree_b;
2883 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
2884 local $/ = "\0";
2885 my $state = 'meta';
2886 my @mods;
2887 while (<$diff_fh>) {
2888 chomp $_; # this gets rid of the trailing "\0"
2889 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
2890 $::sha1\s($::sha1)\s
2891 ([MTCRAD])\d*$/xo) {
2892 push @mods, { mode_a => $1, mode_b => $2,
2893 sha1_b => $3, chg => $4 };
2894 if ($4 =~ /^(?:C|R)$/) {
2895 $state = 'file_a';
2896 } else {
2897 $state = 'file_b';
2899 } elsif ($state eq 'file_a') {
2900 my $x = $mods[$#mods] or croak "Empty array\n";
2901 if ($x->{chg} !~ /^(?:C|R)$/) {
2902 croak "Error parsing $_, $x->{chg}\n";
2904 $x->{file_a} = $_;
2905 $state = 'file_b';
2906 } elsif ($state eq 'file_b') {
2907 my $x = $mods[$#mods] or croak "Empty array\n";
2908 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
2909 croak "Error parsing $_, $x->{chg}\n";
2911 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
2912 croak "Error parsing $_, $x->{chg}\n";
2914 $x->{file_b} = $_;
2915 $state = 'meta';
2916 } else {
2917 croak "Error parsing $_\n";
2920 command_close_pipe($diff_fh, $ctx);
2921 \@mods;
2924 sub check_diff_paths {
2925 my ($ra, $pfx, $rev, $mods) = @_;
2926 my %types;
2927 $pfx .= '/' if length $pfx;
2929 sub type_diff_paths {
2930 my ($ra, $types, $path, $rev) = @_;
2931 my @p = split m#/+#, $path;
2932 my $c = shift @p;
2933 unless (defined $types->{$c}) {
2934 $types->{$c} = $ra->check_path($c, $rev);
2936 while (@p) {
2937 $c .= '/' . shift @p;
2938 next if defined $types->{$c};
2939 $types->{$c} = $ra->check_path($c, $rev);
2943 foreach my $m (@$mods) {
2944 foreach my $f (qw/file_a file_b/) {
2945 next unless defined $m->{$f};
2946 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
2947 if (length $pfx.$dir && ! defined $types{$dir}) {
2948 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
2952 \%types;
2955 sub split_path {
2956 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
2959 sub repo_path {
2960 my ($self, $path) = @_;
2961 $self->{path_prefix}.(defined $path ? $path : '');
2964 sub url_path {
2965 my ($self, $path) = @_;
2966 if ($self->{url} =~ m#^https?://#) {
2967 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
2969 $self->{url} . '/' . $self->repo_path($path);
2972 sub rmdirs {
2973 my ($self) = @_;
2974 my $rm = $self->{rm};
2975 delete $rm->{''}; # we never delete the url we're tracking
2976 return unless %$rm;
2978 foreach (keys %$rm) {
2979 my @d = split m#/#, $_;
2980 my $c = shift @d;
2981 $rm->{$c} = 1;
2982 while (@d) {
2983 $c .= '/' . shift @d;
2984 $rm->{$c} = 1;
2987 delete $rm->{$self->{svn_path}};
2988 delete $rm->{''}; # we never delete the url we're tracking
2989 return unless %$rm;
2991 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
2992 $self->{tree_b});
2993 local $/ = "\0";
2994 while (<$fh>) {
2995 chomp;
2996 my @dn = split m#/#, $_;
2997 while (pop @dn) {
2998 delete $rm->{join '/', @dn};
3000 unless (%$rm) {
3001 close $fh;
3002 return;
3005 command_close_pipe($fh, $ctx);
3007 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3008 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3009 $self->close_directory($bat->{$d}, $p);
3010 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3011 print "\tD+\t$d/\n" unless $::_q;
3012 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3013 delete $bat->{$d};
3017 sub open_or_add_dir {
3018 my ($self, $full_path, $baton) = @_;
3019 my $t = $self->{types}->{$full_path};
3020 if (!defined $t) {
3021 die "$full_path not known in r$self->{r} or we have a bug!\n";
3024 no warnings 'once';
3025 # SVN::Node::none and SVN::Node::file are used only once,
3026 # so we're shutting up Perl's warnings about them.
3027 if ($t == $SVN::Node::none) {
3028 return $self->add_directory($full_path, $baton,
3029 undef, -1, $self->{pool});
3030 } elsif ($t == $SVN::Node::dir) {
3031 return $self->open_directory($full_path, $baton,
3032 $self->{r}, $self->{pool});
3033 } # no warnings 'once'
3034 print STDERR "$full_path already exists in repository at ",
3035 "r$self->{r} and it is not a directory (",
3036 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3037 } # no warnings 'once'
3038 exit 1;
3041 sub ensure_path {
3042 my ($self, $path) = @_;
3043 my $bat = $self->{bat};
3044 my $repo_path = $self->repo_path($path);
3045 return $bat->{''} unless (length $repo_path);
3046 my @p = split m#/+#, $repo_path;
3047 my $c = shift @p;
3048 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3049 while (@p) {
3050 my $c0 = $c;
3051 $c .= '/' . shift @p;
3052 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3054 return $bat->{$c};
3057 sub A {
3058 my ($self, $m) = @_;
3059 my ($dir, $file) = split_path($m->{file_b});
3060 my $pbat = $self->ensure_path($dir);
3061 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3062 undef, -1);
3063 print "\tA\t$m->{file_b}\n" unless $::_q;
3064 $self->chg_file($fbat, $m);
3065 $self->close_file($fbat,undef,$self->{pool});
3068 sub C {
3069 my ($self, $m) = @_;
3070 my ($dir, $file) = split_path($m->{file_b});
3071 my $pbat = $self->ensure_path($dir);
3072 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3073 $self->url_path($m->{file_a}), $self->{r});
3074 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3075 $self->chg_file($fbat, $m);
3076 $self->close_file($fbat,undef,$self->{pool});
3079 sub delete_entry {
3080 my ($self, $path, $pbat) = @_;
3081 my $rpath = $self->repo_path($path);
3082 my ($dir, $file) = split_path($rpath);
3083 $self->{rm}->{$dir} = 1;
3084 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3087 sub R {
3088 my ($self, $m) = @_;
3089 my ($dir, $file) = split_path($m->{file_b});
3090 my $pbat = $self->ensure_path($dir);
3091 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3092 $self->url_path($m->{file_a}), $self->{r});
3093 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3094 $self->chg_file($fbat, $m);
3095 $self->close_file($fbat,undef,$self->{pool});
3097 ($dir, $file) = split_path($m->{file_a});
3098 $pbat = $self->ensure_path($dir);
3099 $self->delete_entry($m->{file_a}, $pbat);
3102 sub M {
3103 my ($self, $m) = @_;
3104 my ($dir, $file) = split_path($m->{file_b});
3105 my $pbat = $self->ensure_path($dir);
3106 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3107 $pbat,$self->{r},$self->{pool});
3108 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3109 $self->chg_file($fbat, $m);
3110 $self->close_file($fbat,undef,$self->{pool});
3113 sub T { shift->M(@_) }
3115 sub change_file_prop {
3116 my ($self, $fbat, $pname, $pval) = @_;
3117 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3120 sub chg_file {
3121 my ($self, $fbat, $m) = @_;
3122 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3123 $self->change_file_prop($fbat,'svn:executable','*');
3124 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3125 $self->change_file_prop($fbat,'svn:executable',undef);
3127 my $fh = IO::File->new_tmpfile or croak $!;
3128 if ($m->{mode_b} =~ /^120/) {
3129 print $fh 'link ' or croak $!;
3130 $self->change_file_prop($fbat,'svn:special','*');
3131 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3132 $self->change_file_prop($fbat,'svn:special',undef);
3134 defined(my $pid = fork) or croak $!;
3135 if (!$pid) {
3136 open STDOUT, '>&', $fh or croak $!;
3137 exec qw/git-cat-file blob/, $m->{sha1_b} or croak $!;
3139 waitpid $pid, 0;
3140 croak $? if $?;
3141 $fh->flush == 0 or croak $!;
3142 seek $fh, 0, 0 or croak $!;
3144 my $md5 = Digest::MD5->new;
3145 $md5->addfile($fh) or croak $!;
3146 seek $fh, 0, 0 or croak $!;
3148 my $exp = $md5->hexdigest;
3149 my $pool = SVN::Pool->new;
3150 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3151 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3152 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3153 $pool->clear;
3155 close $fh or croak $!;
3158 sub D {
3159 my ($self, $m) = @_;
3160 my ($dir, $file) = split_path($m->{file_b});
3161 my $pbat = $self->ensure_path($dir);
3162 print "\tD\t$m->{file_b}\n" unless $::_q;
3163 $self->delete_entry($m->{file_b}, $pbat);
3166 sub close_edit {
3167 my ($self) = @_;
3168 my ($p,$bat) = ($self->{pool}, $self->{bat});
3169 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3170 next if $_ eq '';
3171 $self->close_directory($bat->{$_}, $p);
3173 $self->close_directory($bat->{''}, $p);
3174 $self->SUPER::close_edit($p);
3175 $p->clear;
3178 sub abort_edit {
3179 my ($self) = @_;
3180 $self->SUPER::abort_edit($self->{pool});
3183 sub DESTROY {
3184 my $self = shift;
3185 $self->SUPER::DESTROY(@_);
3186 $self->{pool}->clear;
3189 # this drives the editor
3190 sub apply_diff {
3191 my ($self) = @_;
3192 my $mods = $self->{mods};
3193 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3194 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3195 my $f = $m->{chg};
3196 if (defined $o{$f}) {
3197 $self->$f($m);
3198 } else {
3199 fatal("Invalid change type: $f");
3202 $self->rmdirs if $_rmdir;
3203 if (@$mods == 0) {
3204 $self->abort_edit;
3205 } else {
3206 $self->close_edit;
3208 return scalar @$mods;
3211 package Git::SVN::Ra;
3212 use vars qw/@ISA $config_dir $_log_window_size/;
3213 use strict;
3214 use warnings;
3215 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3217 BEGIN {
3218 # enforce temporary pool usage for some simple functions
3219 no strict 'refs';
3220 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3221 my $SUPER = "SUPER::$f";
3222 *$f = sub {
3223 my $self = shift;
3224 my $pool = SVN::Pool->new;
3225 my @ret = $self->$SUPER(@_,$pool);
3226 $pool->clear;
3227 wantarray ? @ret : $ret[0];
3232 sub _auth_providers () {
3234 SVN::Client::get_simple_provider(),
3235 SVN::Client::get_ssl_server_trust_file_provider(),
3236 SVN::Client::get_simple_prompt_provider(
3237 \&Git::SVN::Prompt::simple, 2),
3238 SVN::Client::get_ssl_client_cert_file_provider(),
3239 SVN::Client::get_ssl_client_cert_prompt_provider(
3240 \&Git::SVN::Prompt::ssl_client_cert, 2),
3241 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3242 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3243 SVN::Client::get_username_provider(),
3244 SVN::Client::get_ssl_server_trust_prompt_provider(
3245 \&Git::SVN::Prompt::ssl_server_trust),
3246 SVN::Client::get_username_prompt_provider(
3247 \&Git::SVN::Prompt::username, 2)
3251 sub escape_uri_only {
3252 my ($uri) = @_;
3253 my @tmp;
3254 foreach (split m{/}, $uri) {
3255 s/([^\w.-])/sprintf("%%%02X",ord($1))/eg;
3256 push @tmp, $_;
3258 join('/', @tmp);
3261 sub escape_url {
3262 my ($url) = @_;
3263 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3264 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3265 $url = "$scheme://$domain$uri";
3267 $url;
3270 sub new {
3271 my ($class, $url) = @_;
3272 $url =~ s!/+$!!;
3273 return $RA if ($RA && $RA->{url} eq $url);
3275 SVN::_Core::svn_config_ensure($config_dir, undef);
3276 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3277 my $config = SVN::Core::config_get_config($config_dir);
3278 $RA = undef;
3279 my $dont_store_passwords = 1;
3280 my $conf_t = ${$config}{'config'};
3282 no warnings 'once';
3283 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3284 # produces warnings that variables are used only once.
3285 # I had not found the better way to shut them up, so
3286 # the warnings of type 'once' are disabled in this block.
3287 if (SVN::_Core::svn_config_get_bool($conf_t,
3288 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3289 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3290 1) == 0) {
3291 SVN::_Core::svn_auth_set_parameter($baton,
3292 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3293 bless (\$dont_store_passwords, "_p_void"));
3295 if (SVN::_Core::svn_config_get_bool($conf_t,
3296 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3297 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3298 1) == 0) {
3299 $Git::SVN::Prompt::_no_auth_cache = 1;
3301 } # no warnings 'once'
3302 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3303 config => $config,
3304 pool => SVN::Pool->new,
3305 auth_provider_callbacks => $callbacks);
3306 $self->{url} = $url;
3307 $self->{svn_path} = $url;
3308 $self->{repos_root} = $self->get_repos_root;
3309 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3310 $self->{cache} = { check_path => { r => 0, data => {} },
3311 get_dir => { r => 0, data => {} } };
3312 $RA = bless $self, $class;
3315 sub check_path {
3316 my ($self, $path, $r) = @_;
3317 my $cache = $self->{cache}->{check_path};
3318 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3319 return $cache->{data}->{$path};
3321 my $pool = SVN::Pool->new;
3322 my $t = $self->SUPER::check_path($path, $r, $pool);
3323 $pool->clear;
3324 if ($r != $cache->{r}) {
3325 %{$cache->{data}} = ();
3326 $cache->{r} = $r;
3328 $cache->{data}->{$path} = $t;
3331 sub get_dir {
3332 my ($self, $dir, $r) = @_;
3333 my $cache = $self->{cache}->{get_dir};
3334 if ($r == $cache->{r}) {
3335 if (my $x = $cache->{data}->{$dir}) {
3336 return wantarray ? @$x : $x->[0];
3339 my $pool = SVN::Pool->new;
3340 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3341 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3342 $pool->clear;
3343 if ($r != $cache->{r}) {
3344 %{$cache->{data}} = ();
3345 $cache->{r} = $r;
3347 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3348 wantarray ? (\%dirents, $r, $props) : \%dirents;
3351 sub DESTROY {
3352 # do not call the real DESTROY since we store ourselves in $RA
3355 sub get_log {
3356 my ($self, @args) = @_;
3357 my $pool = SVN::Pool->new;
3358 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3359 my $ret = $self->SUPER::get_log(@args, $pool);
3360 $pool->clear;
3361 $ret;
3364 sub trees_match {
3365 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3366 my $ctx = SVN::Client->new(auth => _auth_providers);
3367 my $out = IO::File->new_tmpfile;
3369 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3370 # $ctx->diff(), so we'll create a default one
3371 my $pool = SVN::Pool->new_default_sub;
3373 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3374 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3375 $out->flush;
3376 my $ret = (($out->stat)[7] == 0);
3377 close $out or croak $!;
3379 $ret;
3382 sub get_commit_editor {
3383 my ($self, $log, $cb, $pool) = @_;
3384 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3385 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3388 sub gs_do_update {
3389 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3390 my $new = ($rev_a == $rev_b);
3391 my $path = $gs->{path};
3393 if ($new && -e $gs->{index}) {
3394 unlink $gs->{index} or die
3395 "Couldn't unlink index: $gs->{index}: $!\n";
3397 my $pool = SVN::Pool->new;
3398 $editor->set_path_strip($path);
3399 my (@pc) = split m#/#, $path;
3400 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3401 1, $editor, $pool);
3402 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3404 # Since we can't rely on svn_ra_reparent being available, we'll
3405 # just have to do some magic with set_path to make it so
3406 # we only want a partial path.
3407 my $sp = '';
3408 my $final = join('/', @pc);
3409 while (@pc) {
3410 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3411 $sp .= '/' if length $sp;
3412 $sp .= shift @pc;
3414 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3416 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3418 $reporter->finish_report($pool);
3419 $pool->clear;
3420 $editor->{git_commit_ok};
3423 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3424 # svn_ra_reparent didn't work before 1.4)
3425 sub gs_do_switch {
3426 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3427 my $path = $gs->{path};
3428 my $pool = SVN::Pool->new;
3430 my $full_url = $self->{url};
3431 my $old_url = $full_url;
3432 $full_url .= '/' . escape_uri_only($path) if length $path;
3433 my ($ra, $reparented);
3434 if ($old_url ne $full_url) {
3435 if ($old_url !~ m#^svn(\+ssh)?://#) {
3436 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3437 $pool);
3438 $self->{url} = $full_url;
3439 $reparented = 1;
3440 } else {
3441 $_[0] = undef;
3442 $self = undef;
3443 $RA = undef;
3444 $ra = Git::SVN::Ra->new($full_url);
3445 $ra_invalid = 1;
3448 $ra ||= $self;
3449 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3450 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3451 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3452 $reporter->finish_report($pool);
3454 if ($reparented) {
3455 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3456 $self->{url} = $old_url;
3459 $pool->clear;
3460 $editor->{git_commit_ok};
3463 sub longest_common_path {
3464 my ($gsv, $globs) = @_;
3465 my %common;
3466 my $common_max = scalar @$gsv;
3468 foreach my $gs (@$gsv) {
3469 my @tmp = split m#/#, $gs->{path};
3470 my $p = '';
3471 foreach (@tmp) {
3472 $p .= length($p) ? "/$_" : $_;
3473 $common{$p} ||= 0;
3474 $common{$p}++;
3477 $globs ||= [];
3478 $common_max += scalar @$globs;
3479 foreach my $glob (@$globs) {
3480 my @tmp = split m#/#, $glob->{path}->{left};
3481 my $p = '';
3482 foreach (@tmp) {
3483 $p .= length($p) ? "/$_" : $_;
3484 $common{$p} ||= 0;
3485 $common{$p}++;
3489 my $longest_path = '';
3490 foreach (sort {length $b <=> length $a} keys %common) {
3491 if ($common{$_} == $common_max) {
3492 $longest_path = $_;
3493 last;
3496 $longest_path;
3499 sub gs_fetch_loop_common {
3500 my ($self, $base, $head, $gsv, $globs) = @_;
3501 return if ($base > $head);
3502 my $inc = $_log_window_size;
3503 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
3504 my $longest_path = longest_common_path($gsv, $globs);
3505 my $ra_url = $self->{url};
3506 while (1) {
3507 my %revs;
3508 my $err;
3509 my $err_handler = $SVN::Error::handler;
3510 $SVN::Error::handler = sub {
3511 ($err) = @_;
3512 skip_unknown_revs($err);
3514 sub _cb {
3515 my ($paths, $r, $author, $date, $log) = @_;
3516 [ dup_changed_paths($paths),
3517 { author => $author, date => $date, log => $log } ];
3519 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
3520 sub { $revs{$_[1]} = _cb(@_) });
3521 if ($err && $max >= $head) {
3522 print STDERR "Path '$longest_path' ",
3523 "was probably deleted:\n",
3524 $err->expanded_message,
3525 "\nWill attempt to follow ",
3526 "revisions r$min .. r$max ",
3527 "committed before the deletion\n";
3528 my $hi = $max;
3529 while (--$hi >= $min) {
3530 my $ok;
3531 $self->get_log([$longest_path], $min, $hi,
3532 0, 1, 1, sub {
3533 $ok ||= $_[1];
3534 $revs{$_[1]} = _cb(@_) });
3535 if ($ok) {
3536 print STDERR "r$min .. r$ok OK\n";
3537 last;
3541 $SVN::Error::handler = $err_handler;
3543 my %exists = map { $_->{path} => $_ } @$gsv;
3544 foreach my $r (sort {$a <=> $b} keys %revs) {
3545 my ($paths, $logged) = @{$revs{$r}};
3547 foreach my $gs ($self->match_globs(\%exists, $paths,
3548 $globs, $r)) {
3549 if ($gs->rev_db_max >= $r) {
3550 next;
3552 next unless $gs->match_paths($paths, $r);
3553 $gs->{logged_rev_props} = $logged;
3554 if (my $last_commit = $gs->last_commit) {
3555 $gs->assert_index_clean($last_commit);
3557 my $log_entry = $gs->do_fetch($paths, $r);
3558 if ($log_entry) {
3559 $gs->do_git_commit($log_entry);
3562 foreach my $g (@$globs) {
3563 my $k = "svn-remote.$g->{remote}." .
3564 "$g->{t}-maxRev";
3565 Git::SVN::tmp_config($k, $r);
3567 if ($ra_invalid) {
3568 $_[0] = undef;
3569 $self = undef;
3570 $RA = undef;
3571 $self = Git::SVN::Ra->new($ra_url);
3572 $ra_invalid = undef;
3575 # pre-fill the .rev_db since it'll eventually get filled in
3576 # with '0' x40 if something new gets committed
3577 foreach my $gs (@$gsv) {
3578 next if defined $gs->rev_db_get($max);
3579 $gs->rev_db_set($max, 0 x40);
3581 foreach my $g (@$globs) {
3582 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
3583 Git::SVN::tmp_config($k, $max);
3585 last if $max >= $head;
3586 $min = $max + 1;
3587 $max += $inc;
3588 $max = $head if ($max > $head);
3592 sub match_globs {
3593 my ($self, $exists, $paths, $globs, $r) = @_;
3595 sub get_dir_check {
3596 my ($self, $exists, $g, $r) = @_;
3597 my @x = eval { $self->get_dir($g->{path}->{left}, $r) };
3598 return unless scalar @x == 3;
3599 my $dirents = $x[0];
3600 foreach my $de (keys %$dirents) {
3601 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
3602 my $p = $g->{path}->full_path($de);
3603 next if $exists->{$p};
3604 next if (length $g->{path}->{right} &&
3605 ($self->check_path($p, $r) !=
3606 $SVN::Node::dir));
3607 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
3608 $g->{ref}->full_path($de), 1);
3611 foreach my $g (@$globs) {
3612 if (my $path = $paths->{"/$g->{path}->{left}"}) {
3613 if ($path->{action} =~ /^[AR]$/) {
3614 get_dir_check($self, $exists, $g, $r);
3617 foreach (keys %$paths) {
3618 if (/$g->{path}->{left_regex}/ &&
3619 !/$g->{path}->{regex}/) {
3620 next if $paths->{$_}->{action} !~ /^[AR]$/;
3621 get_dir_check($self, $exists, $g, $r);
3623 next unless /$g->{path}->{regex}/;
3624 my $p = $1;
3625 my $pathname = $g->{path}->full_path($p);
3626 next if $exists->{$pathname};
3627 next if ($self->check_path($pathname, $r) !=
3628 $SVN::Node::dir);
3629 $exists->{$pathname} = Git::SVN->init(
3630 $self->{url}, $pathname, undef,
3631 $g->{ref}->full_path($p), 1);
3633 my $c = '';
3634 foreach (split m#/#, $g->{path}->{left}) {
3635 $c .= "/$_";
3636 next unless ($paths->{$c} &&
3637 ($paths->{$c}->{action} =~ /^[AR]$/));
3638 get_dir_check($self, $exists, $g, $r);
3641 values %$exists;
3644 sub minimize_url {
3645 my ($self) = @_;
3646 return $self->{url} if ($self->{url} eq $self->{repos_root});
3647 my $url = $self->{repos_root};
3648 my @components = split(m!/!, $self->{svn_path});
3649 my $c = '';
3650 do {
3651 $url .= "/$c" if length $c;
3652 eval { (ref $self)->new($url)->get_latest_revnum };
3653 } while ($@ && ($c = shift @components));
3654 $url;
3657 sub can_do_switch {
3658 my $self = shift;
3659 unless (defined $can_do_switch) {
3660 my $pool = SVN::Pool->new;
3661 my $rep = eval {
3662 $self->do_switch(1, '', 0, $self->{url},
3663 SVN::Delta::Editor->new, $pool);
3665 if ($@) {
3666 $can_do_switch = 0;
3667 } else {
3668 $rep->abort_report($pool);
3669 $can_do_switch = 1;
3671 $pool->clear;
3673 $can_do_switch;
3676 sub skip_unknown_revs {
3677 my ($err) = @_;
3678 my $errno = $err->apr_err();
3679 # Maybe the branch we're tracking didn't
3680 # exist when the repo started, so it's
3681 # not an error if it doesn't, just continue
3683 # Wonderfully consistent library, eh?
3684 # 160013 - svn:// and file://
3685 # 175002 - http(s)://
3686 # 175007 - http(s):// (this repo required authorization, too...)
3687 # More codes may be discovered later...
3688 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
3689 my $err_key = $err->expanded_message;
3690 # revision numbers change every time, filter them out
3691 $err_key =~ s/\d+/\0/g;
3692 $err_key = "$errno\0$err_key";
3693 unless ($ignored_err{$err_key}) {
3694 warn "W: Ignoring error from SVN, path probably ",
3695 "does not exist: ($errno): ",
3696 $err->expanded_message,"\n";
3697 $ignored_err{$err_key} = 1;
3699 return;
3701 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
3704 # svn_log_changed_path_t objects passed to get_log are likely to be
3705 # overwritten even if only the refs are copied to an external variable,
3706 # so we should dup the structures in their entirety. Using an externally
3707 # passed pool (instead of our temporary and quickly cleared pool in
3708 # Git::SVN::Ra) does not help matters at all...
3709 sub dup_changed_paths {
3710 my ($paths) = @_;
3711 return undef unless $paths;
3712 my %ret;
3713 foreach my $p (keys %$paths) {
3714 my $i = $paths->{$p};
3715 my %s = map { $_ => $i->$_ }
3716 qw/copyfrom_path copyfrom_rev action/;
3717 $ret{$p} = \%s;
3719 \%ret;
3722 package Git::SVN::Log;
3723 use strict;
3724 use warnings;
3725 use POSIX qw/strftime/;
3726 use constant commit_log_separator => ('-' x 72) . "\n";
3727 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
3728 %rusers $show_commit $incremental/;
3729 my $l_fmt;
3731 sub cmt_showable {
3732 my ($c) = @_;
3733 return 1 if defined $c->{r};
3735 # big commit message got truncated by the 16k pretty buffer in rev-list
3736 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
3737 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
3738 @{$c->{l}} = ();
3739 my @log = command(qw/cat-file commit/, $c->{c});
3741 # shift off the headers
3742 shift @log while ($log[0] ne '');
3743 shift @log;
3745 # TODO: make $c->{l} not have a trailing newline in the future
3746 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
3748 (undef, $c->{r}, undef) = ::extract_metadata(
3749 (grep(/^git-svn-id: /, @log))[-1]);
3751 return defined $c->{r};
3754 sub log_use_color {
3755 return 1 if $color;
3756 my ($dc, $dcvar);
3757 $dcvar = 'color.diff';
3758 $dc = `git-config --get $dcvar`;
3759 if ($dc eq '') {
3760 # nothing at all; fallback to "diff.color"
3761 $dcvar = 'diff.color';
3762 $dc = `git-config --get $dcvar`;
3764 chomp($dc);
3765 if ($dc eq 'auto') {
3766 my $pc;
3767 $pc = `git-config --get color.pager`;
3768 if ($pc eq '') {
3769 # does not have it -- fallback to pager.color
3770 $pc = `git-config --bool --get pager.color`;
3772 else {
3773 $pc = `git-config --bool --get color.pager`;
3774 if ($?) {
3775 $pc = 'false';
3778 chomp($pc);
3779 if (-t *STDOUT || (defined $pager && $pc eq 'true')) {
3780 return ($ENV{TERM} && $ENV{TERM} ne 'dumb');
3782 return 0;
3784 return 0 if $dc eq 'never';
3785 return 1 if $dc eq 'always';
3786 chomp($dc = `git-config --bool --get $dcvar`);
3787 return ($dc eq 'true');
3790 sub git_svn_log_cmd {
3791 my ($r_min, $r_max, @args) = @_;
3792 my $head = 'HEAD';
3793 my (@files, @log_opts);
3794 foreach my $x (@args) {
3795 if ($x eq '--' || @files) {
3796 push @files, $x;
3797 } else {
3798 if (::verify_ref("$x^0")) {
3799 $head = $x;
3800 } else {
3801 push @log_opts, $x;
3806 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
3807 $gs ||= Git::SVN->_new;
3808 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
3809 $gs->refname);
3810 push @cmd, '-r' unless $non_recursive;
3811 push @cmd, qw/--raw --name-status/ if $verbose;
3812 push @cmd, '--color' if log_use_color();
3813 push @cmd, @log_opts;
3814 if (defined $r_max && $r_max == $r_min) {
3815 push @cmd, '--max-count=1';
3816 if (my $c = $gs->rev_db_get($r_max)) {
3817 push @cmd, $c;
3819 } elsif (defined $r_max) {
3820 if ($r_max < $r_min) {
3821 ($r_min, $r_max) = ($r_max, $r_min);
3823 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
3824 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
3825 # If there are no commits in the range, both $c_max and $c_min
3826 # will be undefined. If there is at least 1 commit in the
3827 # range, both will be defined.
3828 return () if !defined $c_min || !defined $c_max;
3829 if ($c_min eq $c_max) {
3830 push @cmd, '--max-count=1', $c_min;
3831 } else {
3832 push @cmd, '--boundary', "$c_min..$c_max";
3835 return (@cmd, @files);
3838 # adapted from pager.c
3839 sub config_pager {
3840 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
3841 if (!defined $pager) {
3842 $pager = 'less';
3843 } elsif (length $pager == 0 || $pager eq 'cat') {
3844 $pager = undef;
3848 sub run_pager {
3849 return unless -t *STDOUT && defined $pager;
3850 pipe my $rfd, my $wfd or return;
3851 defined(my $pid = fork) or ::fatal "Can't fork: $!";
3852 if (!$pid) {
3853 open STDOUT, '>&', $wfd or
3854 ::fatal "Can't redirect to stdout: $!";
3855 return;
3857 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
3858 $ENV{LESS} ||= 'FRSX';
3859 exec $pager or ::fatal "Can't run pager: $! ($pager)";
3862 sub tz_to_s_offset {
3863 my ($tz) = @_;
3864 $tz =~ s/(\d\d)$//;
3865 return ($1 * 60) + ($tz * 3600);
3868 sub get_author_info {
3869 my ($dest, $author, $t, $tz) = @_;
3870 $author =~ s/(?:^\s*|\s*$)//g;
3871 $dest->{a_raw} = $author;
3872 my $au;
3873 if ($::_authors) {
3874 $au = $rusers{$author} || undef;
3876 if (!$au) {
3877 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
3879 $dest->{t} = $t;
3880 $dest->{tz} = $tz;
3881 $dest->{a} = $au;
3882 # Date::Parse isn't in the standard Perl distro :(
3883 if ($tz =~ s/^\+//) {
3884 $t += tz_to_s_offset($tz);
3885 } elsif ($tz =~ s/^\-//) {
3886 $t -= tz_to_s_offset($tz);
3888 $dest->{t_utc} = $t;
3891 sub process_commit {
3892 my ($c, $r_min, $r_max, $defer) = @_;
3893 if (defined $r_min && defined $r_max) {
3894 if ($r_min == $c->{r} && $r_min == $r_max) {
3895 show_commit($c);
3896 return 0;
3898 return 1 if $r_min == $r_max;
3899 if ($r_min < $r_max) {
3900 # we need to reverse the print order
3901 return 0 if (defined $limit && --$limit < 0);
3902 push @$defer, $c;
3903 return 1;
3905 if ($r_min != $r_max) {
3906 return 1 if ($r_min < $c->{r});
3907 return 1 if ($r_max > $c->{r});
3910 return 0 if (defined $limit && --$limit < 0);
3911 show_commit($c);
3912 return 1;
3915 sub show_commit {
3916 my $c = shift;
3917 if ($oneline) {
3918 my $x = "\n";
3919 if (my $l = $c->{l}) {
3920 while ($l->[0] =~ /^\s*$/) { shift @$l }
3921 $x = $l->[0];
3923 $l_fmt ||= 'A' . length($c->{r});
3924 print 'r',pack($l_fmt, $c->{r}),' | ';
3925 print "$c->{c} | " if $show_commit;
3926 print $x;
3927 } else {
3928 show_commit_normal($c);
3932 sub show_commit_changed_paths {
3933 my ($c) = @_;
3934 return unless $c->{changed};
3935 print "Changed paths:\n", @{$c->{changed}};
3938 sub show_commit_normal {
3939 my ($c) = @_;
3940 print commit_log_separator, "r$c->{r} | ";
3941 print "$c->{c} | " if $show_commit;
3942 print "$c->{a} | ", strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)",
3943 localtime($c->{t_utc})), ' | ';
3944 my $nr_line = 0;
3946 if (my $l = $c->{l}) {
3947 while ($l->[$#$l] eq "\n" && $#$l > 0
3948 && $l->[($#$l - 1)] eq "\n") {
3949 pop @$l;
3951 $nr_line = scalar @$l;
3952 if (!$nr_line) {
3953 print "1 line\n\n\n";
3954 } else {
3955 if ($nr_line == 1) {
3956 $nr_line = '1 line';
3957 } else {
3958 $nr_line .= ' lines';
3960 print $nr_line, "\n";
3961 show_commit_changed_paths($c);
3962 print "\n";
3963 print $_ foreach @$l;
3965 } else {
3966 print "1 line\n";
3967 show_commit_changed_paths($c);
3968 print "\n";
3971 foreach my $x (qw/raw stat diff/) {
3972 if ($c->{$x}) {
3973 print "\n";
3974 print $_ foreach @{$c->{$x}}
3979 sub cmd_show_log {
3980 my (@args) = @_;
3981 my ($r_min, $r_max);
3982 my $r_last = -1; # prevent dupes
3983 if (defined $TZ) {
3984 $ENV{TZ} = $TZ;
3985 } else {
3986 delete $ENV{TZ};
3988 if (defined $::_revision) {
3989 if ($::_revision =~ /^(\d+):(\d+)$/) {
3990 ($r_min, $r_max) = ($1, $2);
3991 } elsif ($::_revision =~ /^\d+$/) {
3992 $r_min = $r_max = $::_revision;
3993 } else {
3994 ::fatal "-r$::_revision is not supported, use ",
3995 "standard 'git log' arguments instead";
3999 config_pager();
4000 @args = git_svn_log_cmd($r_min, $r_max, @args);
4001 if (!@args) {
4002 print commit_log_separator unless $incremental || $oneline;
4003 return;
4005 my $log = command_output_pipe(@args);
4006 run_pager();
4007 my (@k, $c, $d, $stat);
4008 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4009 while (<$log>) {
4010 if (/^${esc_color}commit -?($::sha1_short)/o) {
4011 my $cmt = $1;
4012 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4013 $r_last = $c->{r};
4014 process_commit($c, $r_min, $r_max, \@k) or
4015 goto out;
4017 $d = undef;
4018 $c = { c => $cmt };
4019 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4020 get_author_info($c, $1, $2, $3);
4021 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4022 # ignore
4023 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4024 push @{$c->{raw}}, $_;
4025 } elsif (/^${esc_color}[ACRMDT]\t/) {
4026 # we could add $SVN->{svn_path} here, but that requires
4027 # remote access at the moment (repo_path_split)...
4028 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4029 push @{$c->{changed}}, $_;
4030 } elsif (/^${esc_color}diff /o) {
4031 $d = 1;
4032 push @{$c->{diff}}, $_;
4033 } elsif ($d) {
4034 push @{$c->{diff}}, $_;
4035 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4036 $esc_color*[\+\-]*$esc_color$/x) {
4037 $stat = 1;
4038 push @{$c->{stat}}, $_;
4039 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4040 push @{$c->{stat}}, $_;
4041 $stat = undef;
4042 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4043 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4044 } elsif (s/^${esc_color} //o) {
4045 push @{$c->{l}}, $_;
4048 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4049 $r_last = $c->{r};
4050 process_commit($c, $r_min, $r_max, \@k);
4052 if (@k) {
4053 ($r_min, $r_max) = ($r_max, $r_min);
4054 process_commit($_, $r_min, $r_max) foreach reverse @k;
4056 out:
4057 close $log;
4058 print commit_log_separator unless $incremental || $oneline;
4061 package Git::SVN::Migration;
4062 # these version numbers do NOT correspond to actual version numbers
4063 # of git nor git-svn. They are just relative.
4065 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4067 # v1 layout: .git/$id/info/url, refs/remotes/$id
4069 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4071 # v3 layout: .git/svn/$id, refs/remotes/$id
4072 # - info/url may remain for backwards compatibility
4073 # - this is what we migrate up to this layout automatically,
4074 # - this will be used by git svn init on single branches
4075 # v3.1 layout (auto migrated):
4076 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4077 # for backwards compatibility
4079 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4080 # - this is only created for newly multi-init-ed
4081 # repositories. Similar in spirit to the
4082 # --use-separate-remotes option in git-clone (now default)
4083 # - we do not automatically migrate to this (following
4084 # the example set by core git)
4085 use strict;
4086 use warnings;
4087 use Carp qw/croak/;
4088 use File::Path qw/mkpath/;
4089 use File::Basename qw/dirname basename/;
4090 use vars qw/$_minimize/;
4092 sub migrate_from_v0 {
4093 my $git_dir = $ENV{GIT_DIR};
4094 return undef unless -d $git_dir;
4095 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4096 my $migrated = 0;
4097 while (<$fh>) {
4098 chomp;
4099 my ($id, $orig_ref) = ($_, $_);
4100 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4101 next unless -f "$git_dir/$id/info/url";
4102 my $new_ref = "refs/remotes/$id";
4103 if (::verify_ref("$new_ref^0")) {
4104 print STDERR "W: $orig_ref is probably an old ",
4105 "branch used by an ancient version of ",
4106 "git-svn.\n",
4107 "However, $new_ref also exists.\n",
4108 "We will not be able ",
4109 "to use this branch until this ",
4110 "ambiguity is resolved.\n";
4111 next;
4113 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4114 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4115 command_noisy('update-ref', $new_ref, $orig_ref);
4116 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4117 $migrated++;
4119 command_close_pipe($fh, $ctx);
4120 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4121 $migrated;
4124 sub migrate_from_v1 {
4125 my $git_dir = $ENV{GIT_DIR};
4126 my $migrated = 0;
4127 return $migrated unless -d $git_dir;
4128 my $svn_dir = "$git_dir/svn";
4130 # just in case somebody used 'svn' as their $id at some point...
4131 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4133 print STDERR "Migrating from a git-svn v1 layout...\n";
4134 mkpath([$svn_dir]);
4135 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4136 "$svn_dir\n\t(required for this version ",
4137 "($::VERSION) of git-svn) does not. exist\n";
4138 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4139 while (<$fh>) {
4140 my $x = $_;
4141 next unless $x =~ s#^refs/remotes/##;
4142 chomp $x;
4143 next unless -f "$git_dir/$x/info/url";
4144 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4145 next unless $u;
4146 my $dn = dirname("$git_dir/svn/$x");
4147 mkpath([$dn]) unless -d $dn;
4148 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4149 mkpath(["$git_dir/svn/svn"]);
4150 print STDERR " - $git_dir/$x/info => ",
4151 "$git_dir/svn/$x/info\n";
4152 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4153 croak "$!: $x";
4154 # don't worry too much about these, they probably
4155 # don't exist with repos this old (save for index,
4156 # and we can easily regenerate that)
4157 foreach my $f (qw/unhandled.log index .rev_db/) {
4158 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4160 } else {
4161 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4162 rename "$git_dir/$x", "$git_dir/svn/$x" or
4163 croak "$!: $x";
4165 $migrated++;
4167 command_close_pipe($fh, $ctx);
4168 print STDERR "Done migrating from a git-svn v1 layout\n";
4169 $migrated;
4172 sub read_old_urls {
4173 my ($l_map, $pfx, $path) = @_;
4174 my @dir;
4175 foreach (<$path/*>) {
4176 if (-r "$_/info/url") {
4177 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4178 my $ref_id = $pfx . basename $_;
4179 my $url = ::file_to_s("$_/info/url");
4180 $l_map->{$ref_id} = $url;
4181 } elsif (-d $_) {
4182 push @dir, $_;
4185 foreach (@dir) {
4186 my $x = $_;
4187 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4188 read_old_urls($l_map, $x, $_);
4192 sub migrate_from_v2 {
4193 my @cfg = command(qw/config -l/);
4194 return if grep /^svn-remote\..+\.url=/, @cfg;
4195 my %l_map;
4196 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4197 my $migrated = 0;
4199 foreach my $ref_id (sort keys %l_map) {
4200 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4201 if ($@) {
4202 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4204 $migrated++;
4206 $migrated;
4209 sub minimize_connections {
4210 my $r = Git::SVN::read_all_remotes();
4211 my $new_urls = {};
4212 my $root_repos = {};
4213 foreach my $repo_id (keys %$r) {
4214 my $url = $r->{$repo_id}->{url} or next;
4215 my $fetch = $r->{$repo_id}->{fetch} or next;
4216 my $ra = Git::SVN::Ra->new($url);
4218 # skip existing cases where we already connect to the root
4219 if (($ra->{url} eq $ra->{repos_root}) ||
4220 (Git::SVN::sanitize_remote_name($ra->{repos_root}) eq
4221 $repo_id)) {
4222 $root_repos->{$ra->{url}} = $repo_id;
4223 next;
4226 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4227 my $root_path = $ra->{url};
4228 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4229 foreach my $path (keys %$fetch) {
4230 my $ref_id = $fetch->{$path};
4231 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4233 # make sure we can read when connecting to
4234 # a higher level of a repository
4235 my ($last_rev, undef) = $gs->last_rev_commit;
4236 if (!defined $last_rev) {
4237 $last_rev = eval {
4238 $root_ra->get_latest_revnum;
4240 next if $@;
4242 my $new = $root_path;
4243 $new .= length $path ? "/$path" : '';
4244 eval {
4245 $root_ra->get_log([$new], $last_rev, $last_rev,
4246 0, 0, 1, sub { });
4248 next if $@;
4249 $new_urls->{$ra->{repos_root}}->{$new} =
4250 { ref_id => $ref_id,
4251 old_repo_id => $repo_id,
4252 old_path => $path };
4256 my @emptied;
4257 foreach my $url (keys %$new_urls) {
4258 # see if we can re-use an existing [svn-remote "repo_id"]
4259 # instead of creating a(n ugly) new section:
4260 my $repo_id = $root_repos->{$url} ||
4261 Git::SVN::sanitize_remote_name($url);
4263 my $fetch = $new_urls->{$url};
4264 foreach my $path (keys %$fetch) {
4265 my $x = $fetch->{$path};
4266 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4267 my $pfx = "svn-remote.$x->{old_repo_id}";
4269 my $old_fetch = quotemeta("$x->{old_path}:".
4270 "refs/remotes/$x->{ref_id}");
4271 command_noisy(qw/config --unset/,
4272 "$pfx.fetch", '^'. $old_fetch . '$');
4273 delete $r->{$x->{old_repo_id}}->
4274 {fetch}->{$x->{old_path}};
4275 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4276 command_noisy(qw/config --unset/,
4277 "$pfx.url");
4278 push @emptied, $x->{old_repo_id}
4282 if (@emptied) {
4283 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4284 "$ENV{GIT_DIR}/config";
4285 print STDERR <<EOF;
4286 The following [svn-remote] sections in your config file ($file) are empty
4287 and can be safely removed:
4289 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4293 sub migration_check {
4294 migrate_from_v0();
4295 migrate_from_v1();
4296 migrate_from_v2();
4297 minimize_connections() if $_minimize;
4300 package Git::IndexInfo;
4301 use strict;
4302 use warnings;
4303 use Git qw/command_input_pipe command_close_pipe/;
4305 sub new {
4306 my ($class) = @_;
4307 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4308 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4311 sub remove {
4312 my ($self, $path) = @_;
4313 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4314 return ++$self->{nr};
4316 undef;
4319 sub update {
4320 my ($self, $mode, $hash, $path) = @_;
4321 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4322 return ++$self->{nr};
4324 undef;
4327 sub DESTROY {
4328 my ($self) = @_;
4329 command_close_pipe($self->{gui}, $self->{ctx});
4332 package Git::SVN::GlobSpec;
4333 use strict;
4334 use warnings;
4336 sub new {
4337 my ($class, $glob) = @_;
4338 my $re = $glob;
4339 $re =~ s!/+$!!g; # no need for trailing slashes
4340 my $nr = ($re =~ s!^(.*)\*(.*)$!\(\[^/\]+\)!g);
4341 my ($left, $right) = ($1, $2);
4342 if ($nr > 1) {
4343 die "Only one '*' wildcard expansion ",
4344 "is supported (got $nr): '$glob'\n";
4345 } elsif ($nr == 0) {
4346 die "One '*' is needed for glob: '$glob'\n";
4348 $re = quotemeta($left) . $re . quotemeta($right);
4349 if (length $left && !($left =~ s!/+$!!g)) {
4350 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4352 if (length $right && !($right =~ s!^/+!!g)) {
4353 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4355 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4356 bless { left => $left, right => $right, left_regex => $left_re,
4357 regex => qr/$re/, glob => $glob }, $class;
4360 sub full_path {
4361 my ($self, $path) = @_;
4362 return (length $self->{left} ? "$self->{left}/" : '') .
4363 $path . (length $self->{right} ? "/$self->{right}" : '');
4366 __END__
4368 Data structures:
4371 $remotes = { # returned by read_all_remotes()
4372 'svn' => {
4373 # svn-remote.svn.url=https://svn.musicpd.org
4374 url => 'https://svn.musicpd.org',
4375 # svn-remote.svn.fetch=mpd/trunk:trunk
4376 fetch => {
4377 'mpd/trunk' => 'trunk',
4379 # svn-remote.svn.tags=mpd/tags/*:tags/*
4380 tags => {
4381 path => {
4382 left => 'mpd/tags',
4383 right => '',
4384 regex => qr!mpd/tags/([^/]+)$!,
4385 glob => 'tags/*',
4387 ref => {
4388 left => 'tags',
4389 right => '',
4390 regex => qr!tags/([^/]+)$!,
4391 glob => 'tags/*',
4397 $log_entry hashref as returned by libsvn_log_entry()
4399 log => 'whitespace-formatted log entry
4400 ', # trailing newline is preserved
4401 revision => '8', # integer
4402 date => '2004-02-24T17:01:44.108345Z', # commit date
4403 author => 'committer name'
4407 # this is generated by generate_diff();
4408 @mods = array of diff-index line hashes, each element represents one line
4409 of diff-index output
4411 diff-index line ($m hash)
4413 mode_a => first column of diff-index output, no leading ':',
4414 mode_b => second column of diff-index output,
4415 sha1_b => sha1sum of the final blob,
4416 chg => change type [MCRADT],
4417 file_a => original file name of a file (iff chg is 'C' or 'R')
4418 file_b => new/current file name of a file (any chg)
4422 # retval of read_url_paths{,_all}();
4423 $l_map = {
4424 # repository root url
4425 'https://svn.musicpd.org' => {
4426 # repository path # GIT_SVN_ID
4427 'mpd/trunk' => 'trunk',
4428 'mpd/tags/0.11.5' => 'tags/0.11.5',
4432 Notes:
4433 I don't trust the each() function on unless I created %hash myself
4434 because the internal iterator may not have started at base.