git-svn: Allow deep branch names by supporting multi-globs
[git/platforms.git] / git-svn.perl
blobee00e417d2091366e273878046b6fd3df318c29a
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 $_repository
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 Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
43 use IPC::Open3;
44 use Git;
46 BEGIN {
47 # import functions from Git into our packages, en masse
48 no strict 'refs';
49 foreach (qw/command command_oneline command_noisy command_output_pipe
50 command_input_pipe command_close_pipe/) {
51 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
52 Git::SVN::Migration Git::SVN::Log Git::SVN),
53 __PACKAGE__) {
54 *{"${package}::$_"} = \&{"Git::$_"};
59 my ($SVN);
61 $sha1 = qr/[a-f\d]{40}/;
62 $sha1_short = qr/[a-f\d]{4,40}/;
63 my ($_stdin, $_help, $_edit,
64 $_message, $_file,
65 $_template, $_shared,
66 $_version, $_fetch_all, $_no_rebase,
67 $_merge, $_strategy, $_dry_run, $_local,
68 $_prefix, $_no_checkout, $_url, $_verbose,
69 $_git_format, $_commit_url);
70 $Git::SVN::_follow_parent = 1;
71 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
72 'config-dir=s' => \$Git::SVN::Ra::config_dir,
73 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache );
74 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
75 'authors-file|A=s' => \$_authors,
76 'repack:i' => \$Git::SVN::_repack,
77 'noMetadata' => \$Git::SVN::_no_metadata,
78 'useSvmProps' => \$Git::SVN::_use_svm_props,
79 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
80 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
81 'no-checkout' => \$_no_checkout,
82 'quiet|q' => \$_q,
83 'repack-flags|repack-args|repack-opts=s' =>
84 \$Git::SVN::_repack_flags,
85 'use-log-author' => \$Git::SVN::_use_log_author,
86 'add-author-from' => \$Git::SVN::_add_author_from,
87 %remote_opts );
89 my ($_trunk, $_tags, $_branches, $_stdlayout);
90 my %icv;
91 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
92 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
93 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
94 'stdlayout|s' => \$_stdlayout,
95 'minimize-url|m' => \$Git::SVN::_minimize_url,
96 'no-metadata' => sub { $icv{noMetadata} = 1 },
97 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
98 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
99 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
100 %remote_opts );
101 my %cmt_opts = ( 'edit|e' => \$_edit,
102 'rmdir' => \$SVN::Git::Editor::_rmdir,
103 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
104 'l=i' => \$SVN::Git::Editor::_rename_limit,
105 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
108 my %cmd = (
109 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
110 { 'revision|r=s' => \$_revision,
111 'fetch-all|all' => \$_fetch_all,
112 %fc_opts } ],
113 clone => [ \&cmd_clone, "Initialize and fetch revisions",
114 { 'revision|r=s' => \$_revision,
115 %fc_opts, %init_opts } ],
116 init => [ \&cmd_init, "Initialize a repo for tracking" .
117 " (requires URL argument)",
118 \%init_opts ],
119 'multi-init' => [ \&cmd_multi_init,
120 "Deprecated alias for ".
121 "'$0 init -T<trunk> -b<branches> -t<tags>'",
122 \%init_opts ],
123 dcommit => [ \&cmd_dcommit,
124 'Commit several diffs to merge with upstream',
125 { 'merge|m|M' => \$_merge,
126 'strategy|s=s' => \$_strategy,
127 'verbose|v' => \$_verbose,
128 'dry-run|n' => \$_dry_run,
129 'fetch-all|all' => \$_fetch_all,
130 'commit-url=s' => \$_commit_url,
131 'revision|r=i' => \$_revision,
132 'no-rebase' => \$_no_rebase,
133 %cmt_opts, %fc_opts } ],
134 'set-tree' => [ \&cmd_set_tree,
135 "Set an SVN repository to a git tree-ish",
136 { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ],
137 'create-ignore' => [ \&cmd_create_ignore,
138 'Create a .gitignore per svn:ignore',
139 { 'revision|r=i' => \$_revision
140 } ],
141 'propget' => [ \&cmd_propget,
142 'Print the value of a property on a file or directory',
143 { 'revision|r=i' => \$_revision } ],
144 'proplist' => [ \&cmd_proplist,
145 'List all properties of a file or directory',
146 { 'revision|r=i' => \$_revision } ],
147 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
148 { 'revision|r=i' => \$_revision
149 } ],
150 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
151 { 'revision|r=i' => \$_revision
152 } ],
153 'multi-fetch' => [ \&cmd_multi_fetch,
154 "Deprecated alias for $0 fetch --all",
155 { 'revision|r=s' => \$_revision, %fc_opts } ],
156 'migrate' => [ sub { },
157 # no-op, we automatically run this anyways,
158 'Migrate configuration/metadata/layout from
159 previous versions of git-svn',
160 { 'minimize' => \$Git::SVN::Migration::_minimize,
161 %remote_opts } ],
162 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
163 { 'limit=i' => \$Git::SVN::Log::limit,
164 'revision|r=s' => \$_revision,
165 'verbose|v' => \$Git::SVN::Log::verbose,
166 'incremental' => \$Git::SVN::Log::incremental,
167 'oneline' => \$Git::SVN::Log::oneline,
168 'show-commit' => \$Git::SVN::Log::show_commit,
169 'non-recursive' => \$Git::SVN::Log::non_recursive,
170 'authors-file|A=s' => \$_authors,
171 'color' => \$Git::SVN::Log::color,
172 'pager=s' => \$Git::SVN::Log::pager
173 } ],
174 'find-rev' => [ \&cmd_find_rev, "Translate between SVN revision numbers and tree-ish",
175 {} ],
176 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
177 { 'merge|m|M' => \$_merge,
178 'verbose|v' => \$_verbose,
179 'strategy|s=s' => \$_strategy,
180 'local|l' => \$_local,
181 'fetch-all|all' => \$_fetch_all,
182 'dry-run|n' => \$_dry_run,
183 %fc_opts } ],
184 'commit-diff' => [ \&cmd_commit_diff,
185 'Commit a diff between two trees',
186 { 'message|m=s' => \$_message,
187 'file|F=s' => \$_file,
188 'revision|r=s' => \$_revision,
189 %cmt_opts } ],
190 'info' => [ \&cmd_info,
191 "Show info about the latest SVN revision
192 on the current branch",
193 { 'url' => \$_url, } ],
194 'blame' => [ \&Git::SVN::Log::cmd_blame,
195 "Show what revision and author last modified each line of a file",
196 { 'git-format' => \$_git_format } ],
199 my $cmd;
200 for (my $i = 0; $i < @ARGV; $i++) {
201 if (defined $cmd{$ARGV[$i]}) {
202 $cmd = $ARGV[$i];
203 splice @ARGV, $i, 1;
204 last;
208 # make sure we're always running at the top-level working directory
209 unless ($cmd && $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;
228 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
231 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
233 read_repo_config(\%opts);
234 Getopt::Long::Configure('pass_through') if ($cmd && ($cmd eq 'log' || $cmd eq 'blame'));
235 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
236 'minimize-connections' => \$Git::SVN::Migration::_minimize,
237 'id|i=s' => \$Git::SVN::default_ref_id,
238 'svn-remote|remote|R=s' => sub {
239 $Git::SVN::no_reuse_existing = 1;
240 $Git::SVN::default_repo_id = $_[1] });
241 exit 1 if (!$rv && $cmd && $cmd ne 'log');
243 usage(0) if $_help;
244 version() if $_version;
245 usage(1) unless defined $cmd;
246 load_authors() if $_authors;
248 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
249 Git::SVN::Migration::migration_check();
251 Git::SVN::init_vars();
252 eval {
253 Git::SVN::verify_remotes_sanity();
254 $cmd{$cmd}->[0]->(@ARGV);
256 fatal $@ if $@;
257 post_fetch_checkout();
258 exit 0;
260 ####################### primary functions ######################
261 sub usage {
262 my $exit = shift || 0;
263 my $fd = $exit ? \*STDERR : \*STDOUT;
264 print $fd <<"";
265 git-svn - bidirectional operations between a single Subversion tree and git
266 Usage: git svn <command> [options] [arguments]\n
268 print $fd "Available commands:\n" unless $cmd;
270 foreach (sort keys %cmd) {
271 next if $cmd && $cmd ne $_;
272 next if /^multi-/; # don't show deprecated commands
273 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
274 foreach (sort keys %{$cmd{$_}->[2]}) {
275 # mixed-case options are for .git/config only
276 next if /[A-Z]/ && /^[a-z]+$/i;
277 # prints out arguments as they should be passed:
278 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
279 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
280 "--$_" : "-$_" }
281 split /\|/,$_)," $x\n";
284 print $fd <<"";
285 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
286 arbitrary identifier if you're tracking multiple SVN branches/repositories in
287 one git repository and want to keep them separate. See git-svn(1) for more
288 information.
290 exit $exit;
293 sub version {
294 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
295 exit 0;
298 sub do_git_init_db {
299 unless (-d $ENV{GIT_DIR}) {
300 my @init_db = ('init');
301 push @init_db, "--template=$_template" if defined $_template;
302 if (defined $_shared) {
303 if ($_shared =~ /[a-z]/) {
304 push @init_db, "--shared=$_shared";
305 } else {
306 push @init_db, "--shared";
309 command_noisy(@init_db);
310 $_repository = Git->repository(Repository => ".git");
312 my $set;
313 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
314 foreach my $i (keys %icv) {
315 die "'$set' and '$i' cannot both be set\n" if $set;
316 next unless defined $icv{$i};
317 command_noisy('config', "$pfx.$i", $icv{$i});
318 $set = $i;
322 sub init_subdir {
323 my $repo_path = shift or return;
324 mkpath([$repo_path]) unless -d $repo_path;
325 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
326 $ENV{GIT_DIR} = '.git';
327 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
330 sub cmd_clone {
331 my ($url, $path) = @_;
332 if (!defined $path &&
333 (defined $_trunk || defined $_branches || defined $_tags ||
334 defined $_stdlayout) &&
335 $url !~ m#^[a-z\+]+://#) {
336 $path = $url;
338 $path = basename($url) if !defined $path || !length $path;
339 cmd_init($url, $path);
340 Git::SVN::fetch_all($Git::SVN::default_repo_id);
343 sub cmd_init {
344 if (defined $_stdlayout) {
345 $_trunk = 'trunk' if (!defined $_trunk);
346 $_tags = 'tags' if (!defined $_tags);
347 $_branches = 'branches' if (!defined $_branches);
349 if (defined $_trunk || defined $_branches || defined $_tags) {
350 return cmd_multi_init(@_);
352 my $url = shift or die "SVN repository location required ",
353 "as a command-line argument\n";
354 init_subdir(@_);
355 do_git_init_db();
357 Git::SVN->init($url);
360 sub cmd_fetch {
361 if (grep /^\d+=./, @_) {
362 die "'<rev>=<commit>' fetch arguments are ",
363 "no longer supported.\n";
365 my ($remote) = @_;
366 if (@_ > 1) {
367 die "Usage: $0 fetch [--all] [svn-remote]\n";
369 $remote ||= $Git::SVN::default_repo_id;
370 if ($_fetch_all) {
371 cmd_multi_fetch();
372 } else {
373 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
377 sub cmd_set_tree {
378 my (@commits) = @_;
379 if ($_stdin || !@commits) {
380 print "Reading from stdin...\n";
381 @commits = ();
382 while (<STDIN>) {
383 if (/\b($sha1_short)\b/o) {
384 unshift @commits, $1;
388 my @revs;
389 foreach my $c (@commits) {
390 my @tmp = command('rev-parse',$c);
391 if (scalar @tmp == 1) {
392 push @revs, $tmp[0];
393 } elsif (scalar @tmp > 1) {
394 push @revs, reverse(command('rev-list',@tmp));
395 } else {
396 fatal "Failed to rev-parse $c";
399 my $gs = Git::SVN->new;
400 my ($r_last, $cmt_last) = $gs->last_rev_commit;
401 $gs->fetch;
402 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
403 fatal "There are new revisions that were fetched ",
404 "and need to be merged (or acknowledged) ",
405 "before committing.\nlast rev: $r_last\n",
406 " current: $gs->{last_rev}";
408 $gs->set_tree($_) foreach @revs;
409 print "Done committing ",scalar @revs," revisions to SVN\n";
410 unlink $gs->{index};
413 sub cmd_dcommit {
414 my $head = shift;
415 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
416 'Cannot dcommit with a dirty index. Commit your changes first, '
417 . "or stash them with `git stash'.\n";
418 $head ||= 'HEAD';
419 my @refs;
420 my ($url, $rev, $uuid, $gs) = working_head_info($head, \@refs);
421 $url = $_commit_url if defined $_commit_url;
422 my $last_rev = $_revision if defined $_revision;
423 if ($url) {
424 print "Committing to $url ...\n";
426 unless ($gs) {
427 die "Unable to determine upstream SVN information from ",
428 "$head history.\nPerhaps the repository is empty.";
430 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
431 if ($_no_rebase && scalar(@$linear_refs) > 1) {
432 warn "Attempting to commit more than one change while ",
433 "--no-rebase is enabled.\n",
434 "If these changes depend on each other, re-running ",
435 "without --no-rebase may be required."
437 while (1) {
438 my $d = shift @$linear_refs or last;
439 unless (defined $last_rev) {
440 (undef, $last_rev, undef) = cmt_metadata("$d~1");
441 unless (defined $last_rev) {
442 fatal "Unable to extract revision information ",
443 "from commit $d~1";
446 if ($_dry_run) {
447 print "diff-tree $d~1 $d\n";
448 } else {
449 my $cmt_rev;
450 my %ed_opts = ( r => $last_rev,
451 log => get_commit_entry($d)->{log},
452 ra => Git::SVN::Ra->new($url),
453 config => SVN::Core::config_get_config(
454 $Git::SVN::Ra::config_dir
456 tree_a => "$d~1",
457 tree_b => $d,
458 editor_cb => sub {
459 print "Committed r$_[0]\n";
460 $cmt_rev = $_[0];
462 svn_path => '');
463 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
464 print "No changes\n$d~1 == $d\n";
465 } elsif ($parents->{$d} && @{$parents->{$d}}) {
466 $gs->{inject_parents_dcommit}->{$cmt_rev} =
467 $parents->{$d};
469 $_fetch_all ? $gs->fetch_all : $gs->fetch;
470 $last_rev = $cmt_rev;
471 next if $_no_rebase;
473 # we always want to rebase against the current HEAD,
474 # not any head that was passed to us
475 my @diff = command('diff-tree', $d,
476 $gs->refname, '--');
477 my @finish;
478 if (@diff) {
479 @finish = rebase_cmd();
480 print STDERR "W: $d and ", $gs->refname,
481 " differ, using @finish:\n",
482 join("\n", @diff), "\n";
483 } else {
484 print "No changes between current HEAD and ",
485 $gs->refname,
486 "\nResetting to the latest ",
487 $gs->refname, "\n";
488 @finish = qw/reset --mixed/;
490 command_noisy(@finish, $gs->refname);
491 if (@diff) {
492 @refs = ();
493 my ($url_, $rev_, $uuid_, $gs_) =
494 working_head_info($head, \@refs);
495 my ($linear_refs_, $parents_) =
496 linearize_history($gs_, \@refs);
497 if (scalar(@$linear_refs) !=
498 scalar(@$linear_refs_)) {
499 fatal "# of revisions changed ",
500 "\nbefore:\n",
501 join("\n", @$linear_refs),
502 "\n\nafter:\n",
503 join("\n", @$linear_refs_), "\n",
504 'If you are attempting to commit ',
505 "merges, try running:\n\t",
506 'git rebase --interactive',
507 '--preserve-merges ',
508 $gs->refname,
509 "\nBefore dcommitting";
511 if ($url_ ne $url) {
512 fatal "URL mismatch after rebase: ",
513 "$url_ != $url";
515 if ($uuid_ ne $uuid) {
516 fatal "uuid mismatch after rebase: ",
517 "$uuid_ != $uuid";
519 # remap parents
520 my (%p, @l, $i);
521 for ($i = 0; $i < scalar @$linear_refs; $i++) {
522 my $new = $linear_refs_->[$i] or next;
523 $p{$new} =
524 $parents->{$linear_refs->[$i]};
525 push @l, $new;
527 $parents = \%p;
528 $linear_refs = \@l;
532 unlink $gs->{index};
535 sub cmd_find_rev {
536 my $revision_or_hash = shift or die "SVN or git revision required ",
537 "as a command-line argument\n";
538 my $result;
539 if ($revision_or_hash =~ /^r\d+$/) {
540 my $head = shift;
541 $head ||= 'HEAD';
542 my @refs;
543 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
544 unless ($gs) {
545 die "Unable to determine upstream SVN information from ",
546 "$head history\n";
548 my $desired_revision = substr($revision_or_hash, 1);
549 $result = $gs->rev_map_get($desired_revision, $uuid);
550 } else {
551 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
552 $result = $rev;
554 print "$result\n" if $result;
557 sub cmd_rebase {
558 command_noisy(qw/update-index --refresh/);
559 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
560 unless ($gs) {
561 die "Unable to determine upstream SVN information from ",
562 "working tree history\n";
564 if ($_dry_run) {
565 print "Remote Branch: " . $gs->refname . "\n";
566 print "SVN URL: " . $url . "\n";
567 return;
569 if (command(qw/diff-index HEAD --/)) {
570 print STDERR "Cannot rebase with uncommited changes:\n";
571 command_noisy('status');
572 exit 1;
574 unless ($_local) {
575 # rebase will checkout for us, so no need to do it explicitly
576 $_no_checkout = 'true';
577 $_fetch_all ? $gs->fetch_all : $gs->fetch;
579 command_noisy(rebase_cmd(), $gs->refname);
582 sub cmd_show_ignore {
583 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
584 $gs ||= Git::SVN->new;
585 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
586 $gs->prop_walk($gs->{path}, $r, sub {
587 my ($gs, $path, $props) = @_;
588 print STDOUT "\n# $path\n";
589 my $s = $props->{'svn:ignore'} or return;
590 $s =~ s/[\r\n]+/\n/g;
591 chomp $s;
592 $s =~ s#^#$path#gm;
593 print STDOUT "$s\n";
597 sub cmd_show_externals {
598 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
599 $gs ||= Git::SVN->new;
600 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
601 $gs->prop_walk($gs->{path}, $r, sub {
602 my ($gs, $path, $props) = @_;
603 print STDOUT "\n# $path\n";
604 my $s = $props->{'svn:externals'} or return;
605 $s =~ s/[\r\n]+/\n/g;
606 chomp $s;
607 $s =~ s#^#$path#gm;
608 print STDOUT "$s\n";
612 sub cmd_create_ignore {
613 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
614 $gs ||= Git::SVN->new;
615 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
616 $gs->prop_walk($gs->{path}, $r, sub {
617 my ($gs, $path, $props) = @_;
618 # $path is of the form /path/to/dir/
619 my $ignore = '.' . $path . '.gitignore';
620 my $s = $props->{'svn:ignore'} or return;
621 open(GITIGNORE, '>', $ignore)
622 or fatal("Failed to open `$ignore' for writing: $!");
623 $s =~ s/[\r\n]+/\n/g;
624 chomp $s;
625 # Prefix all patterns so that the ignore doesn't apply
626 # to sub-directories.
627 $s =~ s#^#/#gm;
628 print GITIGNORE "$s\n";
629 close(GITIGNORE)
630 or fatal("Failed to close `$ignore': $!");
631 command_noisy('add', '-f', $ignore);
635 sub canonicalize_path {
636 my ($path) = @_;
637 my $dot_slash_added = 0;
638 if (substr($path, 0, 1) ne "/") {
639 $path = "./" . $path;
640 $dot_slash_added = 1;
642 # File::Spec->canonpath doesn't collapse x/../y into y (for a
643 # good reason), so let's do this manually.
644 $path =~ s#/+#/#g;
645 $path =~ s#/\.(?:/|$)#/#g;
646 $path =~ s#/[^/]+/\.\.##g;
647 $path =~ s#/$##g;
648 $path =~ s#^\./## if $dot_slash_added;
649 $path =~ s#^/##;
650 $path =~ s#^\.$##;
651 return $path;
654 # get_svnprops(PATH)
655 # ------------------
656 # Helper for cmd_propget and cmd_proplist below.
657 sub get_svnprops {
658 my $path = shift;
659 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
660 $gs ||= Git::SVN->new;
662 # prefix THE PATH by the sub-directory from which the user
663 # invoked us.
664 $path = $cmd_dir_prefix . $path;
665 fatal("No such file or directory: $path") unless -e $path;
666 my $is_dir = -d $path ? 1 : 0;
667 $path = $gs->{path} . '/' . $path;
669 # canonicalize the path (otherwise libsvn will abort or fail to
670 # find the file)
671 $path = canonicalize_path($path);
673 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
674 my $props;
675 if ($is_dir) {
676 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
678 else {
679 (undef, $props) = $gs->ra->get_file($path, $r, undef);
681 return $props;
684 # cmd_propget (PROP, PATH)
685 # ------------------------
686 # Print the SVN property PROP for PATH.
687 sub cmd_propget {
688 my ($prop, $path) = @_;
689 $path = '.' if not defined $path;
690 usage(1) if not defined $prop;
691 my $props = get_svnprops($path);
692 if (not defined $props->{$prop}) {
693 fatal("`$path' does not have a `$prop' SVN property.");
695 print $props->{$prop} . "\n";
698 # cmd_proplist (PATH)
699 # -------------------
700 # Print the list of SVN properties for PATH.
701 sub cmd_proplist {
702 my $path = shift;
703 $path = '.' if not defined $path;
704 my $props = get_svnprops($path);
705 print "Properties on '$path':\n";
706 foreach (sort keys %{$props}) {
707 print " $_\n";
711 sub cmd_multi_init {
712 my $url = shift;
713 unless (defined $_trunk || defined $_branches || defined $_tags) {
714 usage(1);
717 # there are currently some bugs that prevent multi-init/multi-fetch
718 # setups from working well without this.
719 $Git::SVN::_minimize_url = 1;
721 $_prefix = '' unless defined $_prefix;
722 if (defined $url) {
723 $url =~ s#/+$##;
724 init_subdir(@_);
726 do_git_init_db();
727 if (defined $_trunk) {
728 my $trunk_ref = $_prefix . 'trunk';
729 # try both old-style and new-style lookups:
730 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
731 unless ($gs_trunk) {
732 my ($trunk_url, $trunk_path) =
733 complete_svn_url($url, $_trunk);
734 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
735 undef, $trunk_ref);
738 return unless defined $_branches || defined $_tags;
739 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
740 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
741 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
744 sub cmd_multi_fetch {
745 my $remotes = Git::SVN::read_all_remotes();
746 foreach my $repo_id (sort keys %$remotes) {
747 if ($remotes->{$repo_id}->{url}) {
748 Git::SVN::fetch_all($repo_id, $remotes);
753 # this command is special because it requires no metadata
754 sub cmd_commit_diff {
755 my ($ta, $tb, $url) = @_;
756 my $usage = "Usage: $0 commit-diff -r<revision> ".
757 "<tree-ish> <tree-ish> [<URL>]";
758 fatal($usage) if (!defined $ta || !defined $tb);
759 my $svn_path = '';
760 if (!defined $url) {
761 my $gs = eval { Git::SVN->new };
762 if (!$gs) {
763 fatal("Needed URL or usable git-svn --id in ",
764 "the command-line\n", $usage);
766 $url = $gs->{url};
767 $svn_path = $gs->{path};
769 unless (defined $_revision) {
770 fatal("-r|--revision is a required argument\n", $usage);
772 if (defined $_message && defined $_file) {
773 fatal("Both --message/-m and --file/-F specified ",
774 "for the commit message.\n",
775 "I have no idea what you mean");
777 if (defined $_file) {
778 $_message = file_to_s($_file);
779 } else {
780 $_message ||= get_commit_entry($tb)->{log};
782 my $ra ||= Git::SVN::Ra->new($url);
783 my $r = $_revision;
784 if ($r eq 'HEAD') {
785 $r = $ra->get_latest_revnum;
786 } elsif ($r !~ /^\d+$/) {
787 die "revision argument: $r not understood by git-svn\n";
789 my %ed_opts = ( r => $r,
790 log => $_message,
791 ra => $ra,
792 tree_a => $ta,
793 tree_b => $tb,
794 editor_cb => sub { print "Committed r$_[0]\n" },
795 svn_path => $svn_path );
796 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
797 print "No changes\n$ta == $tb\n";
801 sub cmd_info {
802 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
803 if (exists $_[1]) {
804 die "Too many arguments specified\n";
807 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
809 if (!$file_type && !$diff_status) {
810 print STDERR "$path: (Not a versioned resource)\n\n";
811 return;
814 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
815 unless ($gs) {
816 die "Unable to determine upstream SVN information from ",
817 "working tree history\n";
820 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
821 $path = "." if $path eq "";
823 my $full_url = $url . ($path eq "." ? "" : "/$path");
825 if ($_url) {
826 print $full_url, "\n";
827 return;
830 my $result = "Path: $path\n";
831 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
832 $result .= "URL: " . $full_url . "\n";
834 eval {
835 my $repos_root = $gs->repos_root;
836 Git::SVN::remove_username($repos_root);
837 $result .= "Repository Root: $repos_root\n";
839 if ($@) {
840 $result .= "Repository Root: (offline)\n";
842 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A";
843 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
845 $result .= "Node Kind: " .
846 ($file_type eq "dir" ? "directory" : "file") . "\n";
848 my $schedule = $diff_status eq "A"
849 ? "add"
850 : ($diff_status eq "D" ? "delete" : "normal");
851 $result .= "Schedule: $schedule\n";
853 if ($diff_status eq "A") {
854 print $result, "\n";
855 return;
858 my ($lc_author, $lc_rev, $lc_date_utc);
859 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $path);
860 my $log = command_output_pipe(@args);
861 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
862 while (<$log>) {
863 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
864 $lc_author = $1;
865 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
866 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
867 (undef, $lc_rev, undef) = ::extract_metadata($1);
870 close $log;
872 Git::SVN::Log::set_local_timezone();
874 $result .= "Last Changed Author: $lc_author\n";
875 $result .= "Last Changed Rev: $lc_rev\n";
876 $result .= "Last Changed Date: " .
877 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
879 if ($file_type ne "dir") {
880 my $text_last_updated_date =
881 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
882 $result .=
883 "Text Last Updated: " .
884 Git::SVN::Log::format_svn_date($text_last_updated_date) .
885 "\n";
886 my $checksum;
887 if ($diff_status eq "D") {
888 my ($fh, $ctx) =
889 command_output_pipe(qw(cat-file blob), "HEAD:$path");
890 if ($file_type eq "link") {
891 my $file_name = <$fh>;
892 $checksum = md5sum("link $file_name");
893 } else {
894 $checksum = md5sum($fh);
896 command_close_pipe($fh, $ctx);
897 } elsif ($file_type eq "link") {
898 my $file_name =
899 command(qw(cat-file blob), "HEAD:$path");
900 $checksum =
901 md5sum("link " . $file_name);
902 } else {
903 open FILE, "<", $path or die $!;
904 $checksum = md5sum(\*FILE);
905 close FILE or die $!;
907 $result .= "Checksum: " . $checksum . "\n";
910 print $result, "\n";
913 ########################### utility functions #########################
915 sub rebase_cmd {
916 my @cmd = qw/rebase/;
917 push @cmd, '-v' if $_verbose;
918 push @cmd, qw/--merge/ if $_merge;
919 push @cmd, "--strategy=$_strategy" if $_strategy;
920 @cmd;
923 sub post_fetch_checkout {
924 return if $_no_checkout;
925 my $gs = $Git::SVN::_head or return;
926 return if verify_ref('refs/heads/master^0');
928 my $valid_head = verify_ref('HEAD^0');
929 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
930 return if ($valid_head || !verify_ref('HEAD^0'));
932 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
933 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
934 return if -f $index;
936 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
937 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
938 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
939 print STDERR "Checked out HEAD:\n ",
940 $gs->full_url, " r", $gs->last_rev, "\n";
943 sub complete_svn_url {
944 my ($url, $path) = @_;
945 $path =~ s#/+$##;
946 if ($path !~ m#^[a-z\+]+://#) {
947 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
948 fatal("E: '$path' is not a complete URL ",
949 "and a separate URL is not specified");
951 return ($url, $path);
953 return ($path, '');
956 sub complete_url_ls_init {
957 my ($ra, $repo_path, $switch, $pfx) = @_;
958 unless ($repo_path) {
959 print STDERR "W: $switch not specified\n";
960 return;
962 $repo_path =~ s#/+$##;
963 if ($repo_path =~ m#^[a-z\+]+://#) {
964 $ra = Git::SVN::Ra->new($repo_path);
965 $repo_path = '';
966 } else {
967 $repo_path =~ s#^/+##;
968 unless ($ra) {
969 fatal("E: '$repo_path' is not a complete URL ",
970 "and a separate URL is not specified");
973 my $url = $ra->{url};
974 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
975 my $k = "svn-remote.$gs->{repo_id}.url";
976 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
977 if ($orig_url && ($orig_url ne $gs->{url})) {
978 die "$k already set: $orig_url\n",
979 "wanted to set to: $gs->{url}\n";
981 command_oneline('config', $k, $gs->{url}) unless $orig_url;
982 my $remote_path = "$ra->{svn_path}/$repo_path";
983 $remote_path =~ s#/+#/#g;
984 $remote_path =~ s#^/##g;
985 $remote_path .= "/*" if $remote_path !~ /\*/;
986 my ($n) = ($switch =~ /^--(\w+)/);
987 if (length $pfx && $pfx !~ m#/$#) {
988 die "--prefix='$pfx' must have a trailing slash '/'\n";
990 command_noisy('config',
991 "svn-remote.$gs->{repo_id}.$n",
992 "$remote_path:refs/remotes/$pfx*" .
993 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
996 sub verify_ref {
997 my ($ref) = @_;
998 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
999 { STDERR => 0 }); };
1002 sub get_tree_from_treeish {
1003 my ($treeish) = @_;
1004 # $treeish can be a symbolic ref, too:
1005 my $type = command_oneline(qw/cat-file -t/, $treeish);
1006 my $expected;
1007 while ($type eq 'tag') {
1008 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1010 if ($type eq 'commit') {
1011 $expected = (grep /^tree /, command(qw/cat-file commit/,
1012 $treeish))[0];
1013 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1014 die "Unable to get tree from $treeish\n" unless $expected;
1015 } elsif ($type eq 'tree') {
1016 $expected = $treeish;
1017 } else {
1018 die "$treeish is a $type, expected tree, tag or commit\n";
1020 return $expected;
1023 sub get_commit_entry {
1024 my ($treeish) = shift;
1025 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1026 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1027 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1028 open my $log_fh, '>', $commit_editmsg or croak $!;
1030 my $type = command_oneline(qw/cat-file -t/, $treeish);
1031 if ($type eq 'commit' || $type eq 'tag') {
1032 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1033 $type, $treeish);
1034 my $in_msg = 0;
1035 my $author;
1036 my $saw_from = 0;
1037 my $msgbuf = "";
1038 while (<$msg_fh>) {
1039 if (!$in_msg) {
1040 $in_msg = 1 if (/^\s*$/);
1041 $author = $1 if (/^author (.*>)/);
1042 } elsif (/^git-svn-id: /) {
1043 # skip this for now, we regenerate the
1044 # correct one on re-fetch anyways
1045 # TODO: set *:merge properties or like...
1046 } else {
1047 if (/^From:/ || /^Signed-off-by:/) {
1048 $saw_from = 1;
1050 $msgbuf .= $_;
1053 $msgbuf =~ s/\s+$//s;
1054 if ($Git::SVN::_add_author_from && defined($author)
1055 && !$saw_from) {
1056 $msgbuf .= "\n\nFrom: $author";
1058 print $log_fh $msgbuf or croak $!;
1059 command_close_pipe($msg_fh, $ctx);
1061 close $log_fh or croak $!;
1063 if ($_edit || ($type eq 'tree')) {
1064 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1065 # TODO: strip out spaces, comments, like git-commit.sh
1066 system($editor, $commit_editmsg);
1068 rename $commit_editmsg, $commit_msg or croak $!;
1069 open $log_fh, '<', $commit_msg or croak $!;
1070 { local $/; chomp($log_entry{log} = <$log_fh>); }
1071 close $log_fh or croak $!;
1072 unlink $commit_msg;
1073 \%log_entry;
1076 sub s_to_file {
1077 my ($str, $file, $mode) = @_;
1078 open my $fd,'>',$file or croak $!;
1079 print $fd $str,"\n" or croak $!;
1080 close $fd or croak $!;
1081 chmod ($mode &~ umask, $file) if (defined $mode);
1084 sub file_to_s {
1085 my $file = shift;
1086 open my $fd,'<',$file or croak "$!: file: $file\n";
1087 local $/;
1088 my $ret = <$fd>;
1089 close $fd or croak $!;
1090 $ret =~ s/\s*$//s;
1091 return $ret;
1094 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1095 sub load_authors {
1096 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1097 my $log = $cmd eq 'log';
1098 while (<$authors>) {
1099 chomp;
1100 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1101 my ($user, $name, $email) = ($1, $2, $3);
1102 if ($log) {
1103 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1104 } else {
1105 $users{$user} = [$name, $email];
1108 close $authors or croak $!;
1111 # convert GetOpt::Long specs for use by git-config
1112 sub read_repo_config {
1113 return unless -d $ENV{GIT_DIR};
1114 my $opts = shift;
1115 my @config_only;
1116 foreach my $o (keys %$opts) {
1117 # if we have mixedCase and a long option-only, then
1118 # it's a config-only variable that we don't need for
1119 # the command-line.
1120 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1121 my $v = $opts->{$o};
1122 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1123 $key =~ s/-//g;
1124 my $arg = 'git-config';
1125 $arg .= ' --int' if ($o =~ /[:=]i$/);
1126 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1127 if (ref $v eq 'ARRAY') {
1128 chomp(my @tmp = `$arg --get-all svn.$key`);
1129 @$v = @tmp if @tmp;
1130 } else {
1131 chomp(my $tmp = `$arg --get svn.$key`);
1132 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1133 $$v = $tmp;
1137 delete @$opts{@config_only} if @config_only;
1140 sub extract_metadata {
1141 my $id = shift or return (undef, undef, undef);
1142 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1143 \s([a-f\d\-]+)$/x);
1144 if (!defined $rev || !$uuid || !$url) {
1145 # some of the original repositories I made had
1146 # identifiers like this:
1147 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1149 return ($url, $rev, $uuid);
1152 sub cmt_metadata {
1153 return extract_metadata((grep(/^git-svn-id: /,
1154 command(qw/cat-file commit/, shift)))[-1]);
1157 sub working_head_info {
1158 my ($head, $refs) = @_;
1159 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1160 my ($fh, $ctx) = command_output_pipe(@args, $head);
1161 my $hash;
1162 my %max;
1163 while (<$fh>) {
1164 if ( m{^commit ($::sha1)$} ) {
1165 unshift @$refs, $hash if $hash and $refs;
1166 $hash = $1;
1167 next;
1169 next unless s{^\s*(git-svn-id:)}{$1};
1170 my ($url, $rev, $uuid) = extract_metadata($_);
1171 if (defined $url && defined $rev) {
1172 next if $max{$url} and $max{$url} < $rev;
1173 if (my $gs = Git::SVN->find_by_url($url)) {
1174 my $c = $gs->rev_map_get($rev, $uuid);
1175 if ($c && $c eq $hash) {
1176 close $fh; # break the pipe
1177 return ($url, $rev, $uuid, $gs);
1178 } else {
1179 $max{$url} ||= $gs->rev_map_max;
1184 command_close_pipe($fh, $ctx);
1185 (undef, undef, undef, undef);
1188 sub read_commit_parents {
1189 my ($parents, $c) = @_;
1190 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1191 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1192 @{$parents->{$c}} = split(/ /, $p);
1195 sub linearize_history {
1196 my ($gs, $refs) = @_;
1197 my %parents;
1198 foreach my $c (@$refs) {
1199 read_commit_parents(\%parents, $c);
1202 my @linear_refs;
1203 my %skip = ();
1204 my $last_svn_commit = $gs->last_commit;
1205 foreach my $c (reverse @$refs) {
1206 next if $c eq $last_svn_commit;
1207 last if $skip{$c};
1209 unshift @linear_refs, $c;
1210 $skip{$c} = 1;
1212 # we only want the first parent to diff against for linear
1213 # history, we save the rest to inject when we finalize the
1214 # svn commit
1215 my $fp_a = verify_ref("$c~1");
1216 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1217 if (!$fp_a || !$fp_b) {
1218 die "Commit $c\n",
1219 "has no parent commit, and therefore ",
1220 "nothing to diff against.\n",
1221 "You should be working from a repository ",
1222 "originally created by git-svn\n";
1224 if ($fp_a ne $fp_b) {
1225 die "$c~1 = $fp_a, however parsing commit $c ",
1226 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1229 foreach my $p (@{$parents{$c}}) {
1230 $skip{$p} = 1;
1233 (\@linear_refs, \%parents);
1236 sub find_file_type_and_diff_status {
1237 my ($path) = @_;
1238 return ('dir', '') if $path eq '';
1240 my $diff_output =
1241 command_oneline(qw(diff --cached --name-status --), $path) || "";
1242 my $diff_status = (split(' ', $diff_output))[0] || "";
1244 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1246 return (undef, undef) if !$diff_status && !$ls_tree;
1248 if ($diff_status eq "A") {
1249 return ("link", $diff_status) if -l $path;
1250 return ("dir", $diff_status) if -d $path;
1251 return ("file", $diff_status);
1254 my $mode = (split(' ', $ls_tree))[0] || "";
1256 return ("link", $diff_status) if $mode eq "120000";
1257 return ("dir", $diff_status) if $mode eq "040000";
1258 return ("file", $diff_status);
1261 sub md5sum {
1262 my $arg = shift;
1263 my $ref = ref $arg;
1264 my $md5 = Digest::MD5->new();
1265 if ($ref eq 'GLOB' || $ref eq 'IO::File') {
1266 $md5->addfile($arg) or croak $!;
1267 } elsif ($ref eq 'SCALAR') {
1268 $md5->add($$arg) or croak $!;
1269 } elsif (!$ref) {
1270 $md5->add($arg) or croak $!;
1271 } else {
1272 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1274 return $md5->hexdigest();
1277 package Git::SVN;
1278 use strict;
1279 use warnings;
1280 use Fcntl qw/:DEFAULT :seek/;
1281 use constant rev_map_fmt => 'NH40';
1282 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1283 $_repack $_repack_flags $_use_svm_props $_head
1284 $_use_svnsync_props $no_reuse_existing $_minimize_url
1285 $_use_log_author $_add_author_from/;
1286 use Carp qw/croak/;
1287 use File::Path qw/mkpath/;
1288 use File::Copy qw/copy/;
1289 use IPC::Open3;
1291 my ($_gc_nr, $_gc_period);
1293 # properties that we do not log:
1294 my %SKIP_PROP;
1295 BEGIN {
1296 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1297 svn:special svn:executable
1298 svn:entry:committed-rev
1299 svn:entry:last-author
1300 svn:entry:uuid
1301 svn:entry:committed-date/;
1303 # some options are read globally, but can be overridden locally
1304 # per [svn-remote "..."] section. Command-line options will *NOT*
1305 # override options set in an [svn-remote "..."] section
1306 no strict 'refs';
1307 for my $option (qw/follow_parent no_metadata use_svm_props
1308 use_svnsync_props/) {
1309 my $key = $option;
1310 $key =~ tr/_//d;
1311 my $prop = "-$option";
1312 *$option = sub {
1313 my ($self) = @_;
1314 return $self->{$prop} if exists $self->{$prop};
1315 my $k = "svn-remote.$self->{repo_id}.$key";
1316 eval { command_oneline(qw/config --get/, $k) };
1317 if ($@) {
1318 $self->{$prop} = ${"Git::SVN::_$option"};
1319 } else {
1320 my $v = command_oneline(qw/config --bool/,$k);
1321 $self->{$prop} = $v eq 'false' ? 0 : 1;
1323 return $self->{$prop};
1328 my (%LOCKFILES, %INDEX_FILES);
1329 END {
1330 unlink keys %LOCKFILES if %LOCKFILES;
1331 unlink keys %INDEX_FILES if %INDEX_FILES;
1334 sub resolve_local_globs {
1335 my ($url, $fetch, $glob_spec) = @_;
1336 return unless defined $glob_spec;
1337 my $ref = $glob_spec->{ref};
1338 my $path = $glob_spec->{path};
1339 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1340 next unless m#^refs/remotes/$ref->{regex}$#;
1341 my $p = $1;
1342 my $pathname = desanitize_refname($path->full_path($p));
1343 my $refname = desanitize_refname($ref->full_path($p));
1344 if (my $existing = $fetch->{$pathname}) {
1345 if ($existing ne $refname) {
1346 die "Refspec conflict:\n",
1347 "existing: refs/remotes/$existing\n",
1348 " globbed: refs/remotes/$refname\n";
1350 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1351 $u =~ s!^\Q$url\E(/|$)!! or die
1352 "refs/remotes/$refname: '$url' not found in '$u'\n";
1353 if ($pathname ne $u) {
1354 warn "W: Refspec glob conflict ",
1355 "(ref: refs/remotes/$refname):\n",
1356 "expected path: $pathname\n",
1357 " real path: $u\n",
1358 "Continuing ahead with $u\n";
1359 next;
1361 } else {
1362 $fetch->{$pathname} = $refname;
1367 sub parse_revision_argument {
1368 my ($base, $head) = @_;
1369 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1370 return ($base, $head);
1372 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1373 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1374 return ($head, $head) if ($::_revision eq 'HEAD');
1375 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1376 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1377 die "revision argument: $::_revision not understood by git-svn\n";
1380 sub fetch_all {
1381 my ($repo_id, $remotes) = @_;
1382 if (ref $repo_id) {
1383 my $gs = $repo_id;
1384 $repo_id = undef;
1385 $repo_id = $gs->{repo_id};
1387 $remotes ||= read_all_remotes();
1388 my $remote = $remotes->{$repo_id} or
1389 die "[svn-remote \"$repo_id\"] unknown\n";
1390 my $fetch = $remote->{fetch};
1391 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1392 my (@gs, @globs);
1393 my $ra = Git::SVN::Ra->new($url);
1394 my $uuid = $ra->get_uuid;
1395 my $head = $ra->get_latest_revnum;
1396 my $base = defined $fetch ? $head : 0;
1398 # read the max revs for wildcard expansion (branches/*, tags/*)
1399 foreach my $t (qw/branches tags/) {
1400 defined $remote->{$t} or next;
1401 push @globs, $remote->{$t};
1402 my $max_rev = eval { tmp_config(qw/--int --get/,
1403 "svn-remote.$repo_id.${t}-maxRev") };
1404 if (defined $max_rev && ($max_rev < $base)) {
1405 $base = $max_rev;
1406 } elsif (!defined $max_rev) {
1407 $base = 0;
1411 if ($fetch) {
1412 foreach my $p (sort keys %$fetch) {
1413 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1414 my $lr = $gs->rev_map_max;
1415 if (defined $lr) {
1416 $base = $lr if ($lr < $base);
1418 push @gs, $gs;
1422 ($base, $head) = parse_revision_argument($base, $head);
1423 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1426 sub read_all_remotes {
1427 my $r = {};
1428 my $use_svm_props = eval { command_oneline(qw/config --bool
1429 svn.useSvmProps/) };
1430 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1431 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1432 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1433 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1434 die("svn-remote.$remote: remote ref '$_remote_ref' "
1435 . "must start with 'refs/remotes/'\n")
1436 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1437 my $remote_ref = $1;
1438 $local_ref =~ s{^/}{};
1439 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1440 $r->{$remote}->{svm} = {} if $use_svm_props;
1441 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1442 $r->{$1}->{svm} = {};
1443 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1444 $r->{$1}->{url} = $2;
1445 } elsif (m!^(.+)\.(branches|tags)=
1446 (.*):refs/remotes/(.+)\s*$/!x) {
1447 my ($p, $g) = ($3, $4);
1448 my $rs = $r->{$1}->{$2} = {
1449 t => $2,
1450 remote => $1,
1451 path => Git::SVN::GlobSpec->new($p),
1452 ref => Git::SVN::GlobSpec->new($g) };
1453 if (length($rs->{ref}->{right}) != 0) {
1454 die "The '*' glob character must be the last ",
1455 "character of '$g'\n";
1460 map {
1461 if (defined $r->{$_}->{svm}) {
1462 my $svm;
1463 eval {
1464 my $section = "svn-remote.$_";
1465 $svm = {
1466 source => tmp_config('--get',
1467 "$section.svm-source"),
1468 replace => tmp_config('--get',
1469 "$section.svm-replace"),
1472 $r->{$_}->{svm} = $svm;
1474 } keys %$r;
1479 sub init_vars {
1480 $_gc_nr = $_gc_period = 1000;
1481 if (defined $_repack || defined $_repack_flags) {
1482 warn "Repack options are obsolete; they have no effect.\n";
1486 sub verify_remotes_sanity {
1487 return unless -d $ENV{GIT_DIR};
1488 my %seen;
1489 foreach (command(qw/config -l/)) {
1490 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1491 if ($seen{$1}) {
1492 die "Remote ref refs/remote/$1 is tracked by",
1493 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1494 "Please resolve this ambiguity in ",
1495 "your git configuration file before ",
1496 "continuing\n";
1498 $seen{$1} = $_;
1503 sub find_existing_remote {
1504 my ($url, $remotes) = @_;
1505 return undef if $no_reuse_existing;
1506 my $existing;
1507 foreach my $repo_id (keys %$remotes) {
1508 my $u = $remotes->{$repo_id}->{url} or next;
1509 next if $u ne $url;
1510 $existing = $repo_id;
1511 last;
1513 $existing;
1516 sub init_remote_config {
1517 my ($self, $url, $no_write) = @_;
1518 $url =~ s!/+$!!; # strip trailing slash
1519 my $r = read_all_remotes();
1520 my $existing = find_existing_remote($url, $r);
1521 if ($existing) {
1522 unless ($no_write) {
1523 print STDERR "Using existing ",
1524 "[svn-remote \"$existing\"]\n";
1526 $self->{repo_id} = $existing;
1527 } elsif ($_minimize_url) {
1528 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1529 $existing = find_existing_remote($min_url, $r);
1530 if ($existing) {
1531 unless ($no_write) {
1532 print STDERR "Using existing ",
1533 "[svn-remote \"$existing\"]\n";
1535 $self->{repo_id} = $existing;
1537 if ($min_url ne $url) {
1538 unless ($no_write) {
1539 print STDERR "Using higher level of URL: ",
1540 "$url => $min_url\n";
1542 my $old_path = $self->{path};
1543 $self->{path} = $url;
1544 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1545 if (length $old_path) {
1546 $self->{path} .= "/$old_path";
1548 $url = $min_url;
1551 my $orig_url;
1552 if (!$existing) {
1553 # verify that we aren't overwriting anything:
1554 $orig_url = eval {
1555 command_oneline('config', '--get',
1556 "svn-remote.$self->{repo_id}.url")
1558 if ($orig_url && ($orig_url ne $url)) {
1559 die "svn-remote.$self->{repo_id}.url already set: ",
1560 "$orig_url\nwanted to set to: $url\n";
1563 my ($xrepo_id, $xpath) = find_ref($self->refname);
1564 if (defined $xpath) {
1565 die "svn-remote.$xrepo_id.fetch already set to track ",
1566 "$xpath:refs/remotes/", $self->refname, "\n";
1568 unless ($no_write) {
1569 command_noisy('config',
1570 "svn-remote.$self->{repo_id}.url", $url);
1571 $self->{path} =~ s{^/}{};
1572 command_noisy('config', '--add',
1573 "svn-remote.$self->{repo_id}.fetch",
1574 "$self->{path}:".$self->refname);
1576 $self->{url} = $url;
1579 sub find_by_url { # repos_root and, path are optional
1580 my ($class, $full_url, $repos_root, $path) = @_;
1582 return undef unless defined $full_url;
1583 remove_username($full_url);
1584 remove_username($repos_root) if defined $repos_root;
1585 my $remotes = read_all_remotes();
1586 if (defined $full_url && defined $repos_root && !defined $path) {
1587 $path = $full_url;
1588 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1590 foreach my $repo_id (keys %$remotes) {
1591 my $u = $remotes->{$repo_id}->{url} or next;
1592 remove_username($u);
1593 next if defined $repos_root && $repos_root ne $u;
1595 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1596 foreach (qw/branches tags/) {
1597 resolve_local_globs($u, $fetch,
1598 $remotes->{$repo_id}->{$_});
1600 my $p = $path;
1601 my $rwr = rewrite_root({repo_id => $repo_id});
1602 my $svm = $remotes->{$repo_id}->{svm}
1603 if defined $remotes->{$repo_id}->{svm};
1604 unless (defined $p) {
1605 $p = $full_url;
1606 my $z = $u;
1607 my $prefix = '';
1608 if ($rwr) {
1609 $z = $rwr;
1610 } elsif (defined $svm) {
1611 $z = $svm->{source};
1612 $prefix = $svm->{replace};
1613 $prefix =~ s#^\Q$u\E(?:/|$)##;
1614 $prefix =~ s#/$##;
1616 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1618 foreach my $f (keys %$fetch) {
1619 next if $f ne $p;
1620 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1623 undef;
1626 sub init {
1627 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1628 my $self = _new($class, $repo_id, $ref_id, $path);
1629 if (defined $url) {
1630 $self->init_remote_config($url, $no_write);
1632 $self;
1635 sub find_ref {
1636 my ($ref_id) = @_;
1637 foreach (command(qw/config -l/)) {
1638 next unless m!^svn-remote\.(.+)\.fetch=
1639 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1640 my ($repo_id, $path, $ref) = ($1, $2, $3);
1641 if ($ref eq $ref_id) {
1642 $path = '' if ($path =~ m#^\./?#);
1643 return ($repo_id, $path);
1646 (undef, undef, undef);
1649 sub new {
1650 my ($class, $ref_id, $repo_id, $path) = @_;
1651 if (defined $ref_id && !defined $repo_id && !defined $path) {
1652 ($repo_id, $path) = find_ref($ref_id);
1653 if (!defined $repo_id) {
1654 die "Could not find a \"svn-remote.*.fetch\" key ",
1655 "in the repository configuration matching: ",
1656 "refs/remotes/$ref_id\n";
1659 my $self = _new($class, $repo_id, $ref_id, $path);
1660 if (!defined $self->{path} || !length $self->{path}) {
1661 my $fetch = command_oneline('config', '--get',
1662 "svn-remote.$repo_id.fetch",
1663 ":refs/remotes/$ref_id\$") or
1664 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1665 "\":refs/remotes/$ref_id\$\" in config\n";
1666 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1668 $self->{url} = command_oneline('config', '--get',
1669 "svn-remote.$repo_id.url") or
1670 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1671 $self->rebuild;
1672 $self;
1675 sub refname {
1676 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1678 # It cannot end with a slash /, we'll throw up on this because
1679 # SVN can't have directories with a slash in their name, either:
1680 if ($refname =~ m{/$}) {
1681 die "ref: '$refname' ends with a trailing slash, this is ",
1682 "not permitted by git nor Subversion\n";
1685 # It cannot have ASCII control character space, tilde ~, caret ^,
1686 # colon :, question-mark ?, asterisk *, space, or open bracket [
1687 # anywhere.
1689 # Additionally, % must be escaped because it is used for escaping
1690 # and we want our escaped refname to be reversible
1691 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1693 # no slash-separated component can begin with a dot .
1694 # /.* becomes /%2E*
1695 $refname =~ s{/\.}{/%2E}g;
1697 # It cannot have two consecutive dots .. anywhere
1698 # .. becomes %2E%2E
1699 $refname =~ s{\.\.}{%2E%2E}g;
1701 return $refname;
1704 sub desanitize_refname {
1705 my ($refname) = @_;
1706 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1707 return $refname;
1710 sub svm_uuid {
1711 my ($self) = @_;
1712 return $self->{svm}->{uuid} if $self->svm;
1713 $self->ra;
1714 unless ($self->{svm}) {
1715 die "SVM UUID not cached, and reading remotely failed\n";
1717 $self->{svm}->{uuid};
1720 sub svm {
1721 my ($self) = @_;
1722 return $self->{svm} if $self->{svm};
1723 my $svm;
1724 # see if we have it in our config, first:
1725 eval {
1726 my $section = "svn-remote.$self->{repo_id}";
1727 $svm = {
1728 source => tmp_config('--get', "$section.svm-source"),
1729 uuid => tmp_config('--get', "$section.svm-uuid"),
1730 replace => tmp_config('--get', "$section.svm-replace"),
1733 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1734 $self->{svm} = $svm;
1736 $self->{svm};
1739 sub _set_svm_vars {
1740 my ($self, $ra) = @_;
1741 return $ra if $self->svm;
1743 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1744 "(svm:source, svm:uuid) ",
1745 "from the following URLs:\n" );
1746 sub read_svm_props {
1747 my ($self, $ra, $path, $r) = @_;
1748 my $props = ($ra->get_dir($path, $r))[2];
1749 my $src = $props->{'svm:source'};
1750 my $uuid = $props->{'svm:uuid'};
1751 return undef if (!$src || !$uuid);
1753 chomp($src, $uuid);
1755 $uuid =~ m{^[0-9a-f\-]{30,}$}
1756 or die "doesn't look right - svm:uuid is '$uuid'\n";
1758 # the '!' is used to mark the repos_root!/relative/path
1759 $src =~ s{/?!/?}{/};
1760 $src =~ s{/+$}{}; # no trailing slashes please
1761 # username is of no interest
1762 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1764 my $replace = $ra->{url};
1765 $replace .= "/$path" if length $path;
1767 my $section = "svn-remote.$self->{repo_id}";
1768 tmp_config("$section.svm-source", $src);
1769 tmp_config("$section.svm-replace", $replace);
1770 tmp_config("$section.svm-uuid", $uuid);
1771 $self->{svm} = {
1772 source => $src,
1773 uuid => $uuid,
1774 replace => $replace
1778 my $r = $ra->get_latest_revnum;
1779 my $path = $self->{path};
1780 my %tried;
1781 while (length $path) {
1782 unless ($tried{"$self->{url}/$path"}) {
1783 return $ra if $self->read_svm_props($ra, $path, $r);
1784 $tried{"$self->{url}/$path"} = 1;
1786 $path =~ s#/?[^/]+$##;
1788 die "Path: '$path' should be ''\n" if $path ne '';
1789 return $ra if $self->read_svm_props($ra, $path, $r);
1790 $tried{"$self->{url}/$path"} = 1;
1792 if ($ra->{repos_root} eq $self->{url}) {
1793 die @err, (map { " $_\n" } keys %tried), "\n";
1796 # nope, make sure we're connected to the repository root:
1797 my $ok;
1798 my @tried_b;
1799 $path = $ra->{svn_path};
1800 $ra = Git::SVN::Ra->new($ra->{repos_root});
1801 while (length $path) {
1802 unless ($tried{"$ra->{url}/$path"}) {
1803 $ok = $self->read_svm_props($ra, $path, $r);
1804 last if $ok;
1805 $tried{"$ra->{url}/$path"} = 1;
1807 $path =~ s#/?[^/]+$##;
1809 die "Path: '$path' should be ''\n" if $path ne '';
1810 $ok ||= $self->read_svm_props($ra, $path, $r);
1811 $tried{"$ra->{url}/$path"} = 1;
1812 if (!$ok) {
1813 die @err, (map { " $_\n" } keys %tried), "\n";
1815 Git::SVN::Ra->new($self->{url});
1818 sub svnsync {
1819 my ($self) = @_;
1820 return $self->{svnsync} if $self->{svnsync};
1822 if ($self->no_metadata) {
1823 die "Can't have both 'noMetadata' and ",
1824 "'useSvnsyncProps' options set!\n";
1826 if ($self->rewrite_root) {
1827 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
1828 "options set!\n";
1831 my $svnsync;
1832 # see if we have it in our config, first:
1833 eval {
1834 my $section = "svn-remote.$self->{repo_id}";
1836 my $url = tmp_config('--get', "$section.svnsync-url");
1837 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1838 die "doesn't look right - svn:sync-from-url is '$url'\n";
1840 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
1841 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1842 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1844 $svnsync = { url => $url, uuid => $uuid }
1846 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
1847 return $self->{svnsync} = $svnsync;
1850 my $err = "useSvnsyncProps set, but failed to read " .
1851 "svnsync property: svn:sync-from-";
1852 my $rp = $self->ra->rev_proplist(0);
1854 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
1855 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
1856 die "doesn't look right - svn:sync-from-url is '$url'\n";
1858 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
1859 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
1860 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
1862 my $section = "svn-remote.$self->{repo_id}";
1863 tmp_config('--add', "$section.svnsync-uuid", $uuid);
1864 tmp_config('--add', "$section.svnsync-url", $url);
1865 return $self->{svnsync} = { url => $url, uuid => $uuid };
1868 # this allows us to memoize our SVN::Ra UUID locally and avoid a
1869 # remote lookup (useful for 'git svn log').
1870 sub ra_uuid {
1871 my ($self) = @_;
1872 unless ($self->{ra_uuid}) {
1873 my $key = "svn-remote.$self->{repo_id}.uuid";
1874 my $uuid = eval { tmp_config('--get', $key) };
1875 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
1876 $self->{ra_uuid} = $uuid;
1877 } else {
1878 die "ra_uuid called without URL\n" unless $self->{url};
1879 $self->{ra_uuid} = $self->ra->get_uuid;
1880 tmp_config('--add', $key, $self->{ra_uuid});
1883 $self->{ra_uuid};
1886 sub _set_repos_root {
1887 my ($self, $repos_root) = @_;
1888 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1889 $repos_root ||= $self->ra->{repos_root};
1890 tmp_config($k, $repos_root);
1891 $repos_root;
1894 sub repos_root {
1895 my ($self) = @_;
1896 my $k = "svn-remote.$self->{repo_id}.reposRoot";
1897 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
1900 sub ra {
1901 my ($self) = shift;
1902 my $ra = Git::SVN::Ra->new($self->{url});
1903 $self->_set_repos_root($ra->{repos_root});
1904 if ($self->use_svm_props && !$self->{svm}) {
1905 if ($self->no_metadata) {
1906 die "Can't have both 'noMetadata' and ",
1907 "'useSvmProps' options set!\n";
1908 } elsif ($self->use_svnsync_props) {
1909 die "Can't have both 'useSvnsyncProps' and ",
1910 "'useSvmProps' options set!\n";
1912 $ra = $self->_set_svm_vars($ra);
1913 $self->{-want_revprops} = 1;
1915 $ra;
1918 sub rel_path {
1919 my ($self) = @_;
1920 my $repos_root = $self->ra->{repos_root};
1921 return $self->{path} if ($self->{url} eq $repos_root);
1922 my $url = $self->{url} .
1923 (length $self->{path} ? "/$self->{path}" : $self->{path});
1924 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
1925 $url;
1928 # prop_walk(PATH, REV, SUB)
1929 # -------------------------
1930 # Recursively traverse PATH at revision REV and invoke SUB for each
1931 # directory that contains a SVN property. SUB will be invoked as
1932 # follows: &SUB(gs, path, props); where `gs' is this instance of
1933 # Git::SVN, `path' the path to the directory where the properties
1934 # `props' were found. The `path' will be relative to point of checkout,
1935 # that is, if url://repo/trunk is the current Git branch, and that
1936 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
1937 # as `path' (note the trailing `/').
1938 sub prop_walk {
1939 my ($self, $path, $rev, $sub) = @_;
1941 $path =~ s#^/##;
1942 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
1943 $path =~ s#^/*#/#g;
1944 my $p = $path;
1945 # Strip the irrelevant part of the path.
1946 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
1947 # Ensure the path is terminated by a `/'.
1948 $p =~ s#/*$#/#;
1950 # The properties contain all the internal SVN stuff nobody
1951 # (usually) cares about.
1952 my $interesting_props = 0;
1953 foreach (keys %{$props}) {
1954 # If it doesn't start with `svn:', it must be a
1955 # user-defined property.
1956 ++$interesting_props and next if $_ !~ /^svn:/;
1957 # FIXME: Fragile, if SVN adds new public properties,
1958 # this needs to be updated.
1959 ++$interesting_props if /^svn:(?:ignore|keywords|executable
1960 |eol-style|mime-type
1961 |externals|needs-lock)$/x;
1963 &$sub($self, $p, $props) if $interesting_props;
1965 foreach (sort keys %$dirent) {
1966 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
1967 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
1971 sub last_rev { ($_[0]->last_rev_commit)[0] }
1972 sub last_commit { ($_[0]->last_rev_commit)[1] }
1974 # returns the newest SVN revision number and newest commit SHA1
1975 sub last_rev_commit {
1976 my ($self) = @_;
1977 if (defined $self->{last_rev} && defined $self->{last_commit}) {
1978 return ($self->{last_rev}, $self->{last_commit});
1980 my $c = ::verify_ref($self->refname.'^0');
1981 if ($c && !$self->use_svm_props && !$self->no_metadata) {
1982 my $rev = (::cmt_metadata($c))[1];
1983 if (defined $rev) {
1984 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
1985 return ($rev, $c);
1988 my $map_path = $self->map_path;
1989 unless (-e $map_path) {
1990 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
1991 return (undef, undef);
1993 my ($rev, $commit) = $self->rev_map_max(1);
1994 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
1995 return ($rev, $commit);
1998 sub get_fetch_range {
1999 my ($self, $min, $max) = @_;
2000 $max ||= $self->ra->get_latest_revnum;
2001 $min ||= $self->rev_map_max;
2002 (++$min, $max);
2005 sub tmp_config {
2006 my (@args) = @_;
2007 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2008 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2009 if (! -f $config && -f $old_def_config) {
2010 rename $old_def_config, $config or
2011 die "Failed rename $old_def_config => $config: $!\n";
2013 my $old_config = $ENV{GIT_CONFIG};
2014 $ENV{GIT_CONFIG} = $config;
2015 $@ = undef;
2016 my @ret = eval {
2017 unless (-f $config) {
2018 mkfile($config);
2019 open my $fh, '>', $config or
2020 die "Can't open $config: $!\n";
2021 print $fh "; This file is used internally by ",
2022 "git-svn\n" or die
2023 "Couldn't write to $config: $!\n";
2024 print $fh "; You should not have to edit it\n" or
2025 die "Couldn't write to $config: $!\n";
2026 close $fh or die "Couldn't close $config: $!\n";
2028 command('config', @args);
2030 my $err = $@;
2031 if (defined $old_config) {
2032 $ENV{GIT_CONFIG} = $old_config;
2033 } else {
2034 delete $ENV{GIT_CONFIG};
2036 die $err if $err;
2037 wantarray ? @ret : $ret[0];
2040 sub tmp_index_do {
2041 my ($self, $sub) = @_;
2042 my $old_index = $ENV{GIT_INDEX_FILE};
2043 $ENV{GIT_INDEX_FILE} = $self->{index};
2044 $@ = undef;
2045 my @ret = eval {
2046 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2047 mkpath([$dir]) unless -d $dir;
2048 &$sub;
2050 my $err = $@;
2051 if (defined $old_index) {
2052 $ENV{GIT_INDEX_FILE} = $old_index;
2053 } else {
2054 delete $ENV{GIT_INDEX_FILE};
2056 die $err if $err;
2057 wantarray ? @ret : $ret[0];
2060 sub assert_index_clean {
2061 my ($self, $treeish) = @_;
2063 $self->tmp_index_do(sub {
2064 command_noisy('read-tree', $treeish) unless -e $self->{index};
2065 my $x = command_oneline('write-tree');
2066 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2067 /^tree ($::sha1)/mo);
2068 return if $y eq $x;
2070 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2071 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2072 command_noisy('read-tree', $treeish);
2073 $x = command_oneline('write-tree');
2074 if ($y ne $x) {
2075 ::fatal "trees ($treeish) $y != $x\n",
2076 "Something is seriously wrong...";
2081 sub get_commit_parents {
2082 my ($self, $log_entry) = @_;
2083 my (%seen, @ret, @tmp);
2084 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2085 if (my $ip = $self->{inject_parents}) {
2086 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2087 push @tmp, $commit;
2090 if (my $cur = ::verify_ref($self->refname.'^0')) {
2091 push @tmp, $cur;
2093 if (my $ipd = $self->{inject_parents_dcommit}) {
2094 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2095 push @tmp, @$commit;
2098 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2099 while (my $p = shift @tmp) {
2100 next if $seen{$p};
2101 $seen{$p} = 1;
2102 push @ret, $p;
2103 # MAXPARENT is defined to 16 in commit-tree.c:
2104 last if @ret >= 16;
2106 if (@tmp) {
2107 die "r$log_entry->{revision}: No room for parents:\n\t",
2108 join("\n\t", @tmp), "\n";
2110 @ret;
2113 sub rewrite_root {
2114 my ($self) = @_;
2115 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2116 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2117 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2118 if ($rwr) {
2119 $rwr =~ s#/+$##;
2120 if ($rwr !~ m#^[a-z\+]+://#) {
2121 die "$rwr is not a valid URL (key: $k)\n";
2124 $self->{-rewrite_root} = $rwr;
2127 sub metadata_url {
2128 my ($self) = @_;
2129 ($self->rewrite_root || $self->{url}) .
2130 (length $self->{path} ? '/' . $self->{path} : '');
2133 sub full_url {
2134 my ($self) = @_;
2135 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2139 sub set_commit_header_env {
2140 my ($log_entry) = @_;
2141 my %env;
2142 foreach my $ned (qw/NAME EMAIL DATE/) {
2143 foreach my $ac (qw/AUTHOR COMMITTER/) {
2144 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2148 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2149 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2150 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2152 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2153 ? $log_entry->{commit_name}
2154 : $log_entry->{name};
2155 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2156 ? $log_entry->{commit_email}
2157 : $log_entry->{email};
2158 \%env;
2161 sub restore_commit_header_env {
2162 my ($env) = @_;
2163 foreach my $ned (qw/NAME EMAIL DATE/) {
2164 foreach my $ac (qw/AUTHOR COMMITTER/) {
2165 my $k = "GIT_${ac}_${ned}";
2166 if (defined $env->{$k}) {
2167 $ENV{$k} = $env->{$k};
2168 } else {
2169 delete $ENV{$k};
2175 sub gc {
2176 command_noisy('gc', '--auto');
2179 sub do_git_commit {
2180 my ($self, $log_entry) = @_;
2181 my $lr = $self->last_rev;
2182 if (defined $lr && $lr >= $log_entry->{revision}) {
2183 die "Last fetched revision of ", $self->refname,
2184 " was r$lr, but we are about to fetch: ",
2185 "r$log_entry->{revision}!\n";
2187 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2188 croak "$log_entry->{revision} = $c already exists! ",
2189 "Why are we refetching it?\n";
2191 my $old_env = set_commit_header_env($log_entry);
2192 my $tree = $log_entry->{tree};
2193 if (!defined $tree) {
2194 $tree = $self->tmp_index_do(sub {
2195 command_oneline('write-tree') });
2197 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2199 my @exec = ('git-commit-tree', $tree);
2200 foreach ($self->get_commit_parents($log_entry)) {
2201 push @exec, '-p', $_;
2203 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2204 or croak $!;
2205 print $msg_fh $log_entry->{log} or croak $!;
2206 restore_commit_header_env($old_env);
2207 unless ($self->no_metadata) {
2208 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2209 or croak $!;
2211 $msg_fh->flush == 0 or croak $!;
2212 close $msg_fh or croak $!;
2213 chomp(my $commit = do { local $/; <$out_fh> });
2214 close $out_fh or croak $!;
2215 waitpid $pid, 0;
2216 croak $? if $?;
2217 if ($commit !~ /^$::sha1$/o) {
2218 die "Failed to commit, invalid sha1: $commit\n";
2221 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2223 $self->{last_rev} = $log_entry->{revision};
2224 $self->{last_commit} = $commit;
2225 print "r$log_entry->{revision}";
2226 if (defined $log_entry->{svm_revision}) {
2227 print " (\@$log_entry->{svm_revision})";
2228 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2229 0, $self->svm_uuid);
2231 print " = $commit ($self->{ref_id})\n";
2232 if (--$_gc_nr == 0) {
2233 $_gc_nr = $_gc_period;
2234 gc();
2236 return $commit;
2239 sub match_paths {
2240 my ($self, $paths, $r) = @_;
2241 return 1 if $self->{path} eq '';
2242 if (my $path = $paths->{"/$self->{path}"}) {
2243 return ($path->{action} eq 'D') ? 0 : 1;
2245 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2246 if (grep /$self->{path_regex}/, keys %$paths) {
2247 return 1;
2249 my $c = '';
2250 foreach (split m#/#, $self->{path}) {
2251 $c .= "/$_";
2252 next unless ($paths->{$c} &&
2253 ($paths->{$c}->{action} =~ /^[AR]$/));
2254 if ($self->ra->check_path($self->{path}, $r) ==
2255 $SVN::Node::dir) {
2256 return 1;
2259 return 0;
2262 sub find_parent_branch {
2263 my ($self, $paths, $rev) = @_;
2264 return undef unless $self->follow_parent;
2265 unless (defined $paths) {
2266 my $err_handler = $SVN::Error::handler;
2267 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2268 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2269 $paths =
2270 Git::SVN::Ra::dup_changed_paths($_[0]) });
2271 $SVN::Error::handler = $err_handler;
2273 return undef unless defined $paths;
2275 # look for a parent from another branch:
2276 my @b_path_components = split m#/#, $self->rel_path;
2277 my @a_path_components;
2278 my $i;
2279 while (@b_path_components) {
2280 $i = $paths->{'/'.join('/', @b_path_components)};
2281 last if $i && defined $i->{copyfrom_path};
2282 unshift(@a_path_components, pop(@b_path_components));
2284 return undef unless defined $i && defined $i->{copyfrom_path};
2285 my $branch_from = $i->{copyfrom_path};
2286 if (@a_path_components) {
2287 print STDERR "branch_from: $branch_from => ";
2288 $branch_from .= '/'.join('/', @a_path_components);
2289 print STDERR $branch_from, "\n";
2291 my $r = $i->{copyfrom_rev};
2292 my $repos_root = $self->ra->{repos_root};
2293 my $url = $self->ra->{url};
2294 my $new_url = $repos_root . $branch_from;
2295 print STDERR "Found possible branch point: ",
2296 "$new_url => ", $self->full_url, ", $r\n";
2297 $branch_from =~ s#^/##;
2298 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2299 unless ($gs) {
2300 my $ref_id = $self->{ref_id};
2301 $ref_id =~ s/\@\d+$//;
2302 $ref_id .= "\@$r";
2303 # just grow a tail if we're not unique enough :x
2304 $ref_id .= '-' while find_ref($ref_id);
2305 print STDERR "Initializing parent: $ref_id\n";
2306 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2307 if ($u =~ s#^\Q$url\E(/|$)##) {
2308 $p = $u;
2309 $u = $url;
2310 $repo_id = $self->{repo_id};
2312 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2314 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2315 if (!defined $r0 || !defined $parent) {
2316 my ($base, $head) = parse_revision_argument(0, $r);
2317 if ($base <= $r) {
2318 $gs->fetch($base, $r);
2320 ($r0, $parent) = $gs->last_rev_commit;
2322 if (defined $r0 && defined $parent) {
2323 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2324 my $ed;
2325 if ($self->ra->can_do_switch) {
2326 $self->assert_index_clean($parent);
2327 print STDERR "Following parent with do_switch\n";
2328 # do_switch works with svn/trunk >= r22312, but that
2329 # is not included with SVN 1.4.3 (the latest version
2330 # at the moment), so we can't rely on it
2331 $self->{last_commit} = $parent;
2332 $ed = SVN::Git::Fetcher->new($self);
2333 $gs->ra->gs_do_switch($r0, $rev, $gs,
2334 $self->full_url, $ed)
2335 or die "SVN connection failed somewhere...\n";
2336 } elsif ($self->ra->trees_match($new_url, $r0,
2337 $self->full_url, $rev)) {
2338 print STDERR "Trees match:\n",
2339 " $new_url\@$r0\n",
2340 " ${\$self->full_url}\@$rev\n",
2341 "Following parent with no changes\n";
2342 $self->tmp_index_do(sub {
2343 command_noisy('read-tree', $parent);
2345 $self->{last_commit} = $parent;
2346 } else {
2347 print STDERR "Following parent with do_update\n";
2348 $ed = SVN::Git::Fetcher->new($self);
2349 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2350 or die "SVN connection failed somewhere...\n";
2352 print STDERR "Successfully followed parent\n";
2353 return $self->make_log_entry($rev, [$parent], $ed);
2355 return undef;
2358 sub do_fetch {
2359 my ($self, $paths, $rev) = @_;
2360 my $ed;
2361 my ($last_rev, @parents);
2362 if (my $lc = $self->last_commit) {
2363 # we can have a branch that was deleted, then re-added
2364 # under the same name but copied from another path, in
2365 # which case we'll have multiple parents (we don't
2366 # want to break the original ref, nor lose copypath info):
2367 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2368 push @{$log_entry->{parents}}, $lc;
2369 return $log_entry;
2371 $ed = SVN::Git::Fetcher->new($self);
2372 $last_rev = $self->{last_rev};
2373 $ed->{c} = $lc;
2374 @parents = ($lc);
2375 } else {
2376 $last_rev = $rev;
2377 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2378 return $log_entry;
2380 $ed = SVN::Git::Fetcher->new($self);
2382 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2383 die "SVN connection failed somewhere...\n";
2385 $self->make_log_entry($rev, \@parents, $ed);
2388 sub get_untracked {
2389 my ($self, $ed) = @_;
2390 my @out;
2391 my $h = $ed->{empty};
2392 foreach (sort keys %$h) {
2393 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2394 push @out, " $act: " . uri_encode($_);
2395 warn "W: $act: $_\n";
2397 foreach my $t (qw/dir_prop file_prop/) {
2398 $h = $ed->{$t} or next;
2399 foreach my $path (sort keys %$h) {
2400 my $ppath = $path eq '' ? '.' : $path;
2401 foreach my $prop (sort keys %{$h->{$path}}) {
2402 next if $SKIP_PROP{$prop};
2403 my $v = $h->{$path}->{$prop};
2404 my $t_ppath_prop = "$t: " .
2405 uri_encode($ppath) . ' ' .
2406 uri_encode($prop);
2407 if (defined $v) {
2408 push @out, " +$t_ppath_prop " .
2409 uri_encode($v);
2410 } else {
2411 push @out, " -$t_ppath_prop";
2416 foreach my $t (qw/absent_file absent_directory/) {
2417 $h = $ed->{$t} or next;
2418 foreach my $parent (sort keys %$h) {
2419 foreach my $path (sort @{$h->{$parent}}) {
2420 push @out, " $t: " .
2421 uri_encode("$parent/$path");
2422 warn "W: $t: $parent/$path ",
2423 "Insufficient permissions?\n";
2427 \@out;
2430 sub parse_svn_date {
2431 my $date = shift || return '+0000 1970-01-01 00:00:00';
2432 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2433 (\d\d)\:(\d\d)\:(\d\d).\d+Z$/x) or
2434 croak "Unable to parse date: $date\n";
2435 "+0000 $Y-$m-$d $H:$M:$S";
2438 sub check_author {
2439 my ($author) = @_;
2440 if (!defined $author || length $author == 0) {
2441 $author = '(no author)';
2442 } elsif (defined $::_authors && ! defined $::users{$author}) {
2443 die "Author: $author not defined in $::_authors file\n";
2445 $author;
2448 sub make_log_entry {
2449 my ($self, $rev, $parents, $ed) = @_;
2450 my $untracked = $self->get_untracked($ed);
2452 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2453 print $un "r$rev\n" or croak $!;
2454 print $un $_, "\n" foreach @$untracked;
2455 my %log_entry = ( parents => $parents || [], revision => $rev,
2456 log => '');
2458 my $headrev;
2459 my $logged = delete $self->{logged_rev_props};
2460 if (!$logged || $self->{-want_revprops}) {
2461 my $rp = $self->ra->rev_proplist($rev);
2462 foreach (sort keys %$rp) {
2463 my $v = $rp->{$_};
2464 if (/^svn:(author|date|log)$/) {
2465 $log_entry{$1} = $v;
2466 } elsif ($_ eq 'svm:headrev') {
2467 $headrev = $v;
2468 } else {
2469 print $un " rev_prop: ", uri_encode($_), ' ',
2470 uri_encode($v), "\n";
2473 } else {
2474 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2476 close $un or croak $!;
2478 $log_entry{date} = parse_svn_date($log_entry{date});
2479 $log_entry{log} .= "\n";
2480 my $author = $log_entry{author} = check_author($log_entry{author});
2481 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2482 : ($author, undef);
2484 my ($commit_name, $commit_email) = ($name, $email);
2485 if ($_use_log_author) {
2486 my $name_field;
2487 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2488 $name_field = $1;
2489 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2490 $name_field = $1;
2492 if (!defined $name_field) {
2493 if (!defined $email) {
2494 $email = $name;
2496 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2497 ($name, $email) = ($1, $2);
2498 } elsif ($name_field =~ /(.*)@/) {
2499 ($name, $email) = ($1, $name_field);
2500 } else {
2501 ($name, $email) = ($name_field, $name_field);
2504 if (defined $headrev && $self->use_svm_props) {
2505 if ($self->rewrite_root) {
2506 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2507 "options set!\n";
2509 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2510 # we don't want "SVM: initializing mirror for junk" ...
2511 return undef if $r == 0;
2512 my $svm = $self->svm;
2513 if ($uuid ne $svm->{uuid}) {
2514 die "UUID mismatch on SVM path:\n",
2515 "expected: $svm->{uuid}\n",
2516 " got: $uuid\n";
2518 my $full_url = $self->full_url;
2519 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2520 die "Failed to replace '$svm->{replace}' with ",
2521 "'$svm->{source}' in $full_url\n";
2522 # throw away username for storing in records
2523 remove_username($full_url);
2524 $log_entry{metadata} = "$full_url\@$r $uuid";
2525 $log_entry{svm_revision} = $r;
2526 $email ||= "$author\@$uuid";
2527 $commit_email ||= "$author\@$uuid";
2528 } elsif ($self->use_svnsync_props) {
2529 my $full_url = $self->svnsync->{url};
2530 $full_url .= "/$self->{path}" if length $self->{path};
2531 remove_username($full_url);
2532 my $uuid = $self->svnsync->{uuid};
2533 $log_entry{metadata} = "$full_url\@$rev $uuid";
2534 $email ||= "$author\@$uuid";
2535 $commit_email ||= "$author\@$uuid";
2536 } else {
2537 my $url = $self->metadata_url;
2538 remove_username($url);
2539 $log_entry{metadata} = "$url\@$rev " .
2540 $self->ra->get_uuid;
2541 $email ||= "$author\@" . $self->ra->get_uuid;
2542 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2544 $log_entry{name} = $name;
2545 $log_entry{email} = $email;
2546 $log_entry{commit_name} = $commit_name;
2547 $log_entry{commit_email} = $commit_email;
2548 \%log_entry;
2551 sub fetch {
2552 my ($self, $min_rev, $max_rev, @parents) = @_;
2553 my ($last_rev, $last_commit) = $self->last_rev_commit;
2554 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2555 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2558 sub set_tree_cb {
2559 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2560 $self->{inject_parents} = { $rev => $tree };
2561 $self->fetch(undef, undef);
2564 sub set_tree {
2565 my ($self, $tree) = (shift, shift);
2566 my $log_entry = ::get_commit_entry($tree);
2567 unless ($self->{last_rev}) {
2568 fatal("Must have an existing revision to commit");
2570 my %ed_opts = ( r => $self->{last_rev},
2571 log => $log_entry->{log},
2572 ra => $self->ra,
2573 tree_a => $self->{last_commit},
2574 tree_b => $tree,
2575 editor_cb => sub {
2576 $self->set_tree_cb($log_entry, $tree, @_) },
2577 svn_path => $self->{path} );
2578 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2579 print "No changes\nr$self->{last_rev} = $tree\n";
2583 sub rebuild_from_rev_db {
2584 my ($self, $path) = @_;
2585 my $r = -1;
2586 open my $fh, '<', $path or croak "open: $!";
2587 binmode $fh or croak "binmode: $!";
2588 while (<$fh>) {
2589 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2590 chomp($_);
2591 ++$r;
2592 next if $_ eq ('0' x 40);
2593 $self->rev_map_set($r, $_);
2594 print "r$r = $_\n";
2596 close $fh or croak "close: $!";
2597 unlink $path or croak "unlink: $!";
2600 sub rebuild {
2601 my ($self) = @_;
2602 my $map_path = $self->map_path;
2603 return if (-e $map_path && ! -z $map_path);
2604 return unless ::verify_ref($self->refname.'^0');
2605 if ($self->use_svm_props || $self->no_metadata) {
2606 my $rev_db = $self->rev_db_path;
2607 $self->rebuild_from_rev_db($rev_db);
2608 if ($self->use_svm_props) {
2609 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2610 $self->rebuild_from_rev_db($svm_rev_db);
2612 $self->unlink_rev_db_symlink;
2613 return;
2615 print "Rebuilding $map_path ...\n";
2616 my ($log, $ctx) =
2617 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2618 $self->refname, '--');
2619 my $metadata_url = $self->metadata_url;
2620 remove_username($metadata_url);
2621 my $svn_uuid = $self->ra_uuid;
2622 my $c;
2623 while (<$log>) {
2624 if ( m{^commit ($::sha1)$} ) {
2625 $c = $1;
2626 next;
2628 next unless s{^\s*(git-svn-id:)}{$1};
2629 my ($url, $rev, $uuid) = ::extract_metadata($_);
2630 remove_username($url);
2632 # ignore merges (from set-tree)
2633 next if (!defined $rev || !$uuid);
2635 # if we merged or otherwise started elsewhere, this is
2636 # how we break out of it
2637 if (($uuid ne $svn_uuid) ||
2638 ($metadata_url && $url && ($url ne $metadata_url))) {
2639 next;
2642 $self->rev_map_set($rev, $c);
2643 print "r$rev = $c\n";
2645 command_close_pipe($log, $ctx);
2646 print "Done rebuilding $map_path\n";
2647 my $rev_db_path = $self->rev_db_path;
2648 if (-f $self->rev_db_path) {
2649 unlink $self->rev_db_path or croak "unlink: $!";
2651 $self->unlink_rev_db_symlink;
2654 # rev_map:
2655 # Tie::File seems to be prone to offset errors if revisions get sparse,
2656 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2657 # one of my favorite modules is out :< Next up would be one of the DBM
2658 # modules, but I'm not sure which is most portable...
2660 # This is the replacement for the rev_db format, which was too big
2661 # and inefficient for large repositories with a lot of sparse history
2662 # (mainly tags)
2664 # The format is this:
2665 # - 24 bytes for every record,
2666 # * 4 bytes for the integer representing an SVN revision number
2667 # * 20 bytes representing the sha1 of a git commit
2668 # - No empty padding records like the old format
2669 # (except the last record, which can be overwritten)
2670 # - new records are written append-only since SVN revision numbers
2671 # increase monotonically
2672 # - lookups on SVN revision number are done via a binary search
2673 # - Piping the file to xxd -c24 is a good way of dumping it for
2674 # viewing or editing (piped back through xxd -r), should the need
2675 # ever arise.
2676 # - The last record can be padding revision with an all-zero sha1
2677 # This is used to optimize fetch performance when using multiple
2678 # "fetch" directives in .git/config
2680 # These files are disposable unless noMetadata or useSvmProps is set
2682 sub _rev_map_set {
2683 my ($fh, $rev, $commit) = @_;
2685 binmode $fh or croak "binmode: $!";
2686 my $size = (stat($fh))[7];
2687 ($size % 24) == 0 or croak "inconsistent size: $size";
2689 my $wr_offset = 0;
2690 if ($size > 0) {
2691 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2692 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2693 $read == 24 or croak "read only $read bytes (!= 24)";
2694 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2695 if ($last_commit eq ('0' x40)) {
2696 if ($size >= 48) {
2697 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2698 $read = sysread($fh, $buf, 24) or
2699 croak "read: $!";
2700 $read == 24 or
2701 croak "read only $read bytes (!= 24)";
2702 ($last_rev, $last_commit) =
2703 unpack(rev_map_fmt, $buf);
2704 if ($last_commit eq ('0' x40)) {
2705 croak "inconsistent .rev_map\n";
2708 if ($last_rev >= $rev) {
2709 croak "last_rev is higher!: $last_rev >= $rev";
2711 $wr_offset = -24;
2714 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
2715 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
2716 croak "write: $!";
2719 sub mkfile {
2720 my ($path) = @_;
2721 unless (-e $path) {
2722 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
2723 mkpath([$dir]) unless -d $dir;
2724 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
2725 close $fh or die "Couldn't close (create) $path: $!\n";
2729 sub rev_map_set {
2730 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
2731 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
2732 my $db = $self->map_path($uuid);
2733 my $db_lock = "$db.lock";
2734 my $sig;
2735 if ($update_ref) {
2736 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2737 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
2739 mkfile($db);
2741 $LOCKFILES{$db_lock} = 1;
2742 my $sync;
2743 # both of these options make our .rev_db file very, very important
2744 # and we can't afford to lose it because rebuild() won't work
2745 if ($self->use_svm_props || $self->no_metadata) {
2746 $sync = 1;
2747 copy($db, $db_lock) or die "rev_map_set(@_): ",
2748 "Failed to copy: ",
2749 "$db => $db_lock ($!)\n";
2750 } else {
2751 rename $db, $db_lock or die "rev_map_set(@_): ",
2752 "Failed to rename: ",
2753 "$db => $db_lock ($!)\n";
2756 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
2757 or croak "Couldn't open $db_lock: $!\n";
2758 _rev_map_set($fh, $rev, $commit);
2759 if ($sync) {
2760 $fh->flush or die "Couldn't flush $db_lock: $!\n";
2761 $fh->sync or die "Couldn't sync $db_lock: $!\n";
2763 close $fh or croak $!;
2764 if ($update_ref) {
2765 $_head = $self;
2766 command_noisy('update-ref', '-m', "r$rev",
2767 $self->refname, $commit);
2769 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
2770 "$db_lock => $db ($!)\n";
2771 delete $LOCKFILES{$db_lock};
2772 if ($update_ref) {
2773 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
2774 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
2775 kill $sig, $$ if defined $sig;
2779 # If want_commit, this will return an array of (rev, commit) where
2780 # commit _must_ be a valid commit in the archive.
2781 # Otherwise, it'll return the max revision (whether or not the
2782 # commit is valid or just a 0x40 placeholder).
2783 sub rev_map_max {
2784 my ($self, $want_commit) = @_;
2785 $self->rebuild;
2786 my $map_path = $self->map_path;
2787 stat $map_path or return $want_commit ? (0, undef) : 0;
2788 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2789 binmode $fh or croak "binmode: $!";
2790 my $size = (stat($fh))[7];
2791 ($size % 24) == 0 or croak "inconsistent size: $size";
2793 if ($size == 0) {
2794 close $fh or croak "close: $!";
2795 return $want_commit ? (0, undef) : 0;
2798 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2799 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2800 my ($r, $c) = unpack(rev_map_fmt, $buf);
2801 if ($want_commit && $c eq ('0' x40)) {
2802 if ($size < 48) {
2803 return $want_commit ? (0, undef) : 0;
2805 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
2806 sysread($fh, $buf, 24) == 24 or croak "read: $!";
2807 ($r, $c) = unpack(rev_map_fmt, $buf);
2808 if ($c eq ('0'x40)) {
2809 croak "Penultimate record is all-zeroes in $map_path";
2812 close $fh or croak "close: $!";
2813 $want_commit ? ($r, $c) : $r;
2816 sub rev_map_get {
2817 my ($self, $rev, $uuid) = @_;
2818 my $map_path = $self->map_path($uuid);
2819 return undef unless -e $map_path;
2821 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
2822 binmode $fh or croak "binmode: $!";
2823 my $size = (stat($fh))[7];
2824 ($size % 24) == 0 or croak "inconsistent size: $size";
2826 if ($size == 0) {
2827 close $fh or croak "close: $fh";
2828 return undef;
2831 my ($l, $u) = (0, $size - 24);
2832 my ($r, $c, $buf);
2834 while ($l <= $u) {
2835 my $i = int(($l/24 + $u/24) / 2) * 24;
2836 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
2837 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
2838 my ($r, $c) = unpack('NH40', $buf);
2840 if ($r < $rev) {
2841 $l = $i + 24;
2842 } elsif ($r > $rev) {
2843 $u = $i - 24;
2844 } else { # $r == $rev
2845 close($fh) or croak "close: $!";
2846 return $c eq ('0' x 40) ? undef : $c;
2849 close($fh) or croak "close: $!";
2850 undef;
2853 # Finds the first svn revision that exists on (if $eq_ok is true) or
2854 # before $rev for the current branch. It will not search any lower
2855 # than $min_rev. Returns the git commit hash and svn revision number
2856 # if found, else (undef, undef).
2857 sub find_rev_before {
2858 my ($self, $rev, $eq_ok, $min_rev) = @_;
2859 --$rev unless $eq_ok;
2860 $min_rev ||= 1;
2861 while ($rev >= $min_rev) {
2862 if (my $c = $self->rev_map_get($rev)) {
2863 return ($rev, $c);
2865 --$rev;
2867 return (undef, undef);
2870 # Finds the first svn revision that exists on (if $eq_ok is true) or
2871 # after $rev for the current branch. It will not search any higher
2872 # than $max_rev. Returns the git commit hash and svn revision number
2873 # if found, else (undef, undef).
2874 sub find_rev_after {
2875 my ($self, $rev, $eq_ok, $max_rev) = @_;
2876 ++$rev unless $eq_ok;
2877 $max_rev ||= $self->rev_map_max;
2878 while ($rev <= $max_rev) {
2879 if (my $c = $self->rev_map_get($rev)) {
2880 return ($rev, $c);
2882 ++$rev;
2884 return (undef, undef);
2887 sub _new {
2888 my ($class, $repo_id, $ref_id, $path) = @_;
2889 unless (defined $repo_id && length $repo_id) {
2890 $repo_id = $Git::SVN::default_repo_id;
2892 unless (defined $ref_id && length $ref_id) {
2893 $_[2] = $ref_id = $Git::SVN::default_ref_id;
2895 $_[1] = $repo_id;
2896 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
2897 $_[3] = $path = '' unless (defined $path);
2898 mkpath(["$ENV{GIT_DIR}/svn"]);
2899 bless {
2900 ref_id => $ref_id, dir => $dir, index => "$dir/index",
2901 path => $path, config => "$ENV{GIT_DIR}/svn/config",
2902 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
2905 # for read-only access of old .rev_db formats
2906 sub unlink_rev_db_symlink {
2907 my ($self) = @_;
2908 my $link = $self->rev_db_path;
2909 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
2910 if (-l $link) {
2911 unlink $link or croak "unlink: $link failed!";
2915 sub rev_db_path {
2916 my ($self, $uuid) = @_;
2917 my $db_path = $self->map_path($uuid);
2918 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
2919 or croak "map_path: $db_path does not contain '/.rev_map.' !";
2920 $db_path;
2923 # the new replacement for .rev_db
2924 sub map_path {
2925 my ($self, $uuid) = @_;
2926 $uuid ||= $self->ra_uuid;
2927 "$self->{map_root}.$uuid";
2930 sub uri_encode {
2931 my ($f) = @_;
2932 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
2936 sub remove_username {
2937 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
2940 package Git::SVN::Prompt;
2941 use strict;
2942 use warnings;
2943 require SVN::Core;
2944 use vars qw/$_no_auth_cache $_username/;
2946 sub simple {
2947 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
2948 $may_save = undef if $_no_auth_cache;
2949 $default_username = $_username if defined $_username;
2950 if (defined $default_username && length $default_username) {
2951 if (defined $realm && length $realm) {
2952 print STDERR "Authentication realm: $realm\n";
2953 STDERR->flush;
2955 $cred->username($default_username);
2956 } else {
2957 username($cred, $realm, $may_save, $pool);
2959 $cred->password(_read_password("Password for '" .
2960 $cred->username . "': ", $realm));
2961 $cred->may_save($may_save);
2962 $SVN::_Core::SVN_NO_ERROR;
2965 sub ssl_server_trust {
2966 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
2967 $may_save = undef if $_no_auth_cache;
2968 print STDERR "Error validating server certificate for '$realm':\n";
2970 no warnings 'once';
2971 # All variables SVN::Auth::SSL::* are used only once,
2972 # so we're shutting up Perl warnings about this.
2973 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
2974 print STDERR " - The certificate is not issued ",
2975 "by a trusted authority. Use the\n",
2976 " fingerprint to validate ",
2977 "the certificate manually!\n";
2979 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
2980 print STDERR " - The certificate hostname ",
2981 "does not match.\n";
2983 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
2984 print STDERR " - The certificate is not yet valid.\n";
2986 if ($failures & $SVN::Auth::SSL::EXPIRED) {
2987 print STDERR " - The certificate has expired.\n";
2989 if ($failures & $SVN::Auth::SSL::OTHER) {
2990 print STDERR " - The certificate has ",
2991 "an unknown error.\n";
2993 } # no warnings 'once'
2994 printf STDERR
2995 "Certificate information:\n".
2996 " - Hostname: %s\n".
2997 " - Valid: from %s until %s\n".
2998 " - Issuer: %s\n".
2999 " - Fingerprint: %s\n",
3000 map $cert_info->$_, qw(hostname valid_from valid_until
3001 issuer_dname fingerprint);
3002 my $choice;
3003 prompt:
3004 print STDERR $may_save ?
3005 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3006 "(R)eject or accept (t)emporarily? ";
3007 STDERR->flush;
3008 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3009 if ($choice =~ /^t$/i) {
3010 $cred->may_save(undef);
3011 } elsif ($choice =~ /^r$/i) {
3012 return -1;
3013 } elsif ($may_save && $choice =~ /^p$/i) {
3014 $cred->may_save($may_save);
3015 } else {
3016 goto prompt;
3018 $cred->accepted_failures($failures);
3019 $SVN::_Core::SVN_NO_ERROR;
3022 sub ssl_client_cert {
3023 my ($cred, $realm, $may_save, $pool) = @_;
3024 $may_save = undef if $_no_auth_cache;
3025 print STDERR "Client certificate filename: ";
3026 STDERR->flush;
3027 chomp(my $filename = <STDIN>);
3028 $cred->cert_file($filename);
3029 $cred->may_save($may_save);
3030 $SVN::_Core::SVN_NO_ERROR;
3033 sub ssl_client_cert_pw {
3034 my ($cred, $realm, $may_save, $pool) = @_;
3035 $may_save = undef if $_no_auth_cache;
3036 $cred->password(_read_password("Password: ", $realm));
3037 $cred->may_save($may_save);
3038 $SVN::_Core::SVN_NO_ERROR;
3041 sub username {
3042 my ($cred, $realm, $may_save, $pool) = @_;
3043 $may_save = undef if $_no_auth_cache;
3044 if (defined $realm && length $realm) {
3045 print STDERR "Authentication realm: $realm\n";
3047 my $username;
3048 if (defined $_username) {
3049 $username = $_username;
3050 } else {
3051 print STDERR "Username: ";
3052 STDERR->flush;
3053 chomp($username = <STDIN>);
3055 $cred->username($username);
3056 $cred->may_save($may_save);
3057 $SVN::_Core::SVN_NO_ERROR;
3060 sub _read_password {
3061 my ($prompt, $realm) = @_;
3062 print STDERR $prompt;
3063 STDERR->flush;
3064 require Term::ReadKey;
3065 Term::ReadKey::ReadMode('noecho');
3066 my $password = '';
3067 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3068 last if $key =~ /[\012\015]/; # \n\r
3069 $password .= $key;
3071 Term::ReadKey::ReadMode('restore');
3072 print STDERR "\n";
3073 STDERR->flush;
3074 $password;
3077 package SVN::Git::Fetcher;
3078 use vars qw/@ISA/;
3079 use strict;
3080 use warnings;
3081 use Carp qw/croak/;
3082 use File::Temp qw/tempfile/;
3083 use IO::File qw//;
3085 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3086 sub new {
3087 my ($class, $git_svn) = @_;
3088 my $self = SVN::Delta::Editor->new;
3089 bless $self, $class;
3090 $self->{c} = $git_svn->{last_commit} if exists $git_svn->{last_commit};
3091 $self->{empty} = {};
3092 $self->{dir_prop} = {};
3093 $self->{file_prop} = {};
3094 $self->{absent_dir} = {};
3095 $self->{absent_file} = {};
3096 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3097 $self;
3100 sub set_path_strip {
3101 my ($self, $path) = @_;
3102 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3105 sub open_root {
3106 { path => '' };
3109 sub open_directory {
3110 my ($self, $path, $pb, $rev) = @_;
3111 { path => $path };
3114 sub git_path {
3115 my ($self, $path) = @_;
3116 if ($self->{path_strip}) {
3117 $path =~ s!$self->{path_strip}!! or
3118 die "Failed to strip path '$path' ($self->{path_strip})\n";
3120 $path;
3123 sub delete_entry {
3124 my ($self, $path, $rev, $pb) = @_;
3126 my $gpath = $self->git_path($path);
3127 return undef if ($gpath eq '');
3129 # remove entire directories.
3130 if (command('ls-tree', $self->{c}, '--', $gpath) =~ /^040000 tree/) {
3131 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3132 -r --name-only -z/,
3133 $self->{c}, '--', $gpath);
3134 local $/ = "\0";
3135 while (<$ls>) {
3136 chomp;
3137 $self->{gii}->remove($_);
3138 print "\tD\t$_\n" unless $::_q;
3140 print "\tD\t$gpath/\n" unless $::_q;
3141 command_close_pipe($ls, $ctx);
3142 $self->{empty}->{$path} = 0
3143 } else {
3144 $self->{gii}->remove($gpath);
3145 print "\tD\t$gpath\n" unless $::_q;
3147 undef;
3150 sub open_file {
3151 my ($self, $path, $pb, $rev) = @_;
3152 my $gpath = $self->git_path($path);
3153 my ($mode, $blob) = (command('ls-tree', $self->{c}, '--', $gpath)
3154 =~ /^(\d{6}) blob ([a-f\d]{40})\t/);
3155 unless (defined $mode && defined $blob) {
3156 die "$path was not found in commit $self->{c} (r$rev)\n";
3158 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3159 pool => SVN::Pool->new, action => 'M' };
3162 sub add_file {
3163 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3164 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3165 delete $self->{empty}->{$dir};
3166 { path => $path, mode_a => 100644, mode_b => 100644,
3167 pool => SVN::Pool->new, action => 'A' };
3170 sub add_directory {
3171 my ($self, $path, $cp_path, $cp_rev) = @_;
3172 my $gpath = $self->git_path($path);
3173 if ($gpath eq '') {
3174 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3175 -r --name-only -z/,
3176 $self->{c});
3177 local $/ = "\0";
3178 while (<$ls>) {
3179 chomp;
3180 $self->{gii}->remove($_);
3181 print "\tD\t$_\n" unless $::_q;
3183 command_close_pipe($ls, $ctx);
3184 $self->{empty}->{$path} = 0;
3186 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3187 delete $self->{empty}->{$dir};
3188 $self->{empty}->{$path} = 1;
3189 { path => $path };
3192 sub change_dir_prop {
3193 my ($self, $db, $prop, $value) = @_;
3194 $self->{dir_prop}->{$db->{path}} ||= {};
3195 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3196 undef;
3199 sub absent_directory {
3200 my ($self, $path, $pb) = @_;
3201 $self->{absent_dir}->{$pb->{path}} ||= [];
3202 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3203 undef;
3206 sub absent_file {
3207 my ($self, $path, $pb) = @_;
3208 $self->{absent_file}->{$pb->{path}} ||= [];
3209 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3210 undef;
3213 sub change_file_prop {
3214 my ($self, $fb, $prop, $value) = @_;
3215 if ($prop eq 'svn:executable') {
3216 if ($fb->{mode_b} != 120000) {
3217 $fb->{mode_b} = defined $value ? 100755 : 100644;
3219 } elsif ($prop eq 'svn:special') {
3220 $fb->{mode_b} = defined $value ? 120000 : 100644;
3221 } else {
3222 $self->{file_prop}->{$fb->{path}} ||= {};
3223 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3225 undef;
3228 sub apply_textdelta {
3229 my ($self, $fb, $exp) = @_;
3230 my $fh = IO::File->new_tmpfile;
3231 $fh->autoflush(1);
3232 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3233 # (but $base does not,) so dup() it for reading in close_file
3234 open my $dup, '<&', $fh or croak $!;
3235 my $base = IO::File->new_tmpfile;
3236 $base->autoflush(1);
3237 if ($fb->{blob}) {
3238 print $base 'link ' if ($fb->{mode_a} == 120000);
3239 my $size = $::_repository->cat_blob($fb->{blob}, $base);
3240 die "Failed to read object $fb->{blob}" if ($size < 0);
3242 if (defined $exp) {
3243 seek $base, 0, 0 or croak $!;
3244 my $got = ::md5sum($base);
3245 die "Checksum mismatch: $fb->{path} $fb->{blob}\n",
3246 "expected: $exp\n",
3247 " got: $got\n" if ($got ne $exp);
3250 seek $base, 0, 0 or croak $!;
3251 $fb->{fh} = $dup;
3252 $fb->{base} = $base;
3253 [ SVN::TxDelta::apply($base, $fh, undef, $fb->{path}, $fb->{pool}) ];
3256 sub close_file {
3257 my ($self, $fb, $exp) = @_;
3258 my $hash;
3259 my $path = $self->git_path($fb->{path});
3260 if (my $fh = $fb->{fh}) {
3261 if (defined $exp) {
3262 seek($fh, 0, 0) or croak $!;
3263 my $got = ::md5sum($fh);
3264 if ($got ne $exp) {
3265 die "Checksum mismatch: $path\n",
3266 "expected: $exp\n got: $got\n";
3269 sysseek($fh, 0, 0) or croak $!;
3270 if ($fb->{mode_b} == 120000) {
3271 eval {
3272 sysread($fh, my $buf, 5) == 5 or croak $!;
3273 $buf eq 'link ' or die "$path has mode 120000",
3274 " but is not a link";
3276 if ($@) {
3277 warn "$@\n";
3278 sysseek($fh, 0, 0) or croak $!;
3282 my ($tmp_fh, $tmp_filename) = File::Temp::tempfile(UNLINK => 1);
3283 my $result;
3284 while ($result = sysread($fh, my $string, 1024)) {
3285 my $wrote = syswrite($tmp_fh, $string, $result);
3286 defined($wrote) && $wrote == $result
3287 or croak("write $tmp_filename: $!\n");
3289 defined $result or croak $!;
3290 close $tmp_fh or croak $!;
3292 close $fh or croak $!;
3294 $hash = $::_repository->hash_and_insert_object($tmp_filename);
3295 unlink($tmp_filename);
3296 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3297 close $fb->{base} or croak $!;
3298 } else {
3299 $hash = $fb->{blob} or die "no blob information\n";
3301 $fb->{pool}->clear;
3302 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3303 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3304 undef;
3307 sub abort_edit {
3308 my $self = shift;
3309 $self->{nr} = $self->{gii}->{nr};
3310 delete $self->{gii};
3311 $self->SUPER::abort_edit(@_);
3314 sub close_edit {
3315 my $self = shift;
3316 $self->{git_commit_ok} = 1;
3317 $self->{nr} = $self->{gii}->{nr};
3318 delete $self->{gii};
3319 $self->SUPER::close_edit(@_);
3322 package SVN::Git::Editor;
3323 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3324 use strict;
3325 use warnings;
3326 use Carp qw/croak/;
3327 use IO::File;
3329 sub new {
3330 my ($class, $opts) = @_;
3331 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3332 die "$_ required!\n" unless (defined $opts->{$_});
3335 my $pool = SVN::Pool->new;
3336 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3337 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3338 $opts->{r}, $mods);
3340 # $opts->{ra} functions should not be used after this:
3341 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3342 $opts->{editor_cb}, $pool);
3343 my $self = SVN::Delta::Editor->new(@ce, $pool);
3344 bless $self, $class;
3345 foreach (qw/svn_path r tree_a tree_b/) {
3346 $self->{$_} = $opts->{$_};
3348 $self->{url} = $opts->{ra}->{url};
3349 $self->{mods} = $mods;
3350 $self->{types} = $types;
3351 $self->{pool} = $pool;
3352 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3353 $self->{rm} = { };
3354 $self->{path_prefix} = length $self->{svn_path} ?
3355 "$self->{svn_path}/" : '';
3356 $self->{config} = $opts->{config};
3357 return $self;
3360 sub generate_diff {
3361 my ($tree_a, $tree_b) = @_;
3362 my @diff_tree = qw(diff-tree -z -r);
3363 if ($_cp_similarity) {
3364 push @diff_tree, "-C$_cp_similarity";
3365 } else {
3366 push @diff_tree, '-C';
3368 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3369 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3370 push @diff_tree, $tree_a, $tree_b;
3371 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3372 local $/ = "\0";
3373 my $state = 'meta';
3374 my @mods;
3375 while (<$diff_fh>) {
3376 chomp $_; # this gets rid of the trailing "\0"
3377 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3378 $::sha1\s($::sha1)\s
3379 ([MTCRAD])\d*$/xo) {
3380 push @mods, { mode_a => $1, mode_b => $2,
3381 sha1_b => $3, chg => $4 };
3382 if ($4 =~ /^(?:C|R)$/) {
3383 $state = 'file_a';
3384 } else {
3385 $state = 'file_b';
3387 } elsif ($state eq 'file_a') {
3388 my $x = $mods[$#mods] or croak "Empty array\n";
3389 if ($x->{chg} !~ /^(?:C|R)$/) {
3390 croak "Error parsing $_, $x->{chg}\n";
3392 $x->{file_a} = $_;
3393 $state = 'file_b';
3394 } elsif ($state eq 'file_b') {
3395 my $x = $mods[$#mods] or croak "Empty array\n";
3396 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3397 croak "Error parsing $_, $x->{chg}\n";
3399 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3400 croak "Error parsing $_, $x->{chg}\n";
3402 $x->{file_b} = $_;
3403 $state = 'meta';
3404 } else {
3405 croak "Error parsing $_\n";
3408 command_close_pipe($diff_fh, $ctx);
3409 \@mods;
3412 sub check_diff_paths {
3413 my ($ra, $pfx, $rev, $mods) = @_;
3414 my %types;
3415 $pfx .= '/' if length $pfx;
3417 sub type_diff_paths {
3418 my ($ra, $types, $path, $rev) = @_;
3419 my @p = split m#/+#, $path;
3420 my $c = shift @p;
3421 unless (defined $types->{$c}) {
3422 $types->{$c} = $ra->check_path($c, $rev);
3424 while (@p) {
3425 $c .= '/' . shift @p;
3426 next if defined $types->{$c};
3427 $types->{$c} = $ra->check_path($c, $rev);
3431 foreach my $m (@$mods) {
3432 foreach my $f (qw/file_a file_b/) {
3433 next unless defined $m->{$f};
3434 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3435 if (length $pfx.$dir && ! defined $types{$dir}) {
3436 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3440 \%types;
3443 sub split_path {
3444 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3447 sub repo_path {
3448 my ($self, $path) = @_;
3449 $self->{path_prefix}.(defined $path ? $path : '');
3452 sub url_path {
3453 my ($self, $path) = @_;
3454 if ($self->{url} =~ m#^https?://#) {
3455 $path =~ s/([^a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3457 $self->{url} . '/' . $self->repo_path($path);
3460 sub rmdirs {
3461 my ($self) = @_;
3462 my $rm = $self->{rm};
3463 delete $rm->{''}; # we never delete the url we're tracking
3464 return unless %$rm;
3466 foreach (keys %$rm) {
3467 my @d = split m#/#, $_;
3468 my $c = shift @d;
3469 $rm->{$c} = 1;
3470 while (@d) {
3471 $c .= '/' . shift @d;
3472 $rm->{$c} = 1;
3475 delete $rm->{$self->{svn_path}};
3476 delete $rm->{''}; # we never delete the url we're tracking
3477 return unless %$rm;
3479 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3480 $self->{tree_b});
3481 local $/ = "\0";
3482 while (<$fh>) {
3483 chomp;
3484 my @dn = split m#/#, $_;
3485 while (pop @dn) {
3486 delete $rm->{join '/', @dn};
3488 unless (%$rm) {
3489 close $fh;
3490 return;
3493 command_close_pipe($fh, $ctx);
3495 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3496 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3497 $self->close_directory($bat->{$d}, $p);
3498 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3499 print "\tD+\t$d/\n" unless $::_q;
3500 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3501 delete $bat->{$d};
3505 sub open_or_add_dir {
3506 my ($self, $full_path, $baton) = @_;
3507 my $t = $self->{types}->{$full_path};
3508 if (!defined $t) {
3509 die "$full_path not known in r$self->{r} or we have a bug!\n";
3512 no warnings 'once';
3513 # SVN::Node::none and SVN::Node::file are used only once,
3514 # so we're shutting up Perl's warnings about them.
3515 if ($t == $SVN::Node::none) {
3516 return $self->add_directory($full_path, $baton,
3517 undef, -1, $self->{pool});
3518 } elsif ($t == $SVN::Node::dir) {
3519 return $self->open_directory($full_path, $baton,
3520 $self->{r}, $self->{pool});
3521 } # no warnings 'once'
3522 print STDERR "$full_path already exists in repository at ",
3523 "r$self->{r} and it is not a directory (",
3524 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3525 } # no warnings 'once'
3526 exit 1;
3529 sub ensure_path {
3530 my ($self, $path) = @_;
3531 my $bat = $self->{bat};
3532 my $repo_path = $self->repo_path($path);
3533 return $bat->{''} unless (length $repo_path);
3534 my @p = split m#/+#, $repo_path;
3535 my $c = shift @p;
3536 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3537 while (@p) {
3538 my $c0 = $c;
3539 $c .= '/' . shift @p;
3540 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3542 return $bat->{$c};
3545 # Subroutine to convert a globbing pattern to a regular expression.
3546 # From perl cookbook.
3547 sub glob2pat {
3548 my $globstr = shift;
3549 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3550 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3551 return '^' . $globstr . '$';
3554 sub check_autoprop {
3555 my ($self, $pattern, $properties, $file, $fbat) = @_;
3556 # Convert the globbing pattern to a regular expression.
3557 my $regex = glob2pat($pattern);
3558 # Check if the pattern matches the file name.
3559 if($file =~ m/($regex)/) {
3560 # Parse the list of properties to set.
3561 my @props = split(/;/, $properties);
3562 foreach my $prop (@props) {
3563 # Parse 'name=value' syntax and set the property.
3564 if ($prop =~ /([^=]+)=(.*)/) {
3565 my ($n,$v) = ($1,$2);
3566 for ($n, $v) {
3567 s/^\s+//; s/\s+$//;
3569 $self->change_file_prop($fbat, $n, $v);
3575 sub apply_autoprops {
3576 my ($self, $file, $fbat) = @_;
3577 my $conf_t = ${$self->{config}}{'config'};
3578 no warnings 'once';
3579 # Check [miscellany]/enable-auto-props in svn configuration.
3580 if (SVN::_Core::svn_config_get_bool(
3581 $conf_t,
3582 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
3583 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
3584 0)) {
3585 # Auto-props are enabled. Enumerate them to look for matches.
3586 my $callback = sub {
3587 $self->check_autoprop($_[0], $_[1], $file, $fbat);
3589 SVN::_Core::svn_config_enumerate(
3590 $conf_t,
3591 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
3592 $callback);
3596 sub A {
3597 my ($self, $m) = @_;
3598 my ($dir, $file) = split_path($m->{file_b});
3599 my $pbat = $self->ensure_path($dir);
3600 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3601 undef, -1);
3602 print "\tA\t$m->{file_b}\n" unless $::_q;
3603 $self->apply_autoprops($file, $fbat);
3604 $self->chg_file($fbat, $m);
3605 $self->close_file($fbat,undef,$self->{pool});
3608 sub C {
3609 my ($self, $m) = @_;
3610 my ($dir, $file) = split_path($m->{file_b});
3611 my $pbat = $self->ensure_path($dir);
3612 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3613 $self->url_path($m->{file_a}), $self->{r});
3614 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3615 $self->chg_file($fbat, $m);
3616 $self->close_file($fbat,undef,$self->{pool});
3619 sub delete_entry {
3620 my ($self, $path, $pbat) = @_;
3621 my $rpath = $self->repo_path($path);
3622 my ($dir, $file) = split_path($rpath);
3623 $self->{rm}->{$dir} = 1;
3624 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
3627 sub R {
3628 my ($self, $m) = @_;
3629 my ($dir, $file) = split_path($m->{file_b});
3630 my $pbat = $self->ensure_path($dir);
3631 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
3632 $self->url_path($m->{file_a}), $self->{r});
3633 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
3634 $self->chg_file($fbat, $m);
3635 $self->close_file($fbat,undef,$self->{pool});
3637 ($dir, $file) = split_path($m->{file_a});
3638 $pbat = $self->ensure_path($dir);
3639 $self->delete_entry($m->{file_a}, $pbat);
3642 sub M {
3643 my ($self, $m) = @_;
3644 my ($dir, $file) = split_path($m->{file_b});
3645 my $pbat = $self->ensure_path($dir);
3646 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
3647 $pbat,$self->{r},$self->{pool});
3648 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
3649 $self->chg_file($fbat, $m);
3650 $self->close_file($fbat,undef,$self->{pool});
3653 sub T { shift->M(@_) }
3655 sub change_file_prop {
3656 my ($self, $fbat, $pname, $pval) = @_;
3657 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
3660 sub chg_file {
3661 my ($self, $fbat, $m) = @_;
3662 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
3663 $self->change_file_prop($fbat,'svn:executable','*');
3664 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
3665 $self->change_file_prop($fbat,'svn:executable',undef);
3667 my $fh = IO::File->new_tmpfile or croak $!;
3668 if ($m->{mode_b} =~ /^120/) {
3669 print $fh 'link ' or croak $!;
3670 $self->change_file_prop($fbat,'svn:special','*');
3671 } elsif ($m->{mode_a} =~ /^120/ && $m->{mode_b} !~ /^120/) {
3672 $self->change_file_prop($fbat,'svn:special',undef);
3674 my $size = $::_repository->cat_blob($m->{sha1_b}, $fh);
3675 croak "Failed to read object $m->{sha1_b}" if ($size < 0);
3676 $fh->flush == 0 or croak $!;
3677 seek $fh, 0, 0 or croak $!;
3679 my $exp = ::md5sum($fh);
3680 seek $fh, 0, 0 or croak $!;
3682 my $pool = SVN::Pool->new;
3683 my $atd = $self->apply_textdelta($fbat, undef, $pool);
3684 my $got = SVN::TxDelta::send_stream($fh, @$atd, $pool);
3685 die "Checksum mismatch\nexpected: $exp\ngot: $got\n" if ($got ne $exp);
3686 $pool->clear;
3688 close $fh or croak $!;
3691 sub D {
3692 my ($self, $m) = @_;
3693 my ($dir, $file) = split_path($m->{file_b});
3694 my $pbat = $self->ensure_path($dir);
3695 print "\tD\t$m->{file_b}\n" unless $::_q;
3696 $self->delete_entry($m->{file_b}, $pbat);
3699 sub close_edit {
3700 my ($self) = @_;
3701 my ($p,$bat) = ($self->{pool}, $self->{bat});
3702 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
3703 next if $_ eq '';
3704 $self->close_directory($bat->{$_}, $p);
3706 $self->close_directory($bat->{''}, $p);
3707 $self->SUPER::close_edit($p);
3708 $p->clear;
3711 sub abort_edit {
3712 my ($self) = @_;
3713 $self->SUPER::abort_edit($self->{pool});
3716 sub DESTROY {
3717 my $self = shift;
3718 $self->SUPER::DESTROY(@_);
3719 $self->{pool}->clear;
3722 # this drives the editor
3723 sub apply_diff {
3724 my ($self) = @_;
3725 my $mods = $self->{mods};
3726 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
3727 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
3728 my $f = $m->{chg};
3729 if (defined $o{$f}) {
3730 $self->$f($m);
3731 } else {
3732 fatal("Invalid change type: $f");
3735 $self->rmdirs if $_rmdir;
3736 if (@$mods == 0) {
3737 $self->abort_edit;
3738 } else {
3739 $self->close_edit;
3741 return scalar @$mods;
3744 package Git::SVN::Ra;
3745 use vars qw/@ISA $config_dir $_log_window_size/;
3746 use strict;
3747 use warnings;
3748 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
3750 BEGIN {
3751 # enforce temporary pool usage for some simple functions
3752 no strict 'refs';
3753 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root/) {
3754 my $SUPER = "SUPER::$f";
3755 *$f = sub {
3756 my $self = shift;
3757 my $pool = SVN::Pool->new;
3758 my @ret = $self->$SUPER(@_,$pool);
3759 $pool->clear;
3760 wantarray ? @ret : $ret[0];
3765 sub _auth_providers () {
3767 SVN::Client::get_simple_provider(),
3768 SVN::Client::get_ssl_server_trust_file_provider(),
3769 SVN::Client::get_simple_prompt_provider(
3770 \&Git::SVN::Prompt::simple, 2),
3771 SVN::Client::get_ssl_client_cert_file_provider(),
3772 SVN::Client::get_ssl_client_cert_prompt_provider(
3773 \&Git::SVN::Prompt::ssl_client_cert, 2),
3774 SVN::Client::get_ssl_client_cert_pw_file_provider(),
3775 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
3776 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
3777 SVN::Client::get_username_provider(),
3778 SVN::Client::get_ssl_server_trust_prompt_provider(
3779 \&Git::SVN::Prompt::ssl_server_trust),
3780 SVN::Client::get_username_prompt_provider(
3781 \&Git::SVN::Prompt::username, 2)
3785 sub escape_uri_only {
3786 my ($uri) = @_;
3787 my @tmp;
3788 foreach (split m{/}, $uri) {
3789 s/([^\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
3790 push @tmp, $_;
3792 join('/', @tmp);
3795 sub escape_url {
3796 my ($url) = @_;
3797 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
3798 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
3799 $url = "$scheme://$domain$uri";
3801 $url;
3804 sub new {
3805 my ($class, $url) = @_;
3806 $url =~ s!/+$!!;
3807 return $RA if ($RA && $RA->{url} eq $url);
3809 SVN::_Core::svn_config_ensure($config_dir, undef);
3810 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
3811 my $config = SVN::Core::config_get_config($config_dir);
3812 $RA = undef;
3813 my $dont_store_passwords = 1;
3814 my $conf_t = ${$config}{'config'};
3816 no warnings 'once';
3817 # The usage of $SVN::_Core::SVN_CONFIG_* variables
3818 # produces warnings that variables are used only once.
3819 # I had not found the better way to shut them up, so
3820 # the warnings of type 'once' are disabled in this block.
3821 if (SVN::_Core::svn_config_get_bool($conf_t,
3822 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3823 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
3824 1) == 0) {
3825 SVN::_Core::svn_auth_set_parameter($baton,
3826 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
3827 bless (\$dont_store_passwords, "_p_void"));
3829 if (SVN::_Core::svn_config_get_bool($conf_t,
3830 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
3831 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
3832 1) == 0) {
3833 $Git::SVN::Prompt::_no_auth_cache = 1;
3835 } # no warnings 'once'
3836 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
3837 config => $config,
3838 pool => SVN::Pool->new,
3839 auth_provider_callbacks => $callbacks);
3840 $self->{url} = $url;
3841 $self->{svn_path} = $url;
3842 $self->{repos_root} = $self->get_repos_root;
3843 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
3844 $self->{cache} = { check_path => { r => 0, data => {} },
3845 get_dir => { r => 0, data => {} } };
3846 $RA = bless $self, $class;
3849 sub check_path {
3850 my ($self, $path, $r) = @_;
3851 my $cache = $self->{cache}->{check_path};
3852 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
3853 return $cache->{data}->{$path};
3855 my $pool = SVN::Pool->new;
3856 my $t = $self->SUPER::check_path($path, $r, $pool);
3857 $pool->clear;
3858 if ($r != $cache->{r}) {
3859 %{$cache->{data}} = ();
3860 $cache->{r} = $r;
3862 $cache->{data}->{$path} = $t;
3865 sub get_dir {
3866 my ($self, $dir, $r) = @_;
3867 my $cache = $self->{cache}->{get_dir};
3868 if ($r == $cache->{r}) {
3869 if (my $x = $cache->{data}->{$dir}) {
3870 return wantarray ? @$x : $x->[0];
3873 my $pool = SVN::Pool->new;
3874 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
3875 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
3876 $pool->clear;
3877 if ($r != $cache->{r}) {
3878 %{$cache->{data}} = ();
3879 $cache->{r} = $r;
3881 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
3882 wantarray ? (\%dirents, $r, $props) : \%dirents;
3885 sub DESTROY {
3886 # do not call the real DESTROY since we store ourselves in $RA
3889 sub get_log {
3890 my ($self, @args) = @_;
3891 my $pool = SVN::Pool->new;
3892 splice(@args, 3, 1) if ($SVN::Core::VERSION le '1.2.0');
3893 my $ret = $self->SUPER::get_log(@args, $pool);
3894 $pool->clear;
3895 $ret;
3898 sub trees_match {
3899 my ($self, $url1, $rev1, $url2, $rev2) = @_;
3900 my $ctx = SVN::Client->new(auth => _auth_providers);
3901 my $out = IO::File->new_tmpfile;
3903 # older SVN (1.1.x) doesn't take $pool as the last parameter for
3904 # $ctx->diff(), so we'll create a default one
3905 my $pool = SVN::Pool->new_default_sub;
3907 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
3908 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
3909 $out->flush;
3910 my $ret = (($out->stat)[7] == 0);
3911 close $out or croak $!;
3913 $ret;
3916 sub get_commit_editor {
3917 my ($self, $log, $cb, $pool) = @_;
3918 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
3919 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
3922 sub gs_do_update {
3923 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
3924 my $new = ($rev_a == $rev_b);
3925 my $path = $gs->{path};
3927 if ($new && -e $gs->{index}) {
3928 unlink $gs->{index} or die
3929 "Couldn't unlink index: $gs->{index}: $!\n";
3931 my $pool = SVN::Pool->new;
3932 $editor->set_path_strip($path);
3933 my (@pc) = split m#/#, $path;
3934 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
3935 1, $editor, $pool);
3936 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3938 # Since we can't rely on svn_ra_reparent being available, we'll
3939 # just have to do some magic with set_path to make it so
3940 # we only want a partial path.
3941 my $sp = '';
3942 my $final = join('/', @pc);
3943 while (@pc) {
3944 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
3945 $sp .= '/' if length $sp;
3946 $sp .= shift @pc;
3948 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
3950 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
3952 $reporter->finish_report($pool);
3953 $pool->clear;
3954 $editor->{git_commit_ok};
3957 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
3958 # svn_ra_reparent didn't work before 1.4)
3959 sub gs_do_switch {
3960 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
3961 my $path = $gs->{path};
3962 my $pool = SVN::Pool->new;
3964 my $full_url = $self->{url};
3965 my $old_url = $full_url;
3966 $full_url .= '/' . escape_uri_only($path) if length $path;
3967 my ($ra, $reparented);
3968 if ($old_url ne $full_url) {
3969 if ($old_url !~ m#^svn(\+ssh)?://#) {
3970 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url,
3971 $pool);
3972 $self->{url} = $full_url;
3973 $reparented = 1;
3974 } else {
3975 $_[0] = undef;
3976 $self = undef;
3977 $RA = undef;
3978 $ra = Git::SVN::Ra->new($full_url);
3979 $ra_invalid = 1;
3982 $ra ||= $self;
3983 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
3984 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
3985 $reporter->set_path('', $rev_a, 0, @lock, $pool);
3986 $reporter->finish_report($pool);
3988 if ($reparented) {
3989 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
3990 $self->{url} = $old_url;
3993 $pool->clear;
3994 $editor->{git_commit_ok};
3997 sub longest_common_path {
3998 my ($gsv, $globs) = @_;
3999 my %common;
4000 my $common_max = scalar @$gsv;
4002 foreach my $gs (@$gsv) {
4003 my @tmp = split m#/#, $gs->{path};
4004 my $p = '';
4005 foreach (@tmp) {
4006 $p .= length($p) ? "/$_" : $_;
4007 $common{$p} ||= 0;
4008 $common{$p}++;
4011 $globs ||= [];
4012 $common_max += scalar @$globs;
4013 foreach my $glob (@$globs) {
4014 my @tmp = split m#/#, $glob->{path}->{left};
4015 my $p = '';
4016 foreach (@tmp) {
4017 $p .= length($p) ? "/$_" : $_;
4018 $common{$p} ||= 0;
4019 $common{$p}++;
4023 my $longest_path = '';
4024 foreach (sort {length $b <=> length $a} keys %common) {
4025 if ($common{$_} == $common_max) {
4026 $longest_path = $_;
4027 last;
4030 $longest_path;
4033 sub gs_fetch_loop_common {
4034 my ($self, $base, $head, $gsv, $globs) = @_;
4035 return if ($base > $head);
4036 my $inc = $_log_window_size;
4037 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4038 my $longest_path = longest_common_path($gsv, $globs);
4039 my $ra_url = $self->{url};
4040 while (1) {
4041 my %revs;
4042 my $err;
4043 my $err_handler = $SVN::Error::handler;
4044 $SVN::Error::handler = sub {
4045 ($err) = @_;
4046 skip_unknown_revs($err);
4048 sub _cb {
4049 my ($paths, $r, $author, $date, $log) = @_;
4050 [ dup_changed_paths($paths),
4051 { author => $author, date => $date, log => $log } ];
4053 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4054 sub { $revs{$_[1]} = _cb(@_) });
4055 if ($err && $max >= $head) {
4056 print STDERR "Path '$longest_path' ",
4057 "was probably deleted:\n",
4058 $err->expanded_message,
4059 "\nWill attempt to follow ",
4060 "revisions r$min .. r$max ",
4061 "committed before the deletion\n";
4062 my $hi = $max;
4063 while (--$hi >= $min) {
4064 my $ok;
4065 $self->get_log([$longest_path], $min, $hi,
4066 0, 1, 1, sub {
4067 $ok ||= $_[1];
4068 $revs{$_[1]} = _cb(@_) });
4069 if ($ok) {
4070 print STDERR "r$min .. r$ok OK\n";
4071 last;
4075 $SVN::Error::handler = $err_handler;
4077 my %exists = map { $_->{path} => $_ } @$gsv;
4078 foreach my $r (sort {$a <=> $b} keys %revs) {
4079 my ($paths, $logged) = @{$revs{$r}};
4081 foreach my $gs ($self->match_globs(\%exists, $paths,
4082 $globs, $r)) {
4083 if ($gs->rev_map_max >= $r) {
4084 next;
4086 next unless $gs->match_paths($paths, $r);
4087 $gs->{logged_rev_props} = $logged;
4088 if (my $last_commit = $gs->last_commit) {
4089 $gs->assert_index_clean($last_commit);
4091 my $log_entry = $gs->do_fetch($paths, $r);
4092 if ($log_entry) {
4093 $gs->do_git_commit($log_entry);
4095 $INDEX_FILES{$gs->{index}} = 1;
4097 foreach my $g (@$globs) {
4098 my $k = "svn-remote.$g->{remote}." .
4099 "$g->{t}-maxRev";
4100 Git::SVN::tmp_config($k, $r);
4102 if ($ra_invalid) {
4103 $_[0] = undef;
4104 $self = undef;
4105 $RA = undef;
4106 $self = Git::SVN::Ra->new($ra_url);
4107 $ra_invalid = undef;
4110 # pre-fill the .rev_db since it'll eventually get filled in
4111 # with '0' x40 if something new gets committed
4112 foreach my $gs (@$gsv) {
4113 next if $gs->rev_map_max >= $max;
4114 next if defined $gs->rev_map_get($max);
4115 $gs->rev_map_set($max, 0 x40);
4117 foreach my $g (@$globs) {
4118 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4119 Git::SVN::tmp_config($k, $max);
4121 last if $max >= $head;
4122 $min = $max + 1;
4123 $max += $inc;
4124 $max = $head if ($max > $head);
4126 Git::SVN::gc();
4129 sub get_dir_globbed {
4130 my ($self, $left, $depth, $r) = @_;
4132 my @x = eval { $self->get_dir($left, $r) };
4133 return unless scalar @x == 3;
4134 my $dirents = $x[0];
4135 my @finalents;
4136 foreach my $de (keys %$dirents) {
4137 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4138 if ($depth > 1) {
4139 my @args = ("$left/$de", $depth - 1, $r);
4140 foreach my $dir ($self->get_dir_globbed(@args)) {
4141 push @finalents, "$de/$dir";
4143 } else {
4144 push @finalents, $de;
4147 @finalents;
4150 sub match_globs {
4151 my ($self, $exists, $paths, $globs, $r) = @_;
4153 sub get_dir_check {
4154 my ($self, $exists, $g, $r) = @_;
4156 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4157 $g->{path}->{depth},
4158 $r);
4160 foreach my $de (@dirs) {
4161 my $p = $g->{path}->full_path($de);
4162 next if $exists->{$p};
4163 next if (length $g->{path}->{right} &&
4164 ($self->check_path($p, $r) !=
4165 $SVN::Node::dir));
4166 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4167 $g->{ref}->full_path($de), 1);
4170 foreach my $g (@$globs) {
4171 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4172 if ($path->{action} =~ /^[AR]$/) {
4173 get_dir_check($self, $exists, $g, $r);
4176 foreach (keys %$paths) {
4177 if (/$g->{path}->{left_regex}/ &&
4178 !/$g->{path}->{regex}/) {
4179 next if $paths->{$_}->{action} !~ /^[AR]$/;
4180 get_dir_check($self, $exists, $g, $r);
4182 next unless /$g->{path}->{regex}/;
4183 my $p = $1;
4184 my $pathname = $g->{path}->full_path($p);
4185 next if $exists->{$pathname};
4186 next if ($self->check_path($pathname, $r) !=
4187 $SVN::Node::dir);
4188 $exists->{$pathname} = Git::SVN->init(
4189 $self->{url}, $pathname, undef,
4190 $g->{ref}->full_path($p), 1);
4192 my $c = '';
4193 foreach (split m#/#, $g->{path}->{left}) {
4194 $c .= "/$_";
4195 next unless ($paths->{$c} &&
4196 ($paths->{$c}->{action} =~ /^[AR]$/));
4197 get_dir_check($self, $exists, $g, $r);
4200 values %$exists;
4203 sub minimize_url {
4204 my ($self) = @_;
4205 return $self->{url} if ($self->{url} eq $self->{repos_root});
4206 my $url = $self->{repos_root};
4207 my @components = split(m!/!, $self->{svn_path});
4208 my $c = '';
4209 do {
4210 $url .= "/$c" if length $c;
4211 eval { (ref $self)->new($url)->get_latest_revnum };
4212 } while ($@ && ($c = shift @components));
4213 $url;
4216 sub can_do_switch {
4217 my $self = shift;
4218 unless (defined $can_do_switch) {
4219 my $pool = SVN::Pool->new;
4220 my $rep = eval {
4221 $self->do_switch(1, '', 0, $self->{url},
4222 SVN::Delta::Editor->new, $pool);
4224 if ($@) {
4225 $can_do_switch = 0;
4226 } else {
4227 $rep->abort_report($pool);
4228 $can_do_switch = 1;
4230 $pool->clear;
4232 $can_do_switch;
4235 sub skip_unknown_revs {
4236 my ($err) = @_;
4237 my $errno = $err->apr_err();
4238 # Maybe the branch we're tracking didn't
4239 # exist when the repo started, so it's
4240 # not an error if it doesn't, just continue
4242 # Wonderfully consistent library, eh?
4243 # 160013 - svn:// and file://
4244 # 175002 - http(s)://
4245 # 175007 - http(s):// (this repo required authorization, too...)
4246 # More codes may be discovered later...
4247 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4248 my $err_key = $err->expanded_message;
4249 # revision numbers change every time, filter them out
4250 $err_key =~ s/\d+/\0/g;
4251 $err_key = "$errno\0$err_key";
4252 unless ($ignored_err{$err_key}) {
4253 warn "W: Ignoring error from SVN, path probably ",
4254 "does not exist: ($errno): ",
4255 $err->expanded_message,"\n";
4256 warn "W: Do not be alarmed at the above message ",
4257 "git-svn is just searching aggressively for ",
4258 "old history.\n",
4259 "This may take a while on large repositories\n";
4260 $ignored_err{$err_key} = 1;
4262 return;
4264 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4267 # svn_log_changed_path_t objects passed to get_log are likely to be
4268 # overwritten even if only the refs are copied to an external variable,
4269 # so we should dup the structures in their entirety. Using an externally
4270 # passed pool (instead of our temporary and quickly cleared pool in
4271 # Git::SVN::Ra) does not help matters at all...
4272 sub dup_changed_paths {
4273 my ($paths) = @_;
4274 return undef unless $paths;
4275 my %ret;
4276 foreach my $p (keys %$paths) {
4277 my $i = $paths->{$p};
4278 my %s = map { $_ => $i->$_ }
4279 qw/copyfrom_path copyfrom_rev action/;
4280 $ret{$p} = \%s;
4282 \%ret;
4285 package Git::SVN::Log;
4286 use strict;
4287 use warnings;
4288 use POSIX qw/strftime/;
4289 use constant commit_log_separator => ('-' x 72) . "\n";
4290 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4291 %rusers $show_commit $incremental/;
4292 my $l_fmt;
4294 sub cmt_showable {
4295 my ($c) = @_;
4296 return 1 if defined $c->{r};
4298 # big commit message got truncated by the 16k pretty buffer in rev-list
4299 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4300 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4301 @{$c->{l}} = ();
4302 my @log = command(qw/cat-file commit/, $c->{c});
4304 # shift off the headers
4305 shift @log while ($log[0] ne '');
4306 shift @log;
4308 # TODO: make $c->{l} not have a trailing newline in the future
4309 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4311 (undef, $c->{r}, undef) = ::extract_metadata(
4312 (grep(/^git-svn-id: /, @log))[-1]);
4314 return defined $c->{r};
4317 sub log_use_color {
4318 return $color || Git->repository->get_colorbool('color.diff');
4321 sub git_svn_log_cmd {
4322 my ($r_min, $r_max, @args) = @_;
4323 my $head = 'HEAD';
4324 my (@files, @log_opts);
4325 foreach my $x (@args) {
4326 if ($x eq '--' || @files) {
4327 push @files, $x;
4328 } else {
4329 if (::verify_ref("$x^0")) {
4330 $head = $x;
4331 } else {
4332 push @log_opts, $x;
4337 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4338 $gs ||= Git::SVN->_new;
4339 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4340 $gs->refname);
4341 push @cmd, '-r' unless $non_recursive;
4342 push @cmd, qw/--raw --name-status/ if $verbose;
4343 push @cmd, '--color' if log_use_color();
4344 push @cmd, @log_opts;
4345 if (defined $r_max && $r_max == $r_min) {
4346 push @cmd, '--max-count=1';
4347 if (my $c = $gs->rev_map_get($r_max)) {
4348 push @cmd, $c;
4350 } elsif (defined $r_max) {
4351 if ($r_max < $r_min) {
4352 ($r_min, $r_max) = ($r_max, $r_min);
4354 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4355 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4356 # If there are no commits in the range, both $c_max and $c_min
4357 # will be undefined. If there is at least 1 commit in the
4358 # range, both will be defined.
4359 return () if !defined $c_min || !defined $c_max;
4360 if ($c_min eq $c_max) {
4361 push @cmd, '--max-count=1', $c_min;
4362 } else {
4363 push @cmd, '--boundary', "$c_min..$c_max";
4366 return (@cmd, @files);
4369 # adapted from pager.c
4370 sub config_pager {
4371 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4372 if (!defined $pager) {
4373 $pager = 'less';
4374 } elsif (length $pager == 0 || $pager eq 'cat') {
4375 $pager = undef;
4377 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4380 sub run_pager {
4381 return unless -t *STDOUT && defined $pager;
4382 pipe my $rfd, my $wfd or return;
4383 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4384 if (!$pid) {
4385 open STDOUT, '>&', $wfd or
4386 ::fatal "Can't redirect to stdout: $!";
4387 return;
4389 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4390 $ENV{LESS} ||= 'FRSX';
4391 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4394 sub format_svn_date {
4395 return strftime("%Y-%m-%d %H:%M:%S %z (%a, %d %b %Y)", localtime(shift));
4398 sub parse_git_date {
4399 my ($t, $tz) = @_;
4400 # Date::Parse isn't in the standard Perl distro :(
4401 if ($tz =~ s/^\+//) {
4402 $t += tz_to_s_offset($tz);
4403 } elsif ($tz =~ s/^\-//) {
4404 $t -= tz_to_s_offset($tz);
4406 return $t;
4409 sub set_local_timezone {
4410 if (defined $TZ) {
4411 $ENV{TZ} = $TZ;
4412 } else {
4413 delete $ENV{TZ};
4417 sub tz_to_s_offset {
4418 my ($tz) = @_;
4419 $tz =~ s/(\d\d)$//;
4420 return ($1 * 60) + ($tz * 3600);
4423 sub get_author_info {
4424 my ($dest, $author, $t, $tz) = @_;
4425 $author =~ s/(?:^\s*|\s*$)//g;
4426 $dest->{a_raw} = $author;
4427 my $au;
4428 if ($::_authors) {
4429 $au = $rusers{$author} || undef;
4431 if (!$au) {
4432 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4434 $dest->{t} = $t;
4435 $dest->{tz} = $tz;
4436 $dest->{a} = $au;
4437 $dest->{t_utc} = parse_git_date($t, $tz);
4440 sub process_commit {
4441 my ($c, $r_min, $r_max, $defer) = @_;
4442 if (defined $r_min && defined $r_max) {
4443 if ($r_min == $c->{r} && $r_min == $r_max) {
4444 show_commit($c);
4445 return 0;
4447 return 1 if $r_min == $r_max;
4448 if ($r_min < $r_max) {
4449 # we need to reverse the print order
4450 return 0 if (defined $limit && --$limit < 0);
4451 push @$defer, $c;
4452 return 1;
4454 if ($r_min != $r_max) {
4455 return 1 if ($r_min < $c->{r});
4456 return 1 if ($r_max > $c->{r});
4459 return 0 if (defined $limit && --$limit < 0);
4460 show_commit($c);
4461 return 1;
4464 sub show_commit {
4465 my $c = shift;
4466 if ($oneline) {
4467 my $x = "\n";
4468 if (my $l = $c->{l}) {
4469 while ($l->[0] =~ /^\s*$/) { shift @$l }
4470 $x = $l->[0];
4472 $l_fmt ||= 'A' . length($c->{r});
4473 print 'r',pack($l_fmt, $c->{r}),' | ';
4474 print "$c->{c} | " if $show_commit;
4475 print $x;
4476 } else {
4477 show_commit_normal($c);
4481 sub show_commit_changed_paths {
4482 my ($c) = @_;
4483 return unless $c->{changed};
4484 print "Changed paths:\n", @{$c->{changed}};
4487 sub show_commit_normal {
4488 my ($c) = @_;
4489 print commit_log_separator, "r$c->{r} | ";
4490 print "$c->{c} | " if $show_commit;
4491 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4492 my $nr_line = 0;
4494 if (my $l = $c->{l}) {
4495 while ($l->[$#$l] eq "\n" && $#$l > 0
4496 && $l->[($#$l - 1)] eq "\n") {
4497 pop @$l;
4499 $nr_line = scalar @$l;
4500 if (!$nr_line) {
4501 print "1 line\n\n\n";
4502 } else {
4503 if ($nr_line == 1) {
4504 $nr_line = '1 line';
4505 } else {
4506 $nr_line .= ' lines';
4508 print $nr_line, "\n";
4509 show_commit_changed_paths($c);
4510 print "\n";
4511 print $_ foreach @$l;
4513 } else {
4514 print "1 line\n";
4515 show_commit_changed_paths($c);
4516 print "\n";
4519 foreach my $x (qw/raw stat diff/) {
4520 if ($c->{$x}) {
4521 print "\n";
4522 print $_ foreach @{$c->{$x}}
4527 sub cmd_show_log {
4528 my (@args) = @_;
4529 my ($r_min, $r_max);
4530 my $r_last = -1; # prevent dupes
4531 set_local_timezone();
4532 if (defined $::_revision) {
4533 if ($::_revision =~ /^(\d+):(\d+)$/) {
4534 ($r_min, $r_max) = ($1, $2);
4535 } elsif ($::_revision =~ /^\d+$/) {
4536 $r_min = $r_max = $::_revision;
4537 } else {
4538 ::fatal "-r$::_revision is not supported, use ",
4539 "standard 'git log' arguments instead";
4543 config_pager();
4544 @args = git_svn_log_cmd($r_min, $r_max, @args);
4545 if (!@args) {
4546 print commit_log_separator unless $incremental || $oneline;
4547 return;
4549 my $log = command_output_pipe(@args);
4550 run_pager();
4551 my (@k, $c, $d, $stat);
4552 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
4553 while (<$log>) {
4554 if (/^${esc_color}commit -?($::sha1_short)/o) {
4555 my $cmt = $1;
4556 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
4557 $r_last = $c->{r};
4558 process_commit($c, $r_min, $r_max, \@k) or
4559 goto out;
4561 $d = undef;
4562 $c = { c => $cmt };
4563 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
4564 get_author_info($c, $1, $2, $3);
4565 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
4566 # ignore
4567 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
4568 push @{$c->{raw}}, $_;
4569 } elsif (/^${esc_color}[ACRMDT]\t/) {
4570 # we could add $SVN->{svn_path} here, but that requires
4571 # remote access at the moment (repo_path_split)...
4572 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
4573 push @{$c->{changed}}, $_;
4574 } elsif (/^${esc_color}diff /o) {
4575 $d = 1;
4576 push @{$c->{diff}}, $_;
4577 } elsif ($d) {
4578 push @{$c->{diff}}, $_;
4579 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
4580 $esc_color*[\+\-]*$esc_color$/x) {
4581 $stat = 1;
4582 push @{$c->{stat}}, $_;
4583 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
4584 push @{$c->{stat}}, $_;
4585 $stat = undef;
4586 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
4587 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
4588 } elsif (s/^${esc_color} //o) {
4589 push @{$c->{l}}, $_;
4592 if ($c && defined $c->{r} && $c->{r} != $r_last) {
4593 $r_last = $c->{r};
4594 process_commit($c, $r_min, $r_max, \@k);
4596 if (@k) {
4597 ($r_min, $r_max) = ($r_max, $r_min);
4598 process_commit($_, $r_min, $r_max) foreach reverse @k;
4600 out:
4601 close $log;
4602 print commit_log_separator unless $incremental || $oneline;
4605 sub cmd_blame {
4606 my $path = pop;
4608 config_pager();
4609 run_pager();
4611 my ($fh, $ctx, $rev);
4613 if ($_git_format) {
4614 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
4615 while (my $line = <$fh>) {
4616 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
4617 # Uncommitted edits show up as a rev ID of
4618 # all zeros, which we can't look up with
4619 # cmt_metadata
4620 if ($1 !~ /^0+$/) {
4621 (undef, $rev, undef) =
4622 ::cmt_metadata($1);
4623 $rev = '0' if (!$rev);
4624 } else {
4625 $rev = '0';
4627 $rev = sprintf('%-10s', $rev);
4628 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
4630 print $line;
4632 } else {
4633 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
4634 '--', $path);
4635 my ($sha1);
4636 my %authors;
4637 while (my $line = <$fh>) {
4638 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
4639 $sha1 = $1;
4640 (undef, $rev, undef) = ::cmt_metadata($1);
4641 $rev = '0' if (!$rev);
4643 elsif ($line =~ /^author (.*)/) {
4644 $authors{$rev} = $1;
4645 $authors{$rev} =~ s/\s/_/g;
4647 elsif ($line =~ /^\t(.*)$/) {
4648 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
4652 command_close_pipe($fh, $ctx);
4655 package Git::SVN::Migration;
4656 # these version numbers do NOT correspond to actual version numbers
4657 # of git nor git-svn. They are just relative.
4659 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
4661 # v1 layout: .git/$id/info/url, refs/remotes/$id
4663 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
4665 # v3 layout: .git/svn/$id, refs/remotes/$id
4666 # - info/url may remain for backwards compatibility
4667 # - this is what we migrate up to this layout automatically,
4668 # - this will be used by git svn init on single branches
4669 # v3.1 layout (auto migrated):
4670 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
4671 # for backwards compatibility
4673 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
4674 # - this is only created for newly multi-init-ed
4675 # repositories. Similar in spirit to the
4676 # --use-separate-remotes option in git-clone (now default)
4677 # - we do not automatically migrate to this (following
4678 # the example set by core git)
4680 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
4681 # - newer, more-efficient format that uses 24-bytes per record
4682 # with no filler space.
4683 # - use xxd -c24 < .rev_map.$UUID to view and debug
4684 # - This is a one-way migration, repositories updated to the
4685 # new format will not be able to use old git-svn without
4686 # rebuilding the .rev_db. Rebuilding the rev_db is not
4687 # possible if noMetadata or useSvmProps are set; but should
4688 # be no problem for users that use the (sensible) defaults.
4689 use strict;
4690 use warnings;
4691 use Carp qw/croak/;
4692 use File::Path qw/mkpath/;
4693 use File::Basename qw/dirname basename/;
4694 use vars qw/$_minimize/;
4696 sub migrate_from_v0 {
4697 my $git_dir = $ENV{GIT_DIR};
4698 return undef unless -d $git_dir;
4699 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4700 my $migrated = 0;
4701 while (<$fh>) {
4702 chomp;
4703 my ($id, $orig_ref) = ($_, $_);
4704 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
4705 next unless -f "$git_dir/$id/info/url";
4706 my $new_ref = "refs/remotes/$id";
4707 if (::verify_ref("$new_ref^0")) {
4708 print STDERR "W: $orig_ref is probably an old ",
4709 "branch used by an ancient version of ",
4710 "git-svn.\n",
4711 "However, $new_ref also exists.\n",
4712 "We will not be able ",
4713 "to use this branch until this ",
4714 "ambiguity is resolved.\n";
4715 next;
4717 print STDERR "Migrating from v0 layout...\n" if !$migrated;
4718 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
4719 command_noisy('update-ref', $new_ref, $orig_ref);
4720 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
4721 $migrated++;
4723 command_close_pipe($fh, $ctx);
4724 print STDERR "Done migrating from v0 layout...\n" if $migrated;
4725 $migrated;
4728 sub migrate_from_v1 {
4729 my $git_dir = $ENV{GIT_DIR};
4730 my $migrated = 0;
4731 return $migrated unless -d $git_dir;
4732 my $svn_dir = "$git_dir/svn";
4734 # just in case somebody used 'svn' as their $id at some point...
4735 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
4737 print STDERR "Migrating from a git-svn v1 layout...\n";
4738 mkpath([$svn_dir]);
4739 print STDERR "Data from a previous version of git-svn exists, but\n\t",
4740 "$svn_dir\n\t(required for this version ",
4741 "($::VERSION) of git-svn) does not exist.\n";
4742 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
4743 while (<$fh>) {
4744 my $x = $_;
4745 next unless $x =~ s#^refs/remotes/##;
4746 chomp $x;
4747 next unless -f "$git_dir/$x/info/url";
4748 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
4749 next unless $u;
4750 my $dn = dirname("$git_dir/svn/$x");
4751 mkpath([$dn]) unless -d $dn;
4752 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
4753 mkpath(["$git_dir/svn/svn"]);
4754 print STDERR " - $git_dir/$x/info => ",
4755 "$git_dir/svn/$x/info\n";
4756 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
4757 croak "$!: $x";
4758 # don't worry too much about these, they probably
4759 # don't exist with repos this old (save for index,
4760 # and we can easily regenerate that)
4761 foreach my $f (qw/unhandled.log index .rev_db/) {
4762 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
4764 } else {
4765 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
4766 rename "$git_dir/$x", "$git_dir/svn/$x" or
4767 croak "$!: $x";
4769 $migrated++;
4771 command_close_pipe($fh, $ctx);
4772 print STDERR "Done migrating from a git-svn v1 layout\n";
4773 $migrated;
4776 sub read_old_urls {
4777 my ($l_map, $pfx, $path) = @_;
4778 my @dir;
4779 foreach (<$path/*>) {
4780 if (-r "$_/info/url") {
4781 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
4782 my $ref_id = $pfx . basename $_;
4783 my $url = ::file_to_s("$_/info/url");
4784 $l_map->{$ref_id} = $url;
4785 } elsif (-d $_) {
4786 push @dir, $_;
4789 foreach (@dir) {
4790 my $x = $_;
4791 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
4792 read_old_urls($l_map, $x, $_);
4796 sub migrate_from_v2 {
4797 my @cfg = command(qw/config -l/);
4798 return if grep /^svn-remote\..+\.url=/, @cfg;
4799 my %l_map;
4800 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
4801 my $migrated = 0;
4803 foreach my $ref_id (sort keys %l_map) {
4804 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
4805 if ($@) {
4806 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
4808 $migrated++;
4810 $migrated;
4813 sub minimize_connections {
4814 my $r = Git::SVN::read_all_remotes();
4815 my $new_urls = {};
4816 my $root_repos = {};
4817 foreach my $repo_id (keys %$r) {
4818 my $url = $r->{$repo_id}->{url} or next;
4819 my $fetch = $r->{$repo_id}->{fetch} or next;
4820 my $ra = Git::SVN::Ra->new($url);
4822 # skip existing cases where we already connect to the root
4823 if (($ra->{url} eq $ra->{repos_root}) ||
4824 ($ra->{repos_root} eq $repo_id)) {
4825 $root_repos->{$ra->{url}} = $repo_id;
4826 next;
4829 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
4830 my $root_path = $ra->{url};
4831 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
4832 foreach my $path (keys %$fetch) {
4833 my $ref_id = $fetch->{$path};
4834 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
4836 # make sure we can read when connecting to
4837 # a higher level of a repository
4838 my ($last_rev, undef) = $gs->last_rev_commit;
4839 if (!defined $last_rev) {
4840 $last_rev = eval {
4841 $root_ra->get_latest_revnum;
4843 next if $@;
4845 my $new = $root_path;
4846 $new .= length $path ? "/$path" : '';
4847 eval {
4848 $root_ra->get_log([$new], $last_rev, $last_rev,
4849 0, 0, 1, sub { });
4851 next if $@;
4852 $new_urls->{$ra->{repos_root}}->{$new} =
4853 { ref_id => $ref_id,
4854 old_repo_id => $repo_id,
4855 old_path => $path };
4859 my @emptied;
4860 foreach my $url (keys %$new_urls) {
4861 # see if we can re-use an existing [svn-remote "repo_id"]
4862 # instead of creating a(n ugly) new section:
4863 my $repo_id = $root_repos->{$url} || $url;
4865 my $fetch = $new_urls->{$url};
4866 foreach my $path (keys %$fetch) {
4867 my $x = $fetch->{$path};
4868 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
4869 my $pfx = "svn-remote.$x->{old_repo_id}";
4871 my $old_fetch = quotemeta("$x->{old_path}:".
4872 "refs/remotes/$x->{ref_id}");
4873 command_noisy(qw/config --unset/,
4874 "$pfx.fetch", '^'. $old_fetch . '$');
4875 delete $r->{$x->{old_repo_id}}->
4876 {fetch}->{$x->{old_path}};
4877 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
4878 command_noisy(qw/config --unset/,
4879 "$pfx.url");
4880 push @emptied, $x->{old_repo_id}
4884 if (@emptied) {
4885 my $file = $ENV{GIT_CONFIG} || $ENV{GIT_CONFIG_LOCAL} ||
4886 "$ENV{GIT_DIR}/config";
4887 print STDERR <<EOF;
4888 The following [svn-remote] sections in your config file ($file) are empty
4889 and can be safely removed:
4891 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
4895 sub migration_check {
4896 migrate_from_v0();
4897 migrate_from_v1();
4898 migrate_from_v2();
4899 minimize_connections() if $_minimize;
4902 package Git::IndexInfo;
4903 use strict;
4904 use warnings;
4905 use Git qw/command_input_pipe command_close_pipe/;
4907 sub new {
4908 my ($class) = @_;
4909 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
4910 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
4913 sub remove {
4914 my ($self, $path) = @_;
4915 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
4916 return ++$self->{nr};
4918 undef;
4921 sub update {
4922 my ($self, $mode, $hash, $path) = @_;
4923 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
4924 return ++$self->{nr};
4926 undef;
4929 sub DESTROY {
4930 my ($self) = @_;
4931 command_close_pipe($self->{gui}, $self->{ctx});
4934 package Git::SVN::GlobSpec;
4935 use strict;
4936 use warnings;
4938 sub new {
4939 my ($class, $glob) = @_;
4940 my $re = $glob;
4941 $re =~ s!/+$!!g; # no need for trailing slashes
4942 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
4943 my $temp = $re;
4944 my ($left, $right) = ($1, $3);
4945 $re = $2;
4946 my $depth = $re =~ tr/*/*/;
4947 if ($depth != $temp =~ tr/*/*/) {
4948 die "Only one set of wildcard directories " .
4949 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
4951 if ($depth == 0) {
4952 die "One '*' is needed for glob: '$glob'\n";
4954 $re =~ s!\*!\[^/\]*!g;
4955 $re = quotemeta($left) . "($re)" . quotemeta($right);
4956 if (length $left && !($left =~ s!/+$!!g)) {
4957 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
4959 if (length $right && !($right =~ s!^/+!!g)) {
4960 die "Missing leading '/' on right side of: '$glob' ($right)\n";
4962 my $left_re = qr/^\/\Q$left\E(\/|$)/;
4963 bless { left => $left, right => $right, left_regex => $left_re,
4964 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
4967 sub full_path {
4968 my ($self, $path) = @_;
4969 return (length $self->{left} ? "$self->{left}/" : '') .
4970 $path . (length $self->{right} ? "/$self->{right}" : '');
4973 __END__
4975 Data structures:
4978 $remotes = { # returned by read_all_remotes()
4979 'svn' => {
4980 # svn-remote.svn.url=https://svn.musicpd.org
4981 url => 'https://svn.musicpd.org',
4982 # svn-remote.svn.fetch=mpd/trunk:trunk
4983 fetch => {
4984 'mpd/trunk' => 'trunk',
4986 # svn-remote.svn.tags=mpd/tags/*:tags/*
4987 tags => {
4988 path => {
4989 left => 'mpd/tags',
4990 right => '',
4991 regex => qr!mpd/tags/([^/]+)$!,
4992 glob => 'tags/*',
4994 ref => {
4995 left => 'tags',
4996 right => '',
4997 regex => qr!tags/([^/]+)$!,
4998 glob => 'tags/*',
5004 $log_entry hashref as returned by libsvn_log_entry()
5006 log => 'whitespace-formatted log entry
5007 ', # trailing newline is preserved
5008 revision => '8', # integer
5009 date => '2004-02-24T17:01:44.108345Z', # commit date
5010 author => 'committer name'
5014 # this is generated by generate_diff();
5015 @mods = array of diff-index line hashes, each element represents one line
5016 of diff-index output
5018 diff-index line ($m hash)
5020 mode_a => first column of diff-index output, no leading ':',
5021 mode_b => second column of diff-index output,
5022 sha1_b => sha1sum of the final blob,
5023 chg => change type [MCRADT],
5024 file_a => original file name of a file (iff chg is 'C' or 'R')
5025 file_b => new/current file name of a file (any chg)
5029 # retval of read_url_paths{,_all}();
5030 $l_map = {
5031 # repository root url
5032 'https://svn.musicpd.org' => {
5033 # repository path # GIT_SVN_ID
5034 'mpd/trunk' => 'trunk',
5035 'mpd/tags/0.11.5' => 'tags/0.11.5',
5039 Notes:
5040 I don't trust the each() function on unless I created %hash myself
5041 because the internal iterator may not have started at base.