git-svn: speed up find_rev_before
[git/raj.git] / git-svn.perl
blobf9a672d772e4d586edd18556aa653950b985ec5b
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 $_authors_prog %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 File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, $_tags, $_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
99 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run,
145 'tag|t' => \$_tag } ],
146 tag => [ sub { $_tag = 1; cmd_branch(@_) },
147 'Create a tag in the SVN repository',
148 { 'message|m=s' => \$_message,
149 'dry-run|n' => \$_dry_run } ],
150 'set-tree' => [ \&cmd_set_tree,
151 "Set an SVN repository to a git tree-ish",
152 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
153 'create-ignore' => [ \&cmd_create_ignore,
154 'Create a .gitignore per svn:ignore',
155 { 'revision|r=i' => \$_revision
156 } ],
157 'propget' => [ \&cmd_propget,
158 'Print the value of a property on a file or directory',
159 { 'revision|r=i' => \$_revision } ],
160 'proplist' => [ \&cmd_proplist,
161 'List all properties of a file or directory',
162 { 'revision|r=i' => \$_revision } ],
163 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
164 { 'revision|r=i' => \$_revision
165 } ],
166 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
167 { 'revision|r=i' => \$_revision
168 } ],
169 'multi-fetch' => [ \&cmd_multi_fetch,
170 "Deprecated alias for $0 fetch --all",
171 { 'revision|r=s' => \$_revision, %fc_opts } ],
172 'migrate' => [ sub { },
173 # no-op, we automatically run this anyways,
174 'Migrate configuration/metadata/layout from
175 previous versions of git-svn',
176 { 'minimize' => \$Git::SVN::Migration::_minimize,
177 %remote_opts } ],
178 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
179 { 'limit=i' => \$Git::SVN::Log::limit,
180 'revision|r=s' => \$_revision,
181 'verbose|v' => \$Git::SVN::Log::verbose,
182 'incremental' => \$Git::SVN::Log::incremental,
183 'oneline' => \$Git::SVN::Log::oneline,
184 'show-commit' => \$Git::SVN::Log::show_commit,
185 'non-recursive' => \$Git::SVN::Log::non_recursive,
186 'authors-file|A=s' => \$_authors,
187 'color' => \$Git::SVN::Log::color,
188 'pager=s' => \$Git::SVN::Log::pager
189 } ],
190 'find-rev' => [ \&cmd_find_rev,
191 "Translate between SVN revision numbers and tree-ish",
192 {} ],
193 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
194 { 'merge|m|M' => \$_merge,
195 'verbose|v' => \$_verbose,
196 'strategy|s=s' => \$_strategy,
197 'local|l' => \$_local,
198 'fetch-all|all' => \$_fetch_all,
199 'dry-run|n' => \$_dry_run,
200 %fc_opts } ],
201 'commit-diff' => [ \&cmd_commit_diff,
202 'Commit a diff between two trees',
203 { 'message|m=s' => \$_message,
204 'file|F=s' => \$_file,
205 'revision|r=s' => \$_revision,
206 %cmt_opts } ],
207 'info' => [ \&cmd_info,
208 "Show info about the latest SVN revision
209 on the current branch",
210 { 'url' => \$_url, } ],
211 'blame' => [ \&Git::SVN::Log::cmd_blame,
212 "Show what revision and author last modified each line of a file",
213 { 'git-format' => \$_git_format } ],
216 my $cmd;
217 for (my $i = 0; $i < @ARGV; $i++) {
218 if (defined $cmd{$ARGV[$i]}) {
219 $cmd = $ARGV[$i];
220 splice @ARGV, $i, 1;
221 last;
222 } elsif ($ARGV[$i] eq 'help') {
223 $cmd = $ARGV[$i+1];
224 usage(0);
228 # make sure we're always running at the top-level working directory
229 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
230 unless (-d $ENV{GIT_DIR}) {
231 if ($git_dir_user_set) {
232 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
233 "but it is not a directory\n";
235 my $git_dir = delete $ENV{GIT_DIR};
236 my $cdup = undef;
237 git_cmd_try {
238 $cdup = command_oneline(qw/rev-parse --show-cdup/);
239 $git_dir = '.' unless ($cdup);
240 chomp $cdup if ($cdup);
241 $cdup = "." unless ($cdup && length $cdup);
242 } "Already at toplevel, but $git_dir not found\n";
243 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
244 unless (-d $git_dir) {
245 die "$git_dir still not found after going to ",
246 "'$cdup'\n";
248 $ENV{GIT_DIR} = $git_dir;
250 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
253 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
255 read_repo_config(\%opts);
256 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
257 Getopt::Long::Configure('pass_through');
259 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
260 'minimize-connections' => \$Git::SVN::Migration::_minimize,
261 'id|i=s' => \$Git::SVN::default_ref_id,
262 'svn-remote|remote|R=s' => sub {
263 $Git::SVN::no_reuse_existing = 1;
264 $Git::SVN::default_repo_id = $_[1] });
265 exit 1 if (!$rv && $cmd && $cmd ne 'log');
267 usage(0) if $_help;
268 version() if $_version;
269 usage(1) unless defined $cmd;
270 load_authors() if $_authors;
271 if (defined $_authors_prog) {
272 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
275 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
276 Git::SVN::Migration::migration_check();
278 Git::SVN::init_vars();
279 eval {
280 Git::SVN::verify_remotes_sanity();
281 $cmd{$cmd}->[0]->(@ARGV);
283 fatal $@ if $@;
284 post_fetch_checkout();
285 exit 0;
287 ####################### primary functions ######################
288 sub usage {
289 my $exit = shift || 0;
290 my $fd = $exit ? \*STDERR : \*STDOUT;
291 print $fd <<"";
292 git-svn - bidirectional operations between a single Subversion tree and git
293 Usage: git svn <command> [options] [arguments]\n
295 print $fd "Available commands:\n" unless $cmd;
297 foreach (sort keys %cmd) {
298 next if $cmd && $cmd ne $_;
299 next if /^multi-/; # don't show deprecated commands
300 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
301 foreach (sort keys %{$cmd{$_}->[2]}) {
302 # mixed-case options are for .git/config only
303 next if /[A-Z]/ && /^[a-z]+$/i;
304 # prints out arguments as they should be passed:
305 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
306 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
307 "--$_" : "-$_" }
308 split /\|/,$_)," $x\n";
311 print $fd <<"";
312 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
313 arbitrary identifier if you're tracking multiple SVN branches/repositories in
314 one git repository and want to keep them separate. See git-svn(1) for more
315 information.
317 exit $exit;
320 sub version {
321 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
322 exit 0;
325 sub do_git_init_db {
326 unless (-d $ENV{GIT_DIR}) {
327 my @init_db = ('init');
328 push @init_db, "--template=$_template" if defined $_template;
329 if (defined $_shared) {
330 if ($_shared =~ /[a-z]/) {
331 push @init_db, "--shared=$_shared";
332 } else {
333 push @init_db, "--shared";
336 command_noisy(@init_db);
337 $_repository = Git->repository(Repository => ".git");
339 command_noisy('config', 'core.autocrlf', 'false');
340 my $set;
341 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
342 foreach my $i (keys %icv) {
343 die "'$set' and '$i' cannot both be set\n" if $set;
344 next unless defined $icv{$i};
345 command_noisy('config', "$pfx.$i", $icv{$i});
346 $set = $i;
348 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
349 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
350 if defined $$ignore_regex;
353 sub init_subdir {
354 my $repo_path = shift or return;
355 mkpath([$repo_path]) unless -d $repo_path;
356 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
357 $ENV{GIT_DIR} = '.git';
358 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
361 sub cmd_clone {
362 my ($url, $path) = @_;
363 if (!defined $path &&
364 (defined $_trunk || defined $_branches || defined $_tags ||
365 defined $_stdlayout) &&
366 $url !~ m#^[a-z\+]+://#) {
367 $path = $url;
369 $path = basename($url) if !defined $path || !length $path;
370 cmd_init($url, $path);
371 Git::SVN::fetch_all($Git::SVN::default_repo_id);
372 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
375 sub cmd_init {
376 if (defined $_stdlayout) {
377 $_trunk = 'trunk' if (!defined $_trunk);
378 $_tags = 'tags' if (!defined $_tags);
379 $_branches = 'branches' if (!defined $_branches);
381 if (defined $_trunk || defined $_branches || defined $_tags) {
382 return cmd_multi_init(@_);
384 my $url = shift or die "SVN repository location required ",
385 "as a command-line argument\n";
386 init_subdir(@_);
387 do_git_init_db();
389 Git::SVN->init($url);
392 sub cmd_fetch {
393 if (grep /^\d+=./, @_) {
394 die "'<rev>=<commit>' fetch arguments are ",
395 "no longer supported.\n";
397 my ($remote) = @_;
398 if (@_ > 1) {
399 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
401 if ($_fetch_parent) {
402 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
403 unless ($gs) {
404 die "Unable to determine upstream SVN information from ",
405 "working tree history\n";
407 # just fetch, don't checkout.
408 $_no_checkout = 'true';
409 $_fetch_all ? $gs->fetch_all : $gs->fetch;
410 } elsif ($_fetch_all) {
411 cmd_multi_fetch();
412 } else {
413 $remote ||= $Git::SVN::default_repo_id;
414 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
418 sub cmd_set_tree {
419 my (@commits) = @_;
420 if ($_stdin || !@commits) {
421 print "Reading from stdin...\n";
422 @commits = ();
423 while (<STDIN>) {
424 if (/\b($sha1_short)\b/o) {
425 unshift @commits, $1;
429 my @revs;
430 foreach my $c (@commits) {
431 my @tmp = command('rev-parse',$c);
432 if (scalar @tmp == 1) {
433 push @revs, $tmp[0];
434 } elsif (scalar @tmp > 1) {
435 push @revs, reverse(command('rev-list',@tmp));
436 } else {
437 fatal "Failed to rev-parse $c";
440 my $gs = Git::SVN->new;
441 my ($r_last, $cmt_last) = $gs->last_rev_commit;
442 $gs->fetch;
443 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
444 fatal "There are new revisions that were fetched ",
445 "and need to be merged (or acknowledged) ",
446 "before committing.\nlast rev: $r_last\n",
447 " current: $gs->{last_rev}";
449 $gs->set_tree($_) foreach @revs;
450 print "Done committing ",scalar @revs," revisions to SVN\n";
451 unlink $gs->{index};
454 sub cmd_dcommit {
455 my $head = shift;
456 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
457 'Cannot dcommit with a dirty index. Commit your changes first, '
458 . "or stash them with `git stash'.\n";
459 $head ||= 'HEAD';
461 my $old_head;
462 if ($head ne 'HEAD') {
463 $old_head = eval {
464 command_oneline([qw/symbolic-ref -q HEAD/])
466 if ($old_head) {
467 $old_head =~ s{^refs/heads/}{};
468 } else {
469 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
471 command(['checkout', $head], STDERR => 0);
474 my @refs;
475 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
476 unless ($gs) {
477 die "Unable to determine upstream SVN information from ",
478 "$head history.\nPerhaps the repository is empty.";
481 if (defined $_commit_url) {
482 $url = $_commit_url;
483 } else {
484 $url = eval { command_oneline('config', '--get',
485 "svn-remote.$gs->{repo_id}.commiturl") };
486 if (!$url) {
487 $url = $gs->full_url
491 my $last_rev = $_revision if defined $_revision;
492 if ($url) {
493 print "Committing to $url ...\n";
495 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
496 if ($_no_rebase && scalar(@$linear_refs) > 1) {
497 warn "Attempting to commit more than one change while ",
498 "--no-rebase is enabled.\n",
499 "If these changes depend on each other, re-running ",
500 "without --no-rebase may be required."
502 my $expect_url = $url;
503 Git::SVN::remove_username($expect_url);
504 while (1) {
505 my $d = shift @$linear_refs or last;
506 unless (defined $last_rev) {
507 (undef, $last_rev, undef) = cmt_metadata("$d~1");
508 unless (defined $last_rev) {
509 fatal "Unable to extract revision information ",
510 "from commit $d~1";
513 if ($_dry_run) {
514 print "diff-tree $d~1 $d\n";
515 } else {
516 my $cmt_rev;
517 my %ed_opts = ( r => $last_rev,
518 log => get_commit_entry($d)->{log},
519 ra => Git::SVN::Ra->new($url),
520 config => SVN::Core::config_get_config(
521 $Git::SVN::Ra::config_dir
523 tree_a => "$d~1",
524 tree_b => $d,
525 editor_cb => sub {
526 print "Committed r$_[0]\n";
527 $cmt_rev = $_[0];
529 svn_path => '');
530 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
531 print "No changes\n$d~1 == $d\n";
532 } elsif ($parents->{$d} && @{$parents->{$d}}) {
533 $gs->{inject_parents_dcommit}->{$cmt_rev} =
534 $parents->{$d};
536 $_fetch_all ? $gs->fetch_all : $gs->fetch;
537 $last_rev = $cmt_rev;
538 next if $_no_rebase;
540 # we always want to rebase against the current HEAD,
541 # not any head that was passed to us
542 my @diff = command('diff-tree', $d,
543 $gs->refname, '--');
544 my @finish;
545 if (@diff) {
546 @finish = rebase_cmd();
547 print STDERR "W: $d and ", $gs->refname,
548 " differ, using @finish:\n",
549 join("\n", @diff), "\n";
550 } else {
551 print "No changes between current HEAD and ",
552 $gs->refname,
553 "\nResetting to the latest ",
554 $gs->refname, "\n";
555 @finish = qw/reset --mixed/;
557 command_noisy(@finish, $gs->refname);
558 if (@diff) {
559 @refs = ();
560 my ($url_, $rev_, $uuid_, $gs_) =
561 working_head_info('HEAD', \@refs);
562 my ($linear_refs_, $parents_) =
563 linearize_history($gs_, \@refs);
564 if (scalar(@$linear_refs) !=
565 scalar(@$linear_refs_)) {
566 fatal "# of revisions changed ",
567 "\nbefore:\n",
568 join("\n", @$linear_refs),
569 "\n\nafter:\n",
570 join("\n", @$linear_refs_), "\n",
571 'If you are attempting to commit ',
572 "merges, try running:\n\t",
573 'git rebase --interactive',
574 '--preserve-merges ',
575 $gs->refname,
576 "\nBefore dcommitting";
578 if ($url_ ne $expect_url) {
579 fatal "URL mismatch after rebase: ",
580 "$url_ != $expect_url";
582 if ($uuid_ ne $uuid) {
583 fatal "uuid mismatch after rebase: ",
584 "$uuid_ != $uuid";
586 # remap parents
587 my (%p, @l, $i);
588 for ($i = 0; $i < scalar @$linear_refs; $i++) {
589 my $new = $linear_refs_->[$i] or next;
590 $p{$new} =
591 $parents->{$linear_refs->[$i]};
592 push @l, $new;
594 $parents = \%p;
595 $linear_refs = \@l;
600 if ($old_head) {
601 my $new_head = command_oneline(qw/rev-parse HEAD/);
602 my $new_is_symbolic = eval {
603 command_oneline(qw/symbolic-ref -q HEAD/);
605 if ($new_is_symbolic) {
606 print "dcommitted the branch ", $head, "\n";
607 } else {
608 print "dcommitted on a detached HEAD because you gave ",
609 "a revision argument.\n",
610 "The rewritten commit is: ", $new_head, "\n";
612 command(['checkout', $old_head], STDERR => 0);
615 unlink $gs->{index};
618 sub cmd_branch {
619 my ($branch_name, $head) = @_;
621 unless (defined $branch_name && length $branch_name) {
622 die(($_tag ? "tag" : "branch") . " name required\n");
624 $head ||= 'HEAD';
626 my ($src, $rev, undef, $gs) = working_head_info($head);
628 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
629 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
630 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
631 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
633 my $ctx = SVN::Client->new(
634 auth => Git::SVN::Ra::_auth_providers(),
635 log_msg => sub {
636 ${ $_[0] } = defined $_message
637 ? $_message
638 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
639 . $branch_name;
643 eval {
644 $ctx->ls($dst, 'HEAD', 0);
645 } and die "branch ${branch_name} already exists\n";
647 print "Copying ${src} at r${rev} to ${dst}...\n";
648 $ctx->copy($src, $rev, $dst)
649 unless $_dry_run;
651 $gs->fetch_all;
654 sub cmd_find_rev {
655 my $revision_or_hash = shift or die "SVN or git revision required ",
656 "as a command-line argument\n";
657 my $result;
658 if ($revision_or_hash =~ /^r\d+$/) {
659 my $head = shift;
660 $head ||= 'HEAD';
661 my @refs;
662 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
663 unless ($gs) {
664 die "Unable to determine upstream SVN information from ",
665 "$head history\n";
667 my $desired_revision = substr($revision_or_hash, 1);
668 $result = $gs->rev_map_get($desired_revision, $uuid);
669 } else {
670 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
671 $result = $rev;
673 print "$result\n" if $result;
676 sub cmd_rebase {
677 command_noisy(qw/update-index --refresh/);
678 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
679 unless ($gs) {
680 die "Unable to determine upstream SVN information from ",
681 "working tree history\n";
683 if ($_dry_run) {
684 print "Remote Branch: " . $gs->refname . "\n";
685 print "SVN URL: " . $url . "\n";
686 return;
688 if (command(qw/diff-index HEAD --/)) {
689 print STDERR "Cannot rebase with uncommited changes:\n";
690 command_noisy('status');
691 exit 1;
693 unless ($_local) {
694 # rebase will checkout for us, so no need to do it explicitly
695 $_no_checkout = 'true';
696 $_fetch_all ? $gs->fetch_all : $gs->fetch;
698 command_noisy(rebase_cmd(), $gs->refname);
701 sub cmd_show_ignore {
702 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
703 $gs ||= Git::SVN->new;
704 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
705 $gs->prop_walk($gs->{path}, $r, sub {
706 my ($gs, $path, $props) = @_;
707 print STDOUT "\n# $path\n";
708 my $s = $props->{'svn:ignore'} or return;
709 $s =~ s/[\r\n]+/\n/g;
710 chomp $s;
711 $s =~ s#^#$path#gm;
712 print STDOUT "$s\n";
716 sub cmd_show_externals {
717 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
718 $gs ||= Git::SVN->new;
719 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
720 $gs->prop_walk($gs->{path}, $r, sub {
721 my ($gs, $path, $props) = @_;
722 print STDOUT "\n# $path\n";
723 my $s = $props->{'svn:externals'} or return;
724 $s =~ s/[\r\n]+/\n/g;
725 chomp $s;
726 $s =~ s#^#$path#gm;
727 print STDOUT "$s\n";
731 sub cmd_create_ignore {
732 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
733 $gs ||= Git::SVN->new;
734 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
735 $gs->prop_walk($gs->{path}, $r, sub {
736 my ($gs, $path, $props) = @_;
737 # $path is of the form /path/to/dir/
738 $path = '.' . $path;
739 # SVN can have attributes on empty directories,
740 # which git won't track
741 mkpath([$path]) unless -d $path;
742 my $ignore = $path . '.gitignore';
743 my $s = $props->{'svn:ignore'} or return;
744 open(GITIGNORE, '>', $ignore)
745 or fatal("Failed to open `$ignore' for writing: $!");
746 $s =~ s/[\r\n]+/\n/g;
747 chomp $s;
748 # Prefix all patterns so that the ignore doesn't apply
749 # to sub-directories.
750 $s =~ s#^#/#gm;
751 print GITIGNORE "$s\n";
752 close(GITIGNORE)
753 or fatal("Failed to close `$ignore': $!");
754 command_noisy('add', '-f', $ignore);
758 sub canonicalize_path {
759 my ($path) = @_;
760 my $dot_slash_added = 0;
761 if (substr($path, 0, 1) ne "/") {
762 $path = "./" . $path;
763 $dot_slash_added = 1;
765 # File::Spec->canonpath doesn't collapse x/../y into y (for a
766 # good reason), so let's do this manually.
767 $path =~ s#/+#/#g;
768 $path =~ s#/\.(?:/|$)#/#g;
769 $path =~ s#/[^/]+/\.\.##g;
770 $path =~ s#/$##g;
771 $path =~ s#^\./## if $dot_slash_added;
772 $path =~ s#^/##;
773 $path =~ s#^\.$##;
774 return $path;
777 # get_svnprops(PATH)
778 # ------------------
779 # Helper for cmd_propget and cmd_proplist below.
780 sub get_svnprops {
781 my $path = shift;
782 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
783 $gs ||= Git::SVN->new;
785 # prefix THE PATH by the sub-directory from which the user
786 # invoked us.
787 $path = $cmd_dir_prefix . $path;
788 fatal("No such file or directory: $path") unless -e $path;
789 my $is_dir = -d $path ? 1 : 0;
790 $path = $gs->{path} . '/' . $path;
792 # canonicalize the path (otherwise libsvn will abort or fail to
793 # find the file)
794 $path = canonicalize_path($path);
796 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
797 my $props;
798 if ($is_dir) {
799 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
801 else {
802 (undef, $props) = $gs->ra->get_file($path, $r, undef);
804 return $props;
807 # cmd_propget (PROP, PATH)
808 # ------------------------
809 # Print the SVN property PROP for PATH.
810 sub cmd_propget {
811 my ($prop, $path) = @_;
812 $path = '.' if not defined $path;
813 usage(1) if not defined $prop;
814 my $props = get_svnprops($path);
815 if (not defined $props->{$prop}) {
816 fatal("`$path' does not have a `$prop' SVN property.");
818 print $props->{$prop} . "\n";
821 # cmd_proplist (PATH)
822 # -------------------
823 # Print the list of SVN properties for PATH.
824 sub cmd_proplist {
825 my $path = shift;
826 $path = '.' if not defined $path;
827 my $props = get_svnprops($path);
828 print "Properties on '$path':\n";
829 foreach (sort keys %{$props}) {
830 print " $_\n";
834 sub cmd_multi_init {
835 my $url = shift;
836 unless (defined $_trunk || defined $_branches || defined $_tags) {
837 usage(1);
840 # there are currently some bugs that prevent multi-init/multi-fetch
841 # setups from working well without this.
842 $Git::SVN::_minimize_url = 1;
844 $_prefix = '' unless defined $_prefix;
845 if (defined $url) {
846 $url =~ s#/+$##;
847 init_subdir(@_);
849 do_git_init_db();
850 if (defined $_trunk) {
851 my $trunk_ref = $_prefix . 'trunk';
852 # try both old-style and new-style lookups:
853 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
854 unless ($gs_trunk) {
855 my ($trunk_url, $trunk_path) =
856 complete_svn_url($url, $_trunk);
857 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
858 undef, $trunk_ref);
861 return unless defined $_branches || defined $_tags;
862 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
863 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
864 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
867 sub cmd_multi_fetch {
868 my $remotes = Git::SVN::read_all_remotes();
869 foreach my $repo_id (sort keys %$remotes) {
870 if ($remotes->{$repo_id}->{url}) {
871 Git::SVN::fetch_all($repo_id, $remotes);
876 # this command is special because it requires no metadata
877 sub cmd_commit_diff {
878 my ($ta, $tb, $url) = @_;
879 my $usage = "Usage: $0 commit-diff -r<revision> ".
880 "<tree-ish> <tree-ish> [<URL>]";
881 fatal($usage) if (!defined $ta || !defined $tb);
882 my $svn_path = '';
883 if (!defined $url) {
884 my $gs = eval { Git::SVN->new };
885 if (!$gs) {
886 fatal("Needed URL or usable git-svn --id in ",
887 "the command-line\n", $usage);
889 $url = $gs->{url};
890 $svn_path = $gs->{path};
892 unless (defined $_revision) {
893 fatal("-r|--revision is a required argument\n", $usage);
895 if (defined $_message && defined $_file) {
896 fatal("Both --message/-m and --file/-F specified ",
897 "for the commit message.\n",
898 "I have no idea what you mean");
900 if (defined $_file) {
901 $_message = file_to_s($_file);
902 } else {
903 $_message ||= get_commit_entry($tb)->{log};
905 my $ra ||= Git::SVN::Ra->new($url);
906 my $r = $_revision;
907 if ($r eq 'HEAD') {
908 $r = $ra->get_latest_revnum;
909 } elsif ($r !~ /^\d+$/) {
910 die "revision argument: $r not understood by git-svn\n";
912 my %ed_opts = ( r => $r,
913 log => $_message,
914 ra => $ra,
915 tree_a => $ta,
916 tree_b => $tb,
917 editor_cb => sub { print "Committed r$_[0]\n" },
918 svn_path => $svn_path );
919 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
920 print "No changes\n$ta == $tb\n";
924 sub escape_uri_only {
925 my ($uri) = @_;
926 my @tmp;
927 foreach (split m{/}, $uri) {
928 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
929 push @tmp, $_;
931 join('/', @tmp);
934 sub escape_url {
935 my ($url) = @_;
936 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
937 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
938 $url = "$scheme://$domain$uri";
940 $url;
943 sub cmd_info {
944 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
945 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
946 if (exists $_[1]) {
947 die "Too many arguments specified\n";
950 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
952 if (!$file_type && !$diff_status) {
953 print STDERR "svn: '$path' is not under version control\n";
954 exit 1;
957 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
958 unless ($gs) {
959 die "Unable to determine upstream SVN information from ",
960 "working tree history\n";
963 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
964 $path = "." if $path eq "";
966 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
968 if ($_url) {
969 print escape_url($full_url), "\n";
970 return;
973 my $result = "Path: $path\n";
974 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
975 $result .= "URL: " . escape_url($full_url) . "\n";
977 eval {
978 my $repos_root = $gs->repos_root;
979 Git::SVN::remove_username($repos_root);
980 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
982 if ($@) {
983 $result .= "Repository Root: (offline)\n";
985 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
986 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
987 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
989 $result .= "Node Kind: " .
990 ($file_type eq "dir" ? "directory" : "file") . "\n";
992 my $schedule = $diff_status eq "A"
993 ? "add"
994 : ($diff_status eq "D" ? "delete" : "normal");
995 $result .= "Schedule: $schedule\n";
997 if ($diff_status eq "A") {
998 print $result, "\n";
999 return;
1002 my ($lc_author, $lc_rev, $lc_date_utc);
1003 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1004 my $log = command_output_pipe(@args);
1005 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1006 while (<$log>) {
1007 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1008 $lc_author = $1;
1009 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1010 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1011 (undef, $lc_rev, undef) = ::extract_metadata($1);
1014 close $log;
1016 Git::SVN::Log::set_local_timezone();
1018 $result .= "Last Changed Author: $lc_author\n";
1019 $result .= "Last Changed Rev: $lc_rev\n";
1020 $result .= "Last Changed Date: " .
1021 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1023 if ($file_type ne "dir") {
1024 my $text_last_updated_date =
1025 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1026 $result .=
1027 "Text Last Updated: " .
1028 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1029 "\n";
1030 my $checksum;
1031 if ($diff_status eq "D") {
1032 my ($fh, $ctx) =
1033 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1034 if ($file_type eq "link") {
1035 my $file_name = <$fh>;
1036 $checksum = md5sum("link $file_name");
1037 } else {
1038 $checksum = md5sum($fh);
1040 command_close_pipe($fh, $ctx);
1041 } elsif ($file_type eq "link") {
1042 my $file_name =
1043 command(qw(cat-file blob), "HEAD:$path");
1044 $checksum =
1045 md5sum("link " . $file_name);
1046 } else {
1047 open FILE, "<", $path or die $!;
1048 $checksum = md5sum(\*FILE);
1049 close FILE or die $!;
1051 $result .= "Checksum: " . $checksum . "\n";
1054 print $result, "\n";
1057 ########################### utility functions #########################
1059 sub rebase_cmd {
1060 my @cmd = qw/rebase/;
1061 push @cmd, '-v' if $_verbose;
1062 push @cmd, qw/--merge/ if $_merge;
1063 push @cmd, "--strategy=$_strategy" if $_strategy;
1064 @cmd;
1067 sub post_fetch_checkout {
1068 return if $_no_checkout;
1069 my $gs = $Git::SVN::_head or return;
1070 return if verify_ref('refs/heads/master^0');
1072 my $valid_head = verify_ref('HEAD^0');
1073 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1074 return if ($valid_head || !verify_ref('HEAD^0'));
1076 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1077 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1078 return if -f $index;
1080 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1081 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1082 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1083 print STDERR "Checked out HEAD:\n ",
1084 $gs->full_url, " r", $gs->last_rev, "\n";
1087 sub complete_svn_url {
1088 my ($url, $path) = @_;
1089 $path =~ s#/+$##;
1090 if ($path !~ m#^[a-z\+]+://#) {
1091 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1092 fatal("E: '$path' is not a complete URL ",
1093 "and a separate URL is not specified");
1095 return ($url, $path);
1097 return ($path, '');
1100 sub complete_url_ls_init {
1101 my ($ra, $repo_path, $switch, $pfx) = @_;
1102 unless ($repo_path) {
1103 print STDERR "W: $switch not specified\n";
1104 return;
1106 $repo_path =~ s#/+$##;
1107 if ($repo_path =~ m#^[a-z\+]+://#) {
1108 $ra = Git::SVN::Ra->new($repo_path);
1109 $repo_path = '';
1110 } else {
1111 $repo_path =~ s#^/+##;
1112 unless ($ra) {
1113 fatal("E: '$repo_path' is not a complete URL ",
1114 "and a separate URL is not specified");
1117 my $url = $ra->{url};
1118 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1119 my $k = "svn-remote.$gs->{repo_id}.url";
1120 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1121 if ($orig_url && ($orig_url ne $gs->{url})) {
1122 die "$k already set: $orig_url\n",
1123 "wanted to set to: $gs->{url}\n";
1125 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1126 my $remote_path = "$ra->{svn_path}/$repo_path";
1127 $remote_path =~ s#/+#/#g;
1128 $remote_path =~ s#^/##g;
1129 $remote_path .= "/*" if $remote_path !~ /\*/;
1130 my ($n) = ($switch =~ /^--(\w+)/);
1131 if (length $pfx && $pfx !~ m#/$#) {
1132 die "--prefix='$pfx' must have a trailing slash '/'\n";
1134 command_noisy('config',
1135 "svn-remote.$gs->{repo_id}.$n",
1136 "$remote_path:refs/remotes/$pfx*" .
1137 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1140 sub verify_ref {
1141 my ($ref) = @_;
1142 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1143 { STDERR => 0 }); };
1146 sub get_tree_from_treeish {
1147 my ($treeish) = @_;
1148 # $treeish can be a symbolic ref, too:
1149 my $type = command_oneline(qw/cat-file -t/, $treeish);
1150 my $expected;
1151 while ($type eq 'tag') {
1152 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1154 if ($type eq 'commit') {
1155 $expected = (grep /^tree /, command(qw/cat-file commit/,
1156 $treeish))[0];
1157 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1158 die "Unable to get tree from $treeish\n" unless $expected;
1159 } elsif ($type eq 'tree') {
1160 $expected = $treeish;
1161 } else {
1162 die "$treeish is a $type, expected tree, tag or commit\n";
1164 return $expected;
1167 sub get_commit_entry {
1168 my ($treeish) = shift;
1169 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1170 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1171 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1172 open my $log_fh, '>', $commit_editmsg or croak $!;
1174 my $type = command_oneline(qw/cat-file -t/, $treeish);
1175 if ($type eq 'commit' || $type eq 'tag') {
1176 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1177 $type, $treeish);
1178 my $in_msg = 0;
1179 my $author;
1180 my $saw_from = 0;
1181 my $msgbuf = "";
1182 while (<$msg_fh>) {
1183 if (!$in_msg) {
1184 $in_msg = 1 if (/^\s*$/);
1185 $author = $1 if (/^author (.*>)/);
1186 } elsif (/^git-svn-id: /) {
1187 # skip this for now, we regenerate the
1188 # correct one on re-fetch anyways
1189 # TODO: set *:merge properties or like...
1190 } else {
1191 if (/^From:/ || /^Signed-off-by:/) {
1192 $saw_from = 1;
1194 $msgbuf .= $_;
1197 $msgbuf =~ s/\s+$//s;
1198 if ($Git::SVN::_add_author_from && defined($author)
1199 && !$saw_from) {
1200 $msgbuf .= "\n\nFrom: $author";
1202 print $log_fh $msgbuf or croak $!;
1203 command_close_pipe($msg_fh, $ctx);
1205 close $log_fh or croak $!;
1207 if ($_edit || ($type eq 'tree')) {
1208 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1209 # TODO: strip out spaces, comments, like git-commit.sh
1210 system($editor, $commit_editmsg);
1212 rename $commit_editmsg, $commit_msg or croak $!;
1214 require Encode;
1215 # SVN requires messages to be UTF-8 when entering the repo
1216 local $/;
1217 open $log_fh, '<', $commit_msg or croak $!;
1218 binmode $log_fh;
1219 chomp($log_entry{log} = <$log_fh>);
1221 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1222 my $msg = $log_entry{log};
1224 eval { $msg = Encode::decode($enc, $msg, 1) };
1225 if ($@) {
1226 die "Could not decode as $enc:\n", $msg,
1227 "\nPerhaps you need to set i18n.commitencoding\n";
1230 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1231 die "Could not encode as UTF-8:\n$msg\n" if $@;
1233 $log_entry{log} = $msg;
1235 close $log_fh or croak $!;
1237 unlink $commit_msg;
1238 \%log_entry;
1241 sub s_to_file {
1242 my ($str, $file, $mode) = @_;
1243 open my $fd,'>',$file or croak $!;
1244 print $fd $str,"\n" or croak $!;
1245 close $fd or croak $!;
1246 chmod ($mode &~ umask, $file) if (defined $mode);
1249 sub file_to_s {
1250 my $file = shift;
1251 open my $fd,'<',$file or croak "$!: file: $file\n";
1252 local $/;
1253 my $ret = <$fd>;
1254 close $fd or croak $!;
1255 $ret =~ s/\s*$//s;
1256 return $ret;
1259 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1260 sub load_authors {
1261 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1262 my $log = $cmd eq 'log';
1263 while (<$authors>) {
1264 chomp;
1265 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1266 my ($user, $name, $email) = ($1, $2, $3);
1267 if ($log) {
1268 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1269 } else {
1270 $users{$user} = [$name, $email];
1273 close $authors or croak $!;
1276 # convert GetOpt::Long specs for use by git-config
1277 sub read_repo_config {
1278 return unless -d $ENV{GIT_DIR};
1279 my $opts = shift;
1280 my @config_only;
1281 foreach my $o (keys %$opts) {
1282 # if we have mixedCase and a long option-only, then
1283 # it's a config-only variable that we don't need for
1284 # the command-line.
1285 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1286 my $v = $opts->{$o};
1287 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1288 $key =~ s/-//g;
1289 my $arg = 'git config';
1290 $arg .= ' --int' if ($o =~ /[:=]i$/);
1291 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1292 if (ref $v eq 'ARRAY') {
1293 chomp(my @tmp = `$arg --get-all svn.$key`);
1294 @$v = @tmp if @tmp;
1295 } else {
1296 chomp(my $tmp = `$arg --get svn.$key`);
1297 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1298 $$v = $tmp;
1302 delete @$opts{@config_only} if @config_only;
1305 sub extract_metadata {
1306 my $id = shift or return (undef, undef, undef);
1307 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1308 \s([a-f\d\-]+)$/x);
1309 if (!defined $rev || !$uuid || !$url) {
1310 # some of the original repositories I made had
1311 # identifiers like this:
1312 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1314 return ($url, $rev, $uuid);
1317 sub cmt_metadata {
1318 return extract_metadata((grep(/^git-svn-id: /,
1319 command(qw/cat-file commit/, shift)))[-1]);
1322 sub cmt_sha2rev_batch {
1323 my %s2r;
1324 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1325 my $list = shift;
1327 foreach my $sha (@{$list}) {
1328 my $first = 1;
1329 my $size = 0;
1330 print $out $sha, "\n";
1332 while (my $line = <$in>) {
1333 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1334 last;
1335 } elsif ($first &&
1336 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1337 $first = 0;
1338 $size = $1;
1339 next;
1340 } elsif ($line =~ /^(git-svn-id: )/) {
1341 my (undef, $rev, undef) =
1342 extract_metadata($line);
1343 $s2r{$sha} = $rev;
1346 $size -= length($line);
1347 last if ($size == 0);
1351 command_close_bidi_pipe($pid, $in, $out, $ctx);
1353 return \%s2r;
1356 sub working_head_info {
1357 my ($head, $refs) = @_;
1358 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1359 my ($fh, $ctx) = command_output_pipe(@args, $head);
1360 my $hash;
1361 my %max;
1362 while (<$fh>) {
1363 if ( m{^commit ($::sha1)$} ) {
1364 unshift @$refs, $hash if $hash and $refs;
1365 $hash = $1;
1366 next;
1368 next unless s{^\s*(git-svn-id:)}{$1};
1369 my ($url, $rev, $uuid) = extract_metadata($_);
1370 if (defined $url && defined $rev) {
1371 next if $max{$url} and $max{$url} < $rev;
1372 if (my $gs = Git::SVN->find_by_url($url)) {
1373 my $c = $gs->rev_map_get($rev, $uuid);
1374 if ($c && $c eq $hash) {
1375 close $fh; # break the pipe
1376 return ($url, $rev, $uuid, $gs);
1377 } else {
1378 $max{$url} ||= $gs->rev_map_max;
1383 command_close_pipe($fh, $ctx);
1384 (undef, undef, undef, undef);
1387 sub read_commit_parents {
1388 my ($parents, $c) = @_;
1389 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1390 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1391 @{$parents->{$c}} = split(/ /, $p);
1394 sub linearize_history {
1395 my ($gs, $refs) = @_;
1396 my %parents;
1397 foreach my $c (@$refs) {
1398 read_commit_parents(\%parents, $c);
1401 my @linear_refs;
1402 my %skip = ();
1403 my $last_svn_commit = $gs->last_commit;
1404 foreach my $c (reverse @$refs) {
1405 next if $c eq $last_svn_commit;
1406 last if $skip{$c};
1408 unshift @linear_refs, $c;
1409 $skip{$c} = 1;
1411 # we only want the first parent to diff against for linear
1412 # history, we save the rest to inject when we finalize the
1413 # svn commit
1414 my $fp_a = verify_ref("$c~1");
1415 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1416 if (!$fp_a || !$fp_b) {
1417 die "Commit $c\n",
1418 "has no parent commit, and therefore ",
1419 "nothing to diff against.\n",
1420 "You should be working from a repository ",
1421 "originally created by git-svn\n";
1423 if ($fp_a ne $fp_b) {
1424 die "$c~1 = $fp_a, however parsing commit $c ",
1425 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1428 foreach my $p (@{$parents{$c}}) {
1429 $skip{$p} = 1;
1432 (\@linear_refs, \%parents);
1435 sub find_file_type_and_diff_status {
1436 my ($path) = @_;
1437 return ('dir', '') if $path eq '';
1439 my $diff_output =
1440 command_oneline(qw(diff --cached --name-status --), $path) || "";
1441 my $diff_status = (split(' ', $diff_output))[0] || "";
1443 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1445 return (undef, undef) if !$diff_status && !$ls_tree;
1447 if ($diff_status eq "A") {
1448 return ("link", $diff_status) if -l $path;
1449 return ("dir", $diff_status) if -d $path;
1450 return ("file", $diff_status);
1453 my $mode = (split(' ', $ls_tree))[0] || "";
1455 return ("link", $diff_status) if $mode eq "120000";
1456 return ("dir", $diff_status) if $mode eq "040000";
1457 return ("file", $diff_status);
1460 sub md5sum {
1461 my $arg = shift;
1462 my $ref = ref $arg;
1463 my $md5 = Digest::MD5->new();
1464 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1465 $md5->addfile($arg) or croak $!;
1466 } elsif ($ref eq 'SCALAR') {
1467 $md5->add($$arg) or croak $!;
1468 } elsif (!$ref) {
1469 $md5->add($arg) or croak $!;
1470 } else {
1471 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1473 return $md5->hexdigest();
1476 package Git::SVN;
1477 use strict;
1478 use warnings;
1479 use Fcntl qw/:DEFAULT :seek/;
1480 use constant rev_map_fmt => 'NH40';
1481 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1482 $_repack $_repack_flags $_use_svm_props $_head
1483 $_use_svnsync_props $no_reuse_existing $_minimize_url
1484 $_use_log_author $_add_author_from $_localtime/;
1485 use Carp qw/croak/;
1486 use File::Path qw/mkpath/;
1487 use File::Copy qw/copy/;
1488 use IPC::Open3;
1490 my ($_gc_nr, $_gc_period);
1492 # properties that we do not log:
1493 my %SKIP_PROP;
1494 BEGIN {
1495 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1496 svn:special svn:executable
1497 svn:entry:committed-rev
1498 svn:entry:last-author
1499 svn:entry:uuid
1500 svn:entry:committed-date/;
1502 # some options are read globally, but can be overridden locally
1503 # per [svn-remote "..."] section. Command-line options will *NOT*
1504 # override options set in an [svn-remote "..."] section
1505 no strict 'refs';
1506 for my $option (qw/follow_parent no_metadata use_svm_props
1507 use_svnsync_props/) {
1508 my $key = $option;
1509 $key =~ tr/_//d;
1510 my $prop = "-$option";
1511 *$option = sub {
1512 my ($self) = @_;
1513 return $self->{$prop} if exists $self->{$prop};
1514 my $k = "svn-remote.$self->{repo_id}.$key";
1515 eval { command_oneline(qw/config --get/, $k) };
1516 if ($@) {
1517 $self->{$prop} = ${"Git::SVN::_$option"};
1518 } else {
1519 my $v = command_oneline(qw/config --bool/,$k);
1520 $self->{$prop} = $v eq 'false' ? 0 : 1;
1522 return $self->{$prop};
1528 my (%LOCKFILES, %INDEX_FILES);
1529 END {
1530 unlink keys %LOCKFILES if %LOCKFILES;
1531 unlink keys %INDEX_FILES if %INDEX_FILES;
1534 sub resolve_local_globs {
1535 my ($url, $fetch, $glob_spec) = @_;
1536 return unless defined $glob_spec;
1537 my $ref = $glob_spec->{ref};
1538 my $path = $glob_spec->{path};
1539 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1540 next unless m#^refs/remotes/$ref->{regex}$#;
1541 my $p = $1;
1542 my $pathname = desanitize_refname($path->full_path($p));
1543 my $refname = desanitize_refname($ref->full_path($p));
1544 if (my $existing = $fetch->{$pathname}) {
1545 if ($existing ne $refname) {
1546 die "Refspec conflict:\n",
1547 "existing: refs/remotes/$existing\n",
1548 " globbed: refs/remotes/$refname\n";
1550 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1551 $u =~ s!^\Q$url\E(/|$)!! or die
1552 "refs/remotes/$refname: '$url' not found in '$u'\n";
1553 if ($pathname ne $u) {
1554 warn "W: Refspec glob conflict ",
1555 "(ref: refs/remotes/$refname):\n",
1556 "expected path: $pathname\n",
1557 " real path: $u\n",
1558 "Continuing ahead with $u\n";
1559 next;
1561 } else {
1562 $fetch->{$pathname} = $refname;
1567 sub parse_revision_argument {
1568 my ($base, $head) = @_;
1569 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1570 return ($base, $head);
1572 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1573 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1574 return ($head, $head) if ($::_revision eq 'HEAD');
1575 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1576 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1577 die "revision argument: $::_revision not understood by git-svn\n";
1580 sub fetch_all {
1581 my ($repo_id, $remotes) = @_;
1582 if (ref $repo_id) {
1583 my $gs = $repo_id;
1584 $repo_id = undef;
1585 $repo_id = $gs->{repo_id};
1587 $remotes ||= read_all_remotes();
1588 my $remote = $remotes->{$repo_id} or
1589 die "[svn-remote \"$repo_id\"] unknown\n";
1590 my $fetch = $remote->{fetch};
1591 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1592 my (@gs, @globs);
1593 my $ra = Git::SVN::Ra->new($url);
1594 my $uuid = $ra->get_uuid;
1595 my $head = $ra->get_latest_revnum;
1596 my $base = defined $fetch ? $head : 0;
1598 # read the max revs for wildcard expansion (branches/*, tags/*)
1599 foreach my $t (qw/branches tags/) {
1600 defined $remote->{$t} or next;
1601 push @globs, $remote->{$t};
1602 my $max_rev = eval { tmp_config(qw/--int --get/,
1603 "svn-remote.$repo_id.${t}-maxRev") };
1604 if (defined $max_rev && ($max_rev < $base)) {
1605 $base = $max_rev;
1606 } elsif (!defined $max_rev) {
1607 $base = 0;
1611 if ($fetch) {
1612 foreach my $p (sort keys %$fetch) {
1613 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1614 my $lr = $gs->rev_map_max;
1615 if (defined $lr) {
1616 $base = $lr if ($lr < $base);
1618 push @gs, $gs;
1622 ($base, $head) = parse_revision_argument($base, $head);
1623 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1626 sub read_all_remotes {
1627 my $r = {};
1628 my $use_svm_props = eval { command_oneline(qw/config --bool
1629 svn.useSvmProps/) };
1630 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1631 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1632 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1633 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1634 die("svn-remote.$remote: remote ref '$_remote_ref' "
1635 . "must start with 'refs/remotes/'\n")
1636 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1637 my $remote_ref = $1;
1638 $local_ref =~ s{^/}{};
1639 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1640 $r->{$remote}->{svm} = {} if $use_svm_props;
1641 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1642 $r->{$1}->{svm} = {};
1643 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1644 $r->{$1}->{url} = $2;
1645 } elsif (m!^(.+)\.(branches|tags)=
1646 (.*):refs/remotes/(.+)\s*$/!x) {
1647 my ($p, $g) = ($3, $4);
1648 my $rs = $r->{$1}->{$2} = {
1649 t => $2,
1650 remote => $1,
1651 path => Git::SVN::GlobSpec->new($p),
1652 ref => Git::SVN::GlobSpec->new($g) };
1653 if (length($rs->{ref}->{right}) != 0) {
1654 die "The '*' glob character must be the last ",
1655 "character of '$g'\n";
1660 map {
1661 if (defined $r->{$_}->{svm}) {
1662 my $svm;
1663 eval {
1664 my $section = "svn-remote.$_";
1665 $svm = {
1666 source => tmp_config('--get',
1667 "$section.svm-source"),
1668 replace => tmp_config('--get',
1669 "$section.svm-replace"),
1672 $r->{$_}->{svm} = $svm;
1674 } keys %$r;
1679 sub init_vars {
1680 $_gc_nr = $_gc_period = 1000;
1681 if (defined $_repack || defined $_repack_flags) {
1682 warn "Repack options are obsolete; they have no effect.\n";
1686 sub verify_remotes_sanity {
1687 return unless -d $ENV{GIT_DIR};
1688 my %seen;
1689 foreach (command(qw/config -l/)) {
1690 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1691 if ($seen{$1}) {
1692 die "Remote ref refs/remote/$1 is tracked by",
1693 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1694 "Please resolve this ambiguity in ",
1695 "your git configuration file before ",
1696 "continuing\n";
1698 $seen{$1} = $_;
1703 sub find_existing_remote {
1704 my ($url, $remotes) = @_;
1705 return undef if $no_reuse_existing;
1706 my $existing;
1707 foreach my $repo_id (keys %$remotes) {
1708 my $u = $remotes->{$repo_id}->{url} or next;
1709 next if $u ne $url;
1710 $existing = $repo_id;
1711 last;
1713 $existing;
1716 sub init_remote_config {
1717 my ($self, $url, $no_write) = @_;
1718 $url =~ s!/+$!!; # strip trailing slash
1719 my $r = read_all_remotes();
1720 my $existing = find_existing_remote($url, $r);
1721 if ($existing) {
1722 unless ($no_write) {
1723 print STDERR "Using existing ",
1724 "[svn-remote \"$existing\"]\n";
1726 $self->{repo_id} = $existing;
1727 } elsif ($_minimize_url) {
1728 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1729 $existing = find_existing_remote($min_url, $r);
1730 if ($existing) {
1731 unless ($no_write) {
1732 print STDERR "Using existing ",
1733 "[svn-remote \"$existing\"]\n";
1735 $self->{repo_id} = $existing;
1737 if ($min_url ne $url) {
1738 unless ($no_write) {
1739 print STDERR "Using higher level of URL: ",
1740 "$url => $min_url\n";
1742 my $old_path = $self->{path};
1743 $self->{path} = $url;
1744 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1745 if (length $old_path) {
1746 $self->{path} .= "/$old_path";
1748 $url = $min_url;
1751 my $orig_url;
1752 if (!$existing) {
1753 # verify that we aren't overwriting anything:
1754 $orig_url = eval {
1755 command_oneline('config', '--get',
1756 "svn-remote.$self->{repo_id}.url")
1758 if ($orig_url && ($orig_url ne $url)) {
1759 die "svn-remote.$self->{repo_id}.url already set: ",
1760 "$orig_url\nwanted to set to: $url\n";
1763 my ($xrepo_id, $xpath) = find_ref($self->refname);
1764 if (defined $xpath) {
1765 die "svn-remote.$xrepo_id.fetch already set to track ",
1766 "$xpath:refs/remotes/", $self->refname, "\n";
1768 unless ($no_write) {
1769 command_noisy('config',
1770 "svn-remote.$self->{repo_id}.url", $url);
1771 $self->{path} =~ s{^/}{};
1772 command_noisy('config', '--add',
1773 "svn-remote.$self->{repo_id}.fetch",
1774 "$self->{path}:".$self->refname);
1776 $self->{url} = $url;
1779 sub find_by_url { # repos_root and, path are optional
1780 my ($class, $full_url, $repos_root, $path) = @_;
1782 return undef unless defined $full_url;
1783 remove_username($full_url);
1784 remove_username($repos_root) if defined $repos_root;
1785 my $remotes = read_all_remotes();
1786 if (defined $full_url && defined $repos_root && !defined $path) {
1787 $path = $full_url;
1788 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1790 foreach my $repo_id (keys %$remotes) {
1791 my $u = $remotes->{$repo_id}->{url} or next;
1792 remove_username($u);
1793 next if defined $repos_root && $repos_root ne $u;
1795 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1796 foreach (qw/branches tags/) {
1797 resolve_local_globs($u, $fetch,
1798 $remotes->{$repo_id}->{$_});
1800 my $p = $path;
1801 my $rwr = rewrite_root({repo_id => $repo_id});
1802 my $svm = $remotes->{$repo_id}->{svm}
1803 if defined $remotes->{$repo_id}->{svm};
1804 unless (defined $p) {
1805 $p = $full_url;
1806 my $z = $u;
1807 my $prefix = '';
1808 if ($rwr) {
1809 $z = $rwr;
1810 remove_username($z);
1811 } elsif (defined $svm) {
1812 $z = $svm->{source};
1813 $prefix = $svm->{replace};
1814 $prefix =~ s#^\Q$u\E(?:/|$)##;
1815 $prefix =~ s#/$##;
1817 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1819 foreach my $f (keys %$fetch) {
1820 next if $f ne $p;
1821 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1824 undef;
1827 sub init {
1828 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1829 my $self = _new($class, $repo_id, $ref_id, $path);
1830 if (defined $url) {
1831 $self->init_remote_config($url, $no_write);
1833 $self;
1836 sub find_ref {
1837 my ($ref_id) = @_;
1838 foreach (command(qw/config -l/)) {
1839 next unless m!^svn-remote\.(.+)\.fetch=
1840 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1841 my ($repo_id, $path, $ref) = ($1, $2, $3);
1842 if ($ref eq $ref_id) {
1843 $path = '' if ($path =~ m#^\./?#);
1844 return ($repo_id, $path);
1847 (undef, undef, undef);
1850 sub new {
1851 my ($class, $ref_id, $repo_id, $path) = @_;
1852 if (defined $ref_id && !defined $repo_id && !defined $path) {
1853 ($repo_id, $path) = find_ref($ref_id);
1854 if (!defined $repo_id) {
1855 die "Could not find a \"svn-remote.*.fetch\" key ",
1856 "in the repository configuration matching: ",
1857 "refs/remotes/$ref_id\n";
1860 my $self = _new($class, $repo_id, $ref_id, $path);
1861 if (!defined $self->{path} || !length $self->{path}) {
1862 my $fetch = command_oneline('config', '--get',
1863 "svn-remote.$repo_id.fetch",
1864 ":refs/remotes/$ref_id\$") or
1865 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1866 "\":refs/remotes/$ref_id\$\" in config\n";
1867 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1869 $self->{url} = command_oneline('config', '--get',
1870 "svn-remote.$repo_id.url") or
1871 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1872 $self->rebuild;
1873 $self;
1876 sub refname {
1877 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1879 # It cannot end with a slash /, we'll throw up on this because
1880 # SVN can't have directories with a slash in their name, either:
1881 if ($refname =~ m{/$}) {
1882 die "ref: '$refname' ends with a trailing slash, this is ",
1883 "not permitted by git nor Subversion\n";
1886 # It cannot have ASCII control character space, tilde ~, caret ^,
1887 # colon :, question-mark ?, asterisk *, space, or open bracket [
1888 # anywhere.
1890 # Additionally, % must be escaped because it is used for escaping
1891 # and we want our escaped refname to be reversible
1892 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1894 # no slash-separated component can begin with a dot .
1895 # /.* becomes /%2E*
1896 $refname =~ s{/\.}{/%2E}g;
1898 # It cannot have two consecutive dots .. anywhere
1899 # .. becomes %2E%2E
1900 $refname =~ s{\.\.}{%2E%2E}g;
1902 return $refname;
1905 sub desanitize_refname {
1906 my ($refname) = @_;
1907 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1908 return $refname;
1911 sub svm_uuid {
1912 my ($self) = @_;
1913 return $self->{svm}->{uuid} if $self->svm;
1914 $self->ra;
1915 unless ($self->{svm}) {
1916 die "SVM UUID not cached, and reading remotely failed\n";
1918 $self->{svm}->{uuid};
1921 sub svm {
1922 my ($self) = @_;
1923 return $self->{svm} if $self->{svm};
1924 my $svm;
1925 # see if we have it in our config, first:
1926 eval {
1927 my $section = "svn-remote.$self->{repo_id}";
1928 $svm = {
1929 source => tmp_config('--get', "$section.svm-source"),
1930 uuid => tmp_config('--get', "$section.svm-uuid"),
1931 replace => tmp_config('--get', "$section.svm-replace"),
1934 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1935 $self->{svm} = $svm;
1937 $self->{svm};
1940 sub _set_svm_vars {
1941 my ($self, $ra) = @_;
1942 return $ra if $self->svm;
1944 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1945 "(svm:source, svm:uuid) ",
1946 "from the following URLs:\n" );
1947 sub read_svm_props {
1948 my ($self, $ra, $path, $r) = @_;
1949 my $props = ($ra->get_dir($path, $r))[2];
1950 my $src = $props->{'svm:source'};
1951 my $uuid = $props->{'svm:uuid'};
1952 return undef if (!$src || !$uuid);
1954 chomp($src, $uuid);
1956 $uuid =~ m{^[0-9a-f\-]{30,}$}
1957 or die "doesn't look right - svm:uuid is '$uuid'\n";
1959 # the '!' is used to mark the repos_root!/relative/path
1960 $src =~ s{/?!/?}{/};
1961 $src =~ s{/+$}{}; # no trailing slashes please
1962 # username is of no interest
1963 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1965 my $replace = $ra->{url};
1966 $replace .= "/$path" if length $path;
1968 my $section = "svn-remote.$self->{repo_id}";
1969 tmp_config("$section.svm-source", $src);
1970 tmp_config("$section.svm-replace", $replace);
1971 tmp_config("$section.svm-uuid", $uuid);
1972 $self->{svm} = {
1973 source => $src,
1974 uuid => $uuid,
1975 replace => $replace
1979 my $r = $ra->get_latest_revnum;
1980 my $path = $self->{path};
1981 my %tried;
1982 while (length $path) {
1983 unless ($tried{"$self->{url}/$path"}) {
1984 return $ra if $self->read_svm_props($ra, $path, $r);
1985 $tried{"$self->{url}/$path"} = 1;
1987 $path =~ s#/?[^/]+$##;
1989 die "Path: '$path' should be ''\n" if $path ne '';
1990 return $ra if $self->read_svm_props($ra, $path, $r);
1991 $tried{"$self->{url}/$path"} = 1;
1993 if ($ra->{repos_root} eq $self->{url}) {
1994 die @err, (map { " $_\n" } keys %tried), "\n";
1997 # nope, make sure we're connected to the repository root:
1998 my $ok;
1999 my @tried_b;
2000 $path = $ra->{svn_path};
2001 $ra = Git::SVN::Ra->new($ra->{repos_root});
2002 while (length $path) {
2003 unless ($tried{"$ra->{url}/$path"}) {
2004 $ok = $self->read_svm_props($ra, $path, $r);
2005 last if $ok;
2006 $tried{"$ra->{url}/$path"} = 1;
2008 $path =~ s#/?[^/]+$##;
2010 die "Path: '$path' should be ''\n" if $path ne '';
2011 $ok ||= $self->read_svm_props($ra, $path, $r);
2012 $tried{"$ra->{url}/$path"} = 1;
2013 if (!$ok) {
2014 die @err, (map { " $_\n" } keys %tried), "\n";
2016 Git::SVN::Ra->new($self->{url});
2019 sub svnsync {
2020 my ($self) = @_;
2021 return $self->{svnsync} if $self->{svnsync};
2023 if ($self->no_metadata) {
2024 die "Can't have both 'noMetadata' and ",
2025 "'useSvnsyncProps' options set!\n";
2027 if ($self->rewrite_root) {
2028 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2029 "options set!\n";
2032 my $svnsync;
2033 # see if we have it in our config, first:
2034 eval {
2035 my $section = "svn-remote.$self->{repo_id}";
2037 my $url = tmp_config('--get', "$section.svnsync-url");
2038 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2039 die "doesn't look right - svn:sync-from-url is '$url'\n";
2041 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2042 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2043 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2045 $svnsync = { url => $url, uuid => $uuid }
2047 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2048 return $self->{svnsync} = $svnsync;
2051 my $err = "useSvnsyncProps set, but failed to read " .
2052 "svnsync property: svn:sync-from-";
2053 my $rp = $self->ra->rev_proplist(0);
2055 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2056 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2057 die "doesn't look right - svn:sync-from-url is '$url'\n";
2059 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2060 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2061 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2063 my $section = "svn-remote.$self->{repo_id}";
2064 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2065 tmp_config('--add', "$section.svnsync-url", $url);
2066 return $self->{svnsync} = { url => $url, uuid => $uuid };
2069 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2070 # remote lookup (useful for 'git svn log').
2071 sub ra_uuid {
2072 my ($self) = @_;
2073 unless ($self->{ra_uuid}) {
2074 my $key = "svn-remote.$self->{repo_id}.uuid";
2075 my $uuid = eval { tmp_config('--get', $key) };
2076 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2077 $self->{ra_uuid} = $uuid;
2078 } else {
2079 die "ra_uuid called without URL\n" unless $self->{url};
2080 $self->{ra_uuid} = $self->ra->get_uuid;
2081 tmp_config('--add', $key, $self->{ra_uuid});
2084 $self->{ra_uuid};
2087 sub _set_repos_root {
2088 my ($self, $repos_root) = @_;
2089 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2090 $repos_root ||= $self->ra->{repos_root};
2091 tmp_config($k, $repos_root);
2092 $repos_root;
2095 sub repos_root {
2096 my ($self) = @_;
2097 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2098 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2101 sub ra {
2102 my ($self) = shift;
2103 my $ra = Git::SVN::Ra->new($self->{url});
2104 $self->_set_repos_root($ra->{repos_root});
2105 if ($self->use_svm_props && !$self->{svm}) {
2106 if ($self->no_metadata) {
2107 die "Can't have both 'noMetadata' and ",
2108 "'useSvmProps' options set!\n";
2109 } elsif ($self->use_svnsync_props) {
2110 die "Can't have both 'useSvnsyncProps' and ",
2111 "'useSvmProps' options set!\n";
2113 $ra = $self->_set_svm_vars($ra);
2114 $self->{-want_revprops} = 1;
2116 $ra;
2119 sub rel_path {
2120 my ($self) = @_;
2121 my $repos_root = $self->ra->{repos_root};
2122 return $self->{path} if ($self->{url} eq $repos_root);
2123 my $url = $self->{url} .
2124 (length $self->{path} ? "/$self->{path}" : $self->{path});
2125 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2126 $url;
2129 # prop_walk(PATH, REV, SUB)
2130 # -------------------------
2131 # Recursively traverse PATH at revision REV and invoke SUB for each
2132 # directory that contains a SVN property. SUB will be invoked as
2133 # follows: &SUB(gs, path, props); where `gs' is this instance of
2134 # Git::SVN, `path' the path to the directory where the properties
2135 # `props' were found. The `path' will be relative to point of checkout,
2136 # that is, if url://repo/trunk is the current Git branch, and that
2137 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2138 # as `path' (note the trailing `/').
2139 sub prop_walk {
2140 my ($self, $path, $rev, $sub) = @_;
2142 $path =~ s#^/##;
2143 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2144 $path =~ s#^/*#/#g;
2145 my $p = $path;
2146 # Strip the irrelevant part of the path.
2147 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2148 # Ensure the path is terminated by a `/'.
2149 $p =~ s#/*$#/#;
2151 # The properties contain all the internal SVN stuff nobody
2152 # (usually) cares about.
2153 my $interesting_props = 0;
2154 foreach (keys %{$props}) {
2155 # If it doesn't start with `svn:', it must be a
2156 # user-defined property.
2157 ++$interesting_props and next if $_ !~ /^svn:/;
2158 # FIXME: Fragile, if SVN adds new public properties,
2159 # this needs to be updated.
2160 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2161 |eol-style|mime-type
2162 |externals|needs-lock)$/x;
2164 &$sub($self, $p, $props) if $interesting_props;
2166 foreach (sort keys %$dirent) {
2167 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2168 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2172 sub last_rev { ($_[0]->last_rev_commit)[0] }
2173 sub last_commit { ($_[0]->last_rev_commit)[1] }
2175 # returns the newest SVN revision number and newest commit SHA1
2176 sub last_rev_commit {
2177 my ($self) = @_;
2178 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2179 return ($self->{last_rev}, $self->{last_commit});
2181 my $c = ::verify_ref($self->refname.'^0');
2182 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2183 my $rev = (::cmt_metadata($c))[1];
2184 if (defined $rev) {
2185 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2186 return ($rev, $c);
2189 my $map_path = $self->map_path;
2190 unless (-e $map_path) {
2191 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2192 return (undef, undef);
2194 my ($rev, $commit) = $self->rev_map_max(1);
2195 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2196 return ($rev, $commit);
2199 sub get_fetch_range {
2200 my ($self, $min, $max) = @_;
2201 $max ||= $self->ra->get_latest_revnum;
2202 $min ||= $self->rev_map_max;
2203 (++$min, $max);
2206 sub tmp_config {
2207 my (@args) = @_;
2208 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2209 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2210 if (! -f $config && -f $old_def_config) {
2211 rename $old_def_config, $config or
2212 die "Failed rename $old_def_config => $config: $!\n";
2214 my $old_config = $ENV{GIT_CONFIG};
2215 $ENV{GIT_CONFIG} = $config;
2216 $@ = undef;
2217 my @ret = eval {
2218 unless (-f $config) {
2219 mkfile($config);
2220 open my $fh, '>', $config or
2221 die "Can't open $config: $!\n";
2222 print $fh "; This file is used internally by ",
2223 "git-svn\n" or die
2224 "Couldn't write to $config: $!\n";
2225 print $fh "; You should not have to edit it\n" or
2226 die "Couldn't write to $config: $!\n";
2227 close $fh or die "Couldn't close $config: $!\n";
2229 command('config', @args);
2231 my $err = $@;
2232 if (defined $old_config) {
2233 $ENV{GIT_CONFIG} = $old_config;
2234 } else {
2235 delete $ENV{GIT_CONFIG};
2237 die $err if $err;
2238 wantarray ? @ret : $ret[0];
2241 sub tmp_index_do {
2242 my ($self, $sub) = @_;
2243 my $old_index = $ENV{GIT_INDEX_FILE};
2244 $ENV{GIT_INDEX_FILE} = $self->{index};
2245 $@ = undef;
2246 my @ret = eval {
2247 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2248 mkpath([$dir]) unless -d $dir;
2249 &$sub;
2251 my $err = $@;
2252 if (defined $old_index) {
2253 $ENV{GIT_INDEX_FILE} = $old_index;
2254 } else {
2255 delete $ENV{GIT_INDEX_FILE};
2257 die $err if $err;
2258 wantarray ? @ret : $ret[0];
2261 sub assert_index_clean {
2262 my ($self, $treeish) = @_;
2264 $self->tmp_index_do(sub {
2265 command_noisy('read-tree', $treeish) unless -e $self->{index};
2266 my $x = command_oneline('write-tree');
2267 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2268 /^tree ($::sha1)/mo);
2269 return if $y eq $x;
2271 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2272 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2273 command_noisy('read-tree', $treeish);
2274 $x = command_oneline('write-tree');
2275 if ($y ne $x) {
2276 ::fatal "trees ($treeish) $y != $x\n",
2277 "Something is seriously wrong...";
2282 sub get_commit_parents {
2283 my ($self, $log_entry) = @_;
2284 my (%seen, @ret, @tmp);
2285 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2286 if (my $ip = $self->{inject_parents}) {
2287 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2288 push @tmp, $commit;
2291 if (my $cur = ::verify_ref($self->refname.'^0')) {
2292 push @tmp, $cur;
2294 if (my $ipd = $self->{inject_parents_dcommit}) {
2295 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2296 push @tmp, @$commit;
2299 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2300 while (my $p = shift @tmp) {
2301 next if $seen{$p};
2302 $seen{$p} = 1;
2303 push @ret, $p;
2304 # MAXPARENT is defined to 16 in commit-tree.c:
2305 last if @ret >= 16;
2307 if (@tmp) {
2308 die "r$log_entry->{revision}: No room for parents:\n\t",
2309 join("\n\t", @tmp), "\n";
2311 @ret;
2314 sub rewrite_root {
2315 my ($self) = @_;
2316 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2317 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2318 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2319 if ($rwr) {
2320 $rwr =~ s#/+$##;
2321 if ($rwr !~ m#^[a-z\+]+://#) {
2322 die "$rwr is not a valid URL (key: $k)\n";
2325 $self->{-rewrite_root} = $rwr;
2328 sub metadata_url {
2329 my ($self) = @_;
2330 ($self->rewrite_root || $self->{url}) .
2331 (length $self->{path} ? '/' . $self->{path} : '');
2334 sub full_url {
2335 my ($self) = @_;
2336 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2340 sub set_commit_header_env {
2341 my ($log_entry) = @_;
2342 my %env;
2343 foreach my $ned (qw/NAME EMAIL DATE/) {
2344 foreach my $ac (qw/AUTHOR COMMITTER/) {
2345 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2349 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2350 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2351 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2353 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2354 ? $log_entry->{commit_name}
2355 : $log_entry->{name};
2356 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2357 ? $log_entry->{commit_email}
2358 : $log_entry->{email};
2359 \%env;
2362 sub restore_commit_header_env {
2363 my ($env) = @_;
2364 foreach my $ned (qw/NAME EMAIL DATE/) {
2365 foreach my $ac (qw/AUTHOR COMMITTER/) {
2366 my $k = "GIT_${ac}_${ned}";
2367 if (defined $env->{$k}) {
2368 $ENV{$k} = $env->{$k};
2369 } else {
2370 delete $ENV{$k};
2376 sub gc {
2377 command_noisy('gc', '--auto');
2380 sub do_git_commit {
2381 my ($self, $log_entry) = @_;
2382 my $lr = $self->last_rev;
2383 if (defined $lr && $lr >= $log_entry->{revision}) {
2384 die "Last fetched revision of ", $self->refname,
2385 " was r$lr, but we are about to fetch: ",
2386 "r$log_entry->{revision}!\n";
2388 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2389 croak "$log_entry->{revision} = $c already exists! ",
2390 "Why are we refetching it?\n";
2392 my $old_env = set_commit_header_env($log_entry);
2393 my $tree = $log_entry->{tree};
2394 if (!defined $tree) {
2395 $tree = $self->tmp_index_do(sub {
2396 command_oneline('write-tree') });
2398 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2400 my @exec = ('git', 'commit-tree', $tree);
2401 foreach ($self->get_commit_parents($log_entry)) {
2402 push @exec, '-p', $_;
2404 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2405 or croak $!;
2406 binmode $msg_fh;
2408 # we always get UTF-8 from SVN, but we may want our commits in
2409 # a different encoding.
2410 if (my $enc = Git::config('i18n.commitencoding')) {
2411 require Encode;
2412 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2414 print $msg_fh $log_entry->{log} or croak $!;
2415 restore_commit_header_env($old_env);
2416 unless ($self->no_metadata) {
2417 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2418 or croak $!;
2420 $msg_fh->flush == 0 or croak $!;
2421 close $msg_fh or croak $!;
2422 chomp(my $commit = do { local $/; <$out_fh> });
2423 close $out_fh or croak $!;
2424 waitpid $pid, 0;
2425 croak $? if $?;
2426 if ($commit !~ /^$::sha1$/o) {
2427 die "Failed to commit, invalid sha1: $commit\n";
2430 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2432 $self->{last_rev} = $log_entry->{revision};
2433 $self->{last_commit} = $commit;
2434 print "r$log_entry->{revision}" unless $::_q > 1;
2435 if (defined $log_entry->{svm_revision}) {
2436 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2437 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2438 0, $self->svm_uuid);
2440 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2441 if (--$_gc_nr == 0) {
2442 $_gc_nr = $_gc_period;
2443 gc();
2445 return $commit;
2448 sub match_paths {
2449 my ($self, $paths, $r) = @_;
2450 return 1 if $self->{path} eq '';
2451 if (my $path = $paths->{"/$self->{path}"}) {
2452 return ($path->{action} eq 'D') ? 0 : 1;
2454 my $repos_root = $self->ra->{repos_root};
2455 my $extended_path = $self->{url} . '/' . $self->{path};
2456 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2457 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2458 if (grep /$self->{path_regex}/, keys %$paths) {
2459 return 1;
2461 my $c = '';
2462 foreach (split m#/#, $self->{path}) {
2463 $c .= "/$_";
2464 next unless ($paths->{$c} &&
2465 ($paths->{$c}->{action} =~ /^[AR]$/));
2466 if ($self->ra->check_path($self->{path}, $r) ==
2467 $SVN::Node::dir) {
2468 return 1;
2471 return 0;
2474 sub find_parent_branch {
2475 my ($self, $paths, $rev) = @_;
2476 return undef unless $self->follow_parent;
2477 unless (defined $paths) {
2478 my $err_handler = $SVN::Error::handler;
2479 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2480 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2481 $paths =
2482 Git::SVN::Ra::dup_changed_paths($_[0]) });
2483 $SVN::Error::handler = $err_handler;
2485 return undef unless defined $paths;
2487 # look for a parent from another branch:
2488 my @b_path_components = split m#/#, $self->rel_path;
2489 my @a_path_components;
2490 my $i;
2491 while (@b_path_components) {
2492 $i = $paths->{'/'.join('/', @b_path_components)};
2493 last if $i && defined $i->{copyfrom_path};
2494 unshift(@a_path_components, pop(@b_path_components));
2496 return undef unless defined $i && defined $i->{copyfrom_path};
2497 my $branch_from = $i->{copyfrom_path};
2498 if (@a_path_components) {
2499 print STDERR "branch_from: $branch_from => ";
2500 $branch_from .= '/'.join('/', @a_path_components);
2501 print STDERR $branch_from, "\n";
2503 my $r = $i->{copyfrom_rev};
2504 my $repos_root = $self->ra->{repos_root};
2505 my $url = $self->ra->{url};
2506 my $new_url = $repos_root . $branch_from;
2507 print STDERR "Found possible branch point: ",
2508 "$new_url => ", $self->full_url, ", $r\n";
2509 $branch_from =~ s#^/##;
2510 my $gs = $self->other_gs($new_url, $url, $repos_root,
2511 $branch_from, $r, $self->{ref_id});
2512 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2514 my ($base, $head);
2515 if (!defined $r0 || !defined $parent) {
2516 ($base, $head) = parse_revision_argument(0, $r);
2517 } else {
2518 if ($r0 < $r) {
2519 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2520 0, 1, sub { $base = $_[1] - 1 });
2523 if (defined $base && $base <= $r) {
2524 $gs->fetch($base, $r);
2526 ($r0, $parent) = $gs->find_rev_before($r, 1);
2528 if (defined $r0 && defined $parent) {
2529 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2530 my $ed;
2531 if ($self->ra->can_do_switch) {
2532 $self->assert_index_clean($parent);
2533 print STDERR "Following parent with do_switch\n";
2534 # do_switch works with svn/trunk >= r22312, but that
2535 # is not included with SVN 1.4.3 (the latest version
2536 # at the moment), so we can't rely on it
2537 $self->{last_rev} = $r0;
2538 $self->{last_commit} = $parent;
2539 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2540 $gs->ra->gs_do_switch($r0, $rev, $gs,
2541 $self->full_url, $ed)
2542 or die "SVN connection failed somewhere...\n";
2543 } elsif ($self->ra->trees_match($new_url, $r0,
2544 $self->full_url, $rev)) {
2545 print STDERR "Trees match:\n",
2546 " $new_url\@$r0\n",
2547 " ${\$self->full_url}\@$rev\n",
2548 "Following parent with no changes\n";
2549 $self->tmp_index_do(sub {
2550 command_noisy('read-tree', $parent);
2552 $self->{last_commit} = $parent;
2553 } else {
2554 print STDERR "Following parent with do_update\n";
2555 $ed = SVN::Git::Fetcher->new($self);
2556 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2557 or die "SVN connection failed somewhere...\n";
2559 print STDERR "Successfully followed parent\n";
2560 return $self->make_log_entry($rev, [$parent], $ed);
2562 return undef;
2565 sub do_fetch {
2566 my ($self, $paths, $rev) = @_;
2567 my $ed;
2568 my ($last_rev, @parents);
2569 if (my $lc = $self->last_commit) {
2570 # we can have a branch that was deleted, then re-added
2571 # under the same name but copied from another path, in
2572 # which case we'll have multiple parents (we don't
2573 # want to break the original ref, nor lose copypath info):
2574 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2575 push @{$log_entry->{parents}}, $lc;
2576 return $log_entry;
2578 $ed = SVN::Git::Fetcher->new($self);
2579 $last_rev = $self->{last_rev};
2580 $ed->{c} = $lc;
2581 @parents = ($lc);
2582 } else {
2583 $last_rev = $rev;
2584 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2585 return $log_entry;
2587 $ed = SVN::Git::Fetcher->new($self);
2589 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2590 die "SVN connection failed somewhere...\n";
2592 $self->make_log_entry($rev, \@parents, $ed);
2595 sub get_untracked {
2596 my ($self, $ed) = @_;
2597 my @out;
2598 my $h = $ed->{empty};
2599 foreach (sort keys %$h) {
2600 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2601 push @out, " $act: " . uri_encode($_);
2602 warn "W: $act: $_\n";
2604 foreach my $t (qw/dir_prop file_prop/) {
2605 $h = $ed->{$t} or next;
2606 foreach my $path (sort keys %$h) {
2607 my $ppath = $path eq '' ? '.' : $path;
2608 foreach my $prop (sort keys %{$h->{$path}}) {
2609 next if $SKIP_PROP{$prop};
2610 my $v = $h->{$path}->{$prop};
2611 my $t_ppath_prop = "$t: " .
2612 uri_encode($ppath) . ' ' .
2613 uri_encode($prop);
2614 if (defined $v) {
2615 push @out, " +$t_ppath_prop " .
2616 uri_encode($v);
2617 } else {
2618 push @out, " -$t_ppath_prop";
2623 foreach my $t (qw/absent_file absent_directory/) {
2624 $h = $ed->{$t} or next;
2625 foreach my $parent (sort keys %$h) {
2626 foreach my $path (sort @{$h->{$parent}}) {
2627 push @out, " $t: " .
2628 uri_encode("$parent/$path");
2629 warn "W: $t: $parent/$path ",
2630 "Insufficient permissions?\n";
2634 \@out;
2637 # parse_svn_date(DATE)
2638 # --------------------
2639 # Given a date (in UTC) from Subversion, return a string in the format
2640 # "<TZ Offset> <local date/time>" that Git will use.
2642 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2643 # is true we'll convert it to the local timezone instead.
2644 sub parse_svn_date {
2645 my $date = shift || return '+0000 1970-01-01 00:00:00';
2646 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2647 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2648 croak "Unable to parse date: $date\n";
2649 my $parsed_date; # Set next.
2651 if ($Git::SVN::_localtime) {
2652 # Translate the Subversion datetime to an epoch time.
2653 # Begin by switching ourselves to $date's timezone, UTC.
2654 my $old_env_TZ = $ENV{TZ};
2655 $ENV{TZ} = 'UTC';
2657 my $epoch_in_UTC =
2658 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2660 # Determine our local timezone (including DST) at the
2661 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2662 # value of TZ, if any, at the time we were run.
2663 if (defined $Git::SVN::Log::TZ) {
2664 $ENV{TZ} = $Git::SVN::Log::TZ;
2665 } else {
2666 delete $ENV{TZ};
2669 my $our_TZ =
2670 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2672 # This converts $epoch_in_UTC into our local timezone.
2673 my ($sec, $min, $hour, $mday, $mon, $year,
2674 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2676 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2677 $our_TZ, $year + 1900, $mon + 1,
2678 $mday, $hour, $min, $sec);
2680 # Reset us to the timezone in effect when we entered
2681 # this routine.
2682 if (defined $old_env_TZ) {
2683 $ENV{TZ} = $old_env_TZ;
2684 } else {
2685 delete $ENV{TZ};
2687 } else {
2688 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2691 return $parsed_date;
2694 sub other_gs {
2695 my ($self, $new_url, $url, $repos_root,
2696 $branch_from, $r, $old_ref_id) = @_;
2697 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2698 unless ($gs) {
2699 my $ref_id = $old_ref_id;
2700 $ref_id =~ s/\@\d+$//;
2701 $ref_id .= "\@$r";
2702 # just grow a tail if we're not unique enough :x
2703 $ref_id .= '-' while find_ref($ref_id);
2704 print STDERR "Initializing parent: $ref_id\n";
2705 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2706 if ($u =~ s#^\Q$url\E(/|$)##) {
2707 $p = $u;
2708 $u = $url;
2709 $repo_id = $self->{repo_id};
2711 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2716 sub call_authors_prog {
2717 my ($orig_author) = @_;
2718 my $author = `$::_authors_prog $orig_author`;
2719 if ($? != 0) {
2720 die "$::_authors_prog failed with exit code $?\n"
2722 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2723 my ($name, $email) = ($1, $2);
2724 $email = undef if length $2 == 0;
2725 return [$name, $email];
2726 } else {
2727 die "Author: $orig_author: $::_authors_prog returned "
2728 . "invalid author format: $author\n";
2732 sub check_author {
2733 my ($author) = @_;
2734 if (!defined $author || length $author == 0) {
2735 $author = '(no author)';
2737 if (!defined $::users{$author}) {
2738 if (defined $::_authors_prog) {
2739 $::users{$author} = call_authors_prog($author);
2740 } elsif (defined $::_authors) {
2741 die "Author: $author not defined in $::_authors file\n";
2744 $author;
2747 sub make_log_entry {
2748 my ($self, $rev, $parents, $ed) = @_;
2749 my $untracked = $self->get_untracked($ed);
2751 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2752 print $un "r$rev\n" or croak $!;
2753 print $un $_, "\n" foreach @$untracked;
2754 my %log_entry = ( parents => $parents || [], revision => $rev,
2755 log => '');
2757 my $headrev;
2758 my $logged = delete $self->{logged_rev_props};
2759 if (!$logged || $self->{-want_revprops}) {
2760 my $rp = $self->ra->rev_proplist($rev);
2761 foreach (sort keys %$rp) {
2762 my $v = $rp->{$_};
2763 if (/^svn:(author|date|log)$/) {
2764 $log_entry{$1} = $v;
2765 } elsif ($_ eq 'svm:headrev') {
2766 $headrev = $v;
2767 } else {
2768 print $un " rev_prop: ", uri_encode($_), ' ',
2769 uri_encode($v), "\n";
2772 } else {
2773 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2775 close $un or croak $!;
2777 $log_entry{date} = parse_svn_date($log_entry{date});
2778 $log_entry{log} .= "\n";
2779 my $author = $log_entry{author} = check_author($log_entry{author});
2780 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2781 : ($author, undef);
2783 my ($commit_name, $commit_email) = ($name, $email);
2784 if ($_use_log_author) {
2785 my $name_field;
2786 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2787 $name_field = $1;
2788 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2789 $name_field = $1;
2791 if (!defined $name_field) {
2792 if (!defined $email) {
2793 $email = $name;
2795 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2796 ($name, $email) = ($1, $2);
2797 } elsif ($name_field =~ /(.*)@/) {
2798 ($name, $email) = ($1, $name_field);
2799 } else {
2800 ($name, $email) = ($name_field, $name_field);
2803 if (defined $headrev && $self->use_svm_props) {
2804 if ($self->rewrite_root) {
2805 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2806 "options set!\n";
2808 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2809 # we don't want "SVM: initializing mirror for junk" ...
2810 return undef if $r == 0;
2811 my $svm = $self->svm;
2812 if ($uuid ne $svm->{uuid}) {
2813 die "UUID mismatch on SVM path:\n",
2814 "expected: $svm->{uuid}\n",
2815 " got: $uuid\n";
2817 my $full_url = $self->full_url;
2818 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2819 die "Failed to replace '$svm->{replace}' with ",
2820 "'$svm->{source}' in $full_url\n";
2821 # throw away username for storing in records
2822 remove_username($full_url);
2823 $log_entry{metadata} = "$full_url\@$r $uuid";
2824 $log_entry{svm_revision} = $r;
2825 $email ||= "$author\@$uuid";
2826 $commit_email ||= "$author\@$uuid";
2827 } elsif ($self->use_svnsync_props) {
2828 my $full_url = $self->svnsync->{url};
2829 $full_url .= "/$self->{path}" if length $self->{path};
2830 remove_username($full_url);
2831 my $uuid = $self->svnsync->{uuid};
2832 $log_entry{metadata} = "$full_url\@$rev $uuid";
2833 $email ||= "$author\@$uuid";
2834 $commit_email ||= "$author\@$uuid";
2835 } else {
2836 my $url = $self->metadata_url;
2837 remove_username($url);
2838 $log_entry{metadata} = "$url\@$rev " .
2839 $self->ra->get_uuid;
2840 $email ||= "$author\@" . $self->ra->get_uuid;
2841 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2843 $log_entry{name} = $name;
2844 $log_entry{email} = $email;
2845 $log_entry{commit_name} = $commit_name;
2846 $log_entry{commit_email} = $commit_email;
2847 \%log_entry;
2850 sub fetch {
2851 my ($self, $min_rev, $max_rev, @parents) = @_;
2852 my ($last_rev, $last_commit) = $self->last_rev_commit;
2853 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2854 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2857 sub set_tree_cb {
2858 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2859 $self->{inject_parents} = { $rev => $tree };
2860 $self->fetch(undef, undef);
2863 sub set_tree {
2864 my ($self, $tree) = (shift, shift);
2865 my $log_entry = ::get_commit_entry($tree);
2866 unless ($self->{last_rev}) {
2867 ::fatal("Must have an existing revision to commit");
2869 my %ed_opts = ( r => $self->{last_rev},
2870 log => $log_entry->{log},
2871 ra => $self->ra,
2872 tree_a => $self->{last_commit},
2873 tree_b => $tree,
2874 editor_cb => sub {
2875 $self->set_tree_cb($log_entry, $tree, @_) },
2876 svn_path => $self->{path} );
2877 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2878 print "No changes\nr$self->{last_rev} = $tree\n";
2882 sub rebuild_from_rev_db {
2883 my ($self, $path) = @_;
2884 my $r = -1;
2885 open my $fh, '<', $path or croak "open: $!";
2886 binmode $fh or croak "binmode: $!";
2887 while (<$fh>) {
2888 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2889 chomp($_);
2890 ++$r;
2891 next if $_ eq ('0' x 40);
2892 $self->rev_map_set($r, $_);
2893 print "r$r = $_\n";
2895 close $fh or croak "close: $!";
2896 unlink $path or croak "unlink: $!";
2899 sub rebuild {
2900 my ($self) = @_;
2901 my $map_path = $self->map_path;
2902 my $partial = (-e $map_path && ! -z $map_path);
2903 return unless ::verify_ref($self->refname.'^0');
2904 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2905 my $rev_db = $self->rev_db_path;
2906 $self->rebuild_from_rev_db($rev_db);
2907 if ($self->use_svm_props) {
2908 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2909 $self->rebuild_from_rev_db($svm_rev_db);
2911 $self->unlink_rev_db_symlink;
2912 return;
2914 print "Rebuilding $map_path ...\n" if (!$partial);
2915 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2916 (undef, undef));
2917 my ($log, $ctx) =
2918 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2919 ($head ? "$head.." : "") . $self->refname,
2920 '--');
2921 my $metadata_url = $self->metadata_url;
2922 remove_username($metadata_url);
2923 my $svn_uuid = $self->ra_uuid;
2924 my $c;
2925 while (<$log>) {
2926 if ( m{^commit ($::sha1)$} ) {
2927 $c = $1;
2928 next;
2930 next unless s{^\s*(git-svn-id:)}{$1};
2931 my ($url, $rev, $uuid) = ::extract_metadata($_);
2932 remove_username($url);
2934 # ignore merges (from set-tree)
2935 next if (!defined $rev || !$uuid);
2937 # if we merged or otherwise started elsewhere, this is
2938 # how we break out of it
2939 if (($uuid ne $svn_uuid) ||
2940 ($metadata_url && $url && ($url ne $metadata_url))) {
2941 next;
2943 if ($partial && $head) {
2944 print "Partial-rebuilding $map_path ...\n";
2945 print "Currently at $base_rev = $head\n";
2946 $head = undef;
2949 $self->rev_map_set($rev, $c);
2950 print "r$rev = $c\n";
2952 command_close_pipe($log, $ctx);
2953 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2954 my $rev_db_path = $self->rev_db_path;
2955 if (-f $self->rev_db_path) {
2956 unlink $self->rev_db_path or croak "unlink: $!";
2958 $self->unlink_rev_db_symlink;
2961 # rev_map:
2962 # Tie::File seems to be prone to offset errors if revisions get sparse,
2963 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2964 # one of my favorite modules is out :< Next up would be one of the DBM
2965 # modules, but I'm not sure which is most portable...
2967 # This is the replacement for the rev_db format, which was too big
2968 # and inefficient for large repositories with a lot of sparse history
2969 # (mainly tags)
2971 # The format is this:
2972 # - 24 bytes for every record,
2973 # * 4 bytes for the integer representing an SVN revision number
2974 # * 20 bytes representing the sha1 of a git commit
2975 # - No empty padding records like the old format
2976 # (except the last record, which can be overwritten)
2977 # - new records are written append-only since SVN revision numbers
2978 # increase monotonically
2979 # - lookups on SVN revision number are done via a binary search
2980 # - Piping the file to xxd -c24 is a good way of dumping it for
2981 # viewing or editing (piped back through xxd -r), should the need
2982 # ever arise.
2983 # - The last record can be padding revision with an all-zero sha1
2984 # This is used to optimize fetch performance when using multiple
2985 # "fetch" directives in .git/config
2987 # These files are disposable unless noMetadata or useSvmProps is set
2989 sub _rev_map_set {
2990 my ($fh, $rev, $commit) = @_;
2992 binmode $fh or croak "binmode: $!";
2993 my $size = (stat($fh))[7];
2994 ($size % 24) == 0 or croak "inconsistent size: $size";
2996 my $wr_offset = 0;
2997 if ($size > 0) {
2998 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2999 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3000 $read == 24 or croak "read only $read bytes (!= 24)";
3001 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3002 if ($last_commit eq ('0' x40)) {
3003 if ($size >= 48) {
3004 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3005 $read = sysread($fh, $buf, 24) or
3006 croak "read: $!";
3007 $read == 24 or
3008 croak "read only $read bytes (!= 24)";
3009 ($last_rev, $last_commit) =
3010 unpack(rev_map_fmt, $buf);
3011 if ($last_commit eq ('0' x40)) {
3012 croak "inconsistent .rev_map\n";
3015 if ($last_rev >= $rev) {
3016 croak "last_rev is higher!: $last_rev >= $rev";
3018 $wr_offset = -24;
3021 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3022 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3023 croak "write: $!";
3026 sub mkfile {
3027 my ($path) = @_;
3028 unless (-e $path) {
3029 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3030 mkpath([$dir]) unless -d $dir;
3031 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3032 close $fh or die "Couldn't close (create) $path: $!\n";
3036 sub rev_map_set {
3037 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3038 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3039 my $db = $self->map_path($uuid);
3040 my $db_lock = "$db.lock";
3041 my $sig;
3042 if ($update_ref) {
3043 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3044 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3046 mkfile($db);
3048 $LOCKFILES{$db_lock} = 1;
3049 my $sync;
3050 # both of these options make our .rev_db file very, very important
3051 # and we can't afford to lose it because rebuild() won't work
3052 if ($self->use_svm_props || $self->no_metadata) {
3053 $sync = 1;
3054 copy($db, $db_lock) or die "rev_map_set(@_): ",
3055 "Failed to copy: ",
3056 "$db => $db_lock ($!)\n";
3057 } else {
3058 rename $db, $db_lock or die "rev_map_set(@_): ",
3059 "Failed to rename: ",
3060 "$db => $db_lock ($!)\n";
3063 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3064 or croak "Couldn't open $db_lock: $!\n";
3065 _rev_map_set($fh, $rev, $commit);
3066 if ($sync) {
3067 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3068 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3070 close $fh or croak $!;
3071 if ($update_ref) {
3072 $_head = $self;
3073 command_noisy('update-ref', '-m', "r$rev",
3074 $self->refname, $commit);
3076 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3077 "$db_lock => $db ($!)\n";
3078 delete $LOCKFILES{$db_lock};
3079 if ($update_ref) {
3080 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3081 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3082 kill $sig, $$ if defined $sig;
3086 # If want_commit, this will return an array of (rev, commit) where
3087 # commit _must_ be a valid commit in the archive.
3088 # Otherwise, it'll return the max revision (whether or not the
3089 # commit is valid or just a 0x40 placeholder).
3090 sub rev_map_max {
3091 my ($self, $want_commit) = @_;
3092 $self->rebuild;
3093 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3094 $want_commit ? ($r, $c) : $r;
3097 sub rev_map_max_norebuild {
3098 my ($self, $want_commit) = @_;
3099 my $map_path = $self->map_path;
3100 stat $map_path or return $want_commit ? (0, undef) : 0;
3101 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3102 binmode $fh or croak "binmode: $!";
3103 my $size = (stat($fh))[7];
3104 ($size % 24) == 0 or croak "inconsistent size: $size";
3106 if ($size == 0) {
3107 close $fh or croak "close: $!";
3108 return $want_commit ? (0, undef) : 0;
3111 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3112 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3113 my ($r, $c) = unpack(rev_map_fmt, $buf);
3114 if ($want_commit && $c eq ('0' x40)) {
3115 if ($size < 48) {
3116 return $want_commit ? (0, undef) : 0;
3118 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3119 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3120 ($r, $c) = unpack(rev_map_fmt, $buf);
3121 if ($c eq ('0'x40)) {
3122 croak "Penultimate record is all-zeroes in $map_path";
3125 close $fh or croak "close: $!";
3126 $want_commit ? ($r, $c) : $r;
3129 sub rev_map_get {
3130 my ($self, $rev, $uuid) = @_;
3131 my $map_path = $self->map_path($uuid);
3132 return undef unless -e $map_path;
3134 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3135 binmode $fh or croak "binmode: $!";
3136 my $size = (stat($fh))[7];
3137 ($size % 24) == 0 or croak "inconsistent size: $size";
3139 if ($size == 0) {
3140 close $fh or croak "close: $fh";
3141 return undef;
3144 my ($l, $u) = (0, $size - 24);
3145 my ($r, $c, $buf);
3147 while ($l <= $u) {
3148 my $i = int(($l/24 + $u/24) / 2) * 24;
3149 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3150 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3151 my ($r, $c) = unpack('NH40', $buf);
3153 if ($r < $rev) {
3154 $l = $i + 24;
3155 } elsif ($r > $rev) {
3156 $u = $i - 24;
3157 } else { # $r == $rev
3158 close($fh) or croak "close: $!";
3159 return $c eq ('0' x 40) ? undef : $c;
3162 close($fh) or croak "close: $!";
3163 undef;
3166 # Finds the first svn revision that exists on (if $eq_ok is true) or
3167 # before $rev for the current branch. It will not search any lower
3168 # than $min_rev. Returns the git commit hash and svn revision number
3169 # if found, else (undef, undef).
3170 sub find_rev_before {
3171 my ($self, $rev, $eq_ok, $min_rev) = @_;
3172 --$rev unless $eq_ok;
3173 $min_rev ||= 1;
3174 my $max_rev = $self->rev_map_max;
3175 $rev = $max_rev if ($rev > $max_rev);
3176 while ($rev >= $min_rev) {
3177 if (my $c = $self->rev_map_get($rev)) {
3178 return ($rev, $c);
3180 --$rev;
3182 return (undef, undef);
3185 # Finds the first svn revision that exists on (if $eq_ok is true) or
3186 # after $rev for the current branch. It will not search any higher
3187 # than $max_rev. Returns the git commit hash and svn revision number
3188 # if found, else (undef, undef).
3189 sub find_rev_after {
3190 my ($self, $rev, $eq_ok, $max_rev) = @_;
3191 ++$rev unless $eq_ok;
3192 $max_rev ||= $self->rev_map_max;
3193 while ($rev <= $max_rev) {
3194 if (my $c = $self->rev_map_get($rev)) {
3195 return ($rev, $c);
3197 ++$rev;
3199 return (undef, undef);
3202 sub _new {
3203 my ($class, $repo_id, $ref_id, $path) = @_;
3204 unless (defined $repo_id && length $repo_id) {
3205 $repo_id = $Git::SVN::default_repo_id;
3207 unless (defined $ref_id && length $ref_id) {
3208 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3210 $_[1] = $repo_id;
3211 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3212 $_[3] = $path = '' unless (defined $path);
3213 mkpath(["$ENV{GIT_DIR}/svn"]);
3214 bless {
3215 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3216 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3217 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3220 # for read-only access of old .rev_db formats
3221 sub unlink_rev_db_symlink {
3222 my ($self) = @_;
3223 my $link = $self->rev_db_path;
3224 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3225 if (-l $link) {
3226 unlink $link or croak "unlink: $link failed!";
3230 sub rev_db_path {
3231 my ($self, $uuid) = @_;
3232 my $db_path = $self->map_path($uuid);
3233 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3234 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3235 $db_path;
3238 # the new replacement for .rev_db
3239 sub map_path {
3240 my ($self, $uuid) = @_;
3241 $uuid ||= $self->ra_uuid;
3242 "$self->{map_root}.$uuid";
3245 sub uri_encode {
3246 my ($f) = @_;
3247 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3251 sub remove_username {
3252 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3255 package Git::SVN::Prompt;
3256 use strict;
3257 use warnings;
3258 require SVN::Core;
3259 use vars qw/$_no_auth_cache $_username/;
3261 sub simple {
3262 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3263 $may_save = undef if $_no_auth_cache;
3264 $default_username = $_username if defined $_username;
3265 if (defined $default_username && length $default_username) {
3266 if (defined $realm && length $realm) {
3267 print STDERR "Authentication realm: $realm\n";
3268 STDERR->flush;
3270 $cred->username($default_username);
3271 } else {
3272 username($cred, $realm, $may_save, $pool);
3274 $cred->password(_read_password("Password for '" .
3275 $cred->username . "': ", $realm));
3276 $cred->may_save($may_save);
3277 $SVN::_Core::SVN_NO_ERROR;
3280 sub ssl_server_trust {
3281 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3282 $may_save = undef if $_no_auth_cache;
3283 print STDERR "Error validating server certificate for '$realm':\n";
3285 no warnings 'once';
3286 # All variables SVN::Auth::SSL::* are used only once,
3287 # so we're shutting up Perl warnings about this.
3288 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3289 print STDERR " - The certificate is not issued ",
3290 "by a trusted authority. Use the\n",
3291 " fingerprint to validate ",
3292 "the certificate manually!\n";
3294 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3295 print STDERR " - The certificate hostname ",
3296 "does not match.\n";
3298 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3299 print STDERR " - The certificate is not yet valid.\n";
3301 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3302 print STDERR " - The certificate has expired.\n";
3304 if ($failures & $SVN::Auth::SSL::OTHER) {
3305 print STDERR " - The certificate has ",
3306 "an unknown error.\n";
3308 } # no warnings 'once'
3309 printf STDERR
3310 "Certificate information:\n".
3311 " - Hostname: %s\n".
3312 " - Valid: from %s until %s\n".
3313 " - Issuer: %s\n".
3314 " - Fingerprint: %s\n",
3315 map $cert_info->$_, qw(hostname valid_from valid_until
3316 issuer_dname fingerprint);
3317 my $choice;
3318 prompt:
3319 print STDERR $may_save ?
3320 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3321 "(R)eject or accept (t)emporarily? ";
3322 STDERR->flush;
3323 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3324 if ($choice =~ /^t$/i) {
3325 $cred->may_save(undef);
3326 } elsif ($choice =~ /^r$/i) {
3327 return -1;
3328 } elsif ($may_save && $choice =~ /^p$/i) {
3329 $cred->may_save($may_save);
3330 } else {
3331 goto prompt;
3333 $cred->accepted_failures($failures);
3334 $SVN::_Core::SVN_NO_ERROR;
3337 sub ssl_client_cert {
3338 my ($cred, $realm, $may_save, $pool) = @_;
3339 $may_save = undef if $_no_auth_cache;
3340 print STDERR "Client certificate filename: ";
3341 STDERR->flush;
3342 chomp(my $filename = <STDIN>);
3343 $cred->cert_file($filename);
3344 $cred->may_save($may_save);
3345 $SVN::_Core::SVN_NO_ERROR;
3348 sub ssl_client_cert_pw {
3349 my ($cred, $realm, $may_save, $pool) = @_;
3350 $may_save = undef if $_no_auth_cache;
3351 $cred->password(_read_password("Password: ", $realm));
3352 $cred->may_save($may_save);
3353 $SVN::_Core::SVN_NO_ERROR;
3356 sub username {
3357 my ($cred, $realm, $may_save, $pool) = @_;
3358 $may_save = undef if $_no_auth_cache;
3359 if (defined $realm && length $realm) {
3360 print STDERR "Authentication realm: $realm\n";
3362 my $username;
3363 if (defined $_username) {
3364 $username = $_username;
3365 } else {
3366 print STDERR "Username: ";
3367 STDERR->flush;
3368 chomp($username = <STDIN>);
3370 $cred->username($username);
3371 $cred->may_save($may_save);
3372 $SVN::_Core::SVN_NO_ERROR;
3375 sub _read_password {
3376 my ($prompt, $realm) = @_;
3377 print STDERR $prompt;
3378 STDERR->flush;
3379 require Term::ReadKey;
3380 Term::ReadKey::ReadMode('noecho');
3381 my $password = '';
3382 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3383 last if $key =~ /[\012\015]/; # \n\r
3384 $password .= $key;
3386 Term::ReadKey::ReadMode('restore');
3387 print STDERR "\n";
3388 STDERR->flush;
3389 $password;
3392 package SVN::Git::Fetcher;
3393 use vars qw/@ISA/;
3394 use strict;
3395 use warnings;
3396 use Carp qw/croak/;
3397 use File::Temp qw/tempfile/;
3398 use IO::File qw//;
3399 use vars qw/$_ignore_regex/;
3401 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3402 sub new {
3403 my ($class, $git_svn, $switch_path) = @_;
3404 my $self = SVN::Delta::Editor->new;
3405 bless $self, $class;
3406 if (exists $git_svn->{last_commit}) {
3407 $self->{c} = $git_svn->{last_commit};
3408 $self->{empty_symlinks} =
3409 _mark_empty_symlinks($git_svn, $switch_path);
3411 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3412 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3413 $self->{empty} = {};
3414 $self->{dir_prop} = {};
3415 $self->{file_prop} = {};
3416 $self->{absent_dir} = {};
3417 $self->{absent_file} = {};
3418 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3419 $self;
3422 # this uses the Ra object, so it must be called before do_{switch,update},
3423 # not inside them (when the Git::SVN::Fetcher object is passed) to
3424 # do_{switch,update}
3425 sub _mark_empty_symlinks {
3426 my ($git_svn, $switch_path) = @_;
3427 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3428 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3430 my %ret;
3431 my ($rev, $cmt) = $git_svn->last_rev_commit;
3432 return {} unless ($rev && $cmt);
3434 # allow the warning to be printed for each revision we fetch to
3435 # ensure the user sees it. The user can also disable the workaround
3436 # on the repository even while git svn is running and the next
3437 # revision fetched will skip this expensive function.
3438 my $printed_warning;
3439 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3440 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3441 local $/ = "\0";
3442 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3443 $pfx .= '/' if length($pfx);
3444 while (<$ls>) {
3445 chomp;
3446 s/\A100644 blob $empty_blob\t//o or next;
3447 unless ($printed_warning) {
3448 print STDERR "Scanning for empty symlinks, ",
3449 "this may take a while if you have ",
3450 "many empty files\n",
3451 "You may disable this with `",
3452 "git config svn.brokenSymlinkWorkaround ",
3453 "false'.\n",
3454 "This may be done in a different ",
3455 "terminal without restarting ",
3456 "git svn\n";
3457 $printed_warning = 1;
3459 my $path = $_;
3460 my (undef, $props) =
3461 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3462 if ($props->{'svn:special'}) {
3463 $ret{$path} = 1;
3466 command_close_pipe($ls, $ctx);
3467 \%ret;
3470 # returns true if a given path is inside a ".git" directory
3471 sub in_dot_git {
3472 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3475 # return value: 0 -- don't ignore, 1 -- ignore
3476 sub is_path_ignored {
3477 my ($self, $path) = @_;
3478 return 1 if in_dot_git($path);
3479 return 1 if defined($self->{ignore_regex}) &&
3480 $path =~ m!$self->{ignore_regex}!;
3481 return 0 unless defined($_ignore_regex);
3482 return 1 if $path =~ m!$_ignore_regex!o;
3483 return 0;
3486 sub set_path_strip {
3487 my ($self, $path) = @_;
3488 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3491 sub open_root {
3492 { path => '' };
3495 sub open_directory {
3496 my ($self, $path, $pb, $rev) = @_;
3497 { path => $path };
3500 sub git_path {
3501 my ($self, $path) = @_;
3502 if ($self->{path_strip}) {
3503 $path =~ s!$self->{path_strip}!! or
3504 die "Failed to strip path '$path' ($self->{path_strip})\n";
3506 $path;
3509 sub delete_entry {
3510 my ($self, $path, $rev, $pb) = @_;
3511 return undef if $self->is_path_ignored($path);
3513 my $gpath = $self->git_path($path);
3514 return undef if ($gpath eq '');
3516 # remove entire directories.
3517 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3518 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3519 if ($tree) {
3520 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3521 -r --name-only -z/,
3522 $tree);
3523 local $/ = "\0";
3524 while (<$ls>) {
3525 chomp;
3526 my $rmpath = "$gpath/$_";
3527 $self->{gii}->remove($rmpath);
3528 print "\tD\t$rmpath\n" unless $::_q;
3530 print "\tD\t$gpath/\n" unless $::_q;
3531 command_close_pipe($ls, $ctx);
3532 $self->{empty}->{$path} = 0
3533 } else {
3534 $self->{gii}->remove($gpath);
3535 print "\tD\t$gpath\n" unless $::_q;
3537 undef;
3540 sub open_file {
3541 my ($self, $path, $pb, $rev) = @_;
3542 my ($mode, $blob);
3544 goto out if $self->is_path_ignored($path);
3546 my $gpath = $self->git_path($path);
3547 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3548 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3549 unless (defined $mode && defined $blob) {
3550 die "$path was not found in commit $self->{c} (r$rev)\n";
3552 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3553 $mode = '120000';
3555 out:
3556 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3557 pool => SVN::Pool->new, action => 'M' };
3560 sub add_file {
3561 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3562 my $mode;
3564 if (!$self->is_path_ignored($path)) {
3565 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3566 delete $self->{empty}->{$dir};
3567 $mode = '100644';
3569 { path => $path, mode_a => $mode, mode_b => $mode,
3570 pool => SVN::Pool->new, action => 'A' };
3573 sub add_directory {
3574 my ($self, $path, $cp_path, $cp_rev) = @_;
3575 goto out if $self->is_path_ignored($path);
3576 my $gpath = $self->git_path($path);
3577 if ($gpath eq '') {
3578 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3579 -r --name-only -z/,
3580 $self->{c});
3581 local $/ = "\0";
3582 while (<$ls>) {
3583 chomp;
3584 $self->{gii}->remove($_);
3585 print "\tD\t$_\n" unless $::_q;
3587 command_close_pipe($ls, $ctx);
3588 $self->{empty}->{$path} = 0;
3590 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3591 delete $self->{empty}->{$dir};
3592 $self->{empty}->{$path} = 1;
3593 out:
3594 { path => $path };
3597 sub change_dir_prop {
3598 my ($self, $db, $prop, $value) = @_;
3599 return undef if $self->is_path_ignored($db->{path});
3600 $self->{dir_prop}->{$db->{path}} ||= {};
3601 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3602 undef;
3605 sub absent_directory {
3606 my ($self, $path, $pb) = @_;
3607 return undef if $self->is_path_ignored($path);
3608 $self->{absent_dir}->{$pb->{path}} ||= [];
3609 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3610 undef;
3613 sub absent_file {
3614 my ($self, $path, $pb) = @_;
3615 return undef if $self->is_path_ignored($path);
3616 $self->{absent_file}->{$pb->{path}} ||= [];
3617 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3618 undef;
3621 sub change_file_prop {
3622 my ($self, $fb, $prop, $value) = @_;
3623 return undef if $self->is_path_ignored($fb->{path});
3624 if ($prop eq 'svn:executable') {
3625 if ($fb->{mode_b} != 120000) {
3626 $fb->{mode_b} = defined $value ? 100755 : 100644;
3628 } elsif ($prop eq 'svn:special') {
3629 $fb->{mode_b} = defined $value ? 120000 : 100644;
3630 } else {
3631 $self->{file_prop}->{$fb->{path}} ||= {};
3632 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3634 undef;
3637 sub apply_textdelta {
3638 my ($self, $fb, $exp) = @_;
3639 return undef if $self->is_path_ignored($fb->{path});
3640 my $fh = $::_repository->temp_acquire('svn_delta');
3641 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3642 # (but $base does not,) so dup() it for reading in close_file
3643 open my $dup, '<&', $fh or croak $!;
3644 my $base = $::_repository->temp_acquire('git_blob');
3646 if ($fb->{blob}) {
3647 my ($base_is_link, $size);
3649 if ($fb->{mode_a} eq '120000' &&
3650 ! $self->{empty_symlinks}->{$fb->{path}}) {
3651 print $base 'link ' or die "print $!\n";
3652 $base_is_link = 1;
3654 retry:
3655 $size = $::_repository->cat_blob($fb->{blob}, $base);
3656 die "Failed to read object $fb->{blob}" if ($size < 0);
3658 if (defined $exp) {
3659 seek $base, 0, 0 or croak $!;
3660 my $got = ::md5sum($base);
3661 if ($got ne $exp) {
3662 my $err = "Checksum mismatch: ".
3663 "$fb->{path} $fb->{blob}\n" .
3664 "expected: $exp\n" .
3665 " got: $got\n";
3666 if ($base_is_link) {
3667 warn $err,
3668 "Retrying... (possibly ",
3669 "a bad symlink from SVN)\n";
3670 $::_repository->temp_reset($base);
3671 $base_is_link = 0;
3672 goto retry;
3674 die $err;
3678 seek $base, 0, 0 or croak $!;
3679 $fb->{fh} = $fh;
3680 $fb->{base} = $base;
3681 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3684 sub close_file {
3685 my ($self, $fb, $exp) = @_;
3686 return undef if $self->is_path_ignored($fb->{path});
3688 my $hash;
3689 my $path = $self->git_path($fb->{path});
3690 if (my $fh = $fb->{fh}) {
3691 if (defined $exp) {
3692 seek($fh, 0, 0) or croak $!;
3693 my $got = ::md5sum($fh);
3694 if ($got ne $exp) {
3695 die "Checksum mismatch: $path\n",
3696 "expected: $exp\n got: $got\n";
3699 if ($fb->{mode_b} == 120000) {
3700 sysseek($fh, 0, 0) or croak $!;
3701 my $rd = sysread($fh, my $buf, 5);
3703 if (!defined $rd) {
3704 croak "sysread: $!\n";
3705 } elsif ($rd == 0) {
3706 warn "$path has mode 120000",
3707 " but it points to nothing\n",
3708 "converting to an empty file with mode",
3709 " 100644\n";
3710 $fb->{mode_b} = '100644';
3711 } elsif ($buf ne 'link ') {
3712 warn "$path has mode 120000",
3713 " but is not a link\n";
3714 } else {
3715 my $tmp_fh = $::_repository->temp_acquire(
3716 'svn_hash');
3717 my $res;
3718 while ($res = sysread($fh, my $str, 1024)) {
3719 my $out = syswrite($tmp_fh, $str, $res);
3720 defined($out) && $out == $res
3721 or croak("write ",
3722 Git::temp_path($tmp_fh),
3723 ": $!\n");
3725 defined $res or croak $!;
3727 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3728 Git::temp_release($tmp_fh, 1);
3732 $hash = $::_repository->hash_and_insert_object(
3733 Git::temp_path($fh));
3734 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3736 Git::temp_release($fb->{base}, 1);
3737 Git::temp_release($fh, 1);
3738 } else {
3739 $hash = $fb->{blob} or die "no blob information\n";
3741 $fb->{pool}->clear;
3742 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3743 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3744 undef;
3747 sub abort_edit {
3748 my $self = shift;
3749 $self->{nr} = $self->{gii}->{nr};
3750 delete $self->{gii};
3751 $self->SUPER::abort_edit(@_);
3754 sub close_edit {
3755 my $self = shift;
3756 $self->{git_commit_ok} = 1;
3757 $self->{nr} = $self->{gii}->{nr};
3758 delete $self->{gii};
3759 $self->SUPER::close_edit(@_);
3762 package SVN::Git::Editor;
3763 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3764 use strict;
3765 use warnings;
3766 use Carp qw/croak/;
3767 use IO::File;
3769 sub new {
3770 my ($class, $opts) = @_;
3771 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3772 die "$_ required!\n" unless (defined $opts->{$_});
3775 my $pool = SVN::Pool->new;
3776 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3777 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3778 $opts->{r}, $mods);
3780 # $opts->{ra} functions should not be used after this:
3781 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3782 $opts->{editor_cb}, $pool);
3783 my $self = SVN::Delta::Editor->new(@ce, $pool);
3784 bless $self, $class;
3785 foreach (qw/svn_path r tree_a tree_b/) {
3786 $self->{$_} = $opts->{$_};
3788 $self->{url} = $opts->{ra}->{url};
3789 $self->{mods} = $mods;
3790 $self->{types} = $types;
3791 $self->{pool} = $pool;
3792 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3793 $self->{rm} = { };
3794 $self->{path_prefix} = length $self->{svn_path} ?
3795 "$self->{svn_path}/" : '';
3796 $self->{config} = $opts->{config};
3797 return $self;
3800 sub generate_diff {
3801 my ($tree_a, $tree_b) = @_;
3802 my @diff_tree = qw(diff-tree -z -r);
3803 if ($_cp_similarity) {
3804 push @diff_tree, "-C$_cp_similarity";
3805 } else {
3806 push @diff_tree, '-C';
3808 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3809 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3810 push @diff_tree, $tree_a, $tree_b;
3811 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3812 local $/ = "\0";
3813 my $state = 'meta';
3814 my @mods;
3815 while (<$diff_fh>) {
3816 chomp $_; # this gets rid of the trailing "\0"
3817 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3818 ($::sha1)\s($::sha1)\s
3819 ([MTCRAD])\d*$/xo) {
3820 push @mods, { mode_a => $1, mode_b => $2,
3821 sha1_a => $3, sha1_b => $4,
3822 chg => $5 };
3823 if ($5 =~ /^(?:C|R)$/) {
3824 $state = 'file_a';
3825 } else {
3826 $state = 'file_b';
3828 } elsif ($state eq 'file_a') {
3829 my $x = $mods[$#mods] or croak "Empty array\n";
3830 if ($x->{chg} !~ /^(?:C|R)$/) {
3831 croak "Error parsing $_, $x->{chg}\n";
3833 $x->{file_a} = $_;
3834 $state = 'file_b';
3835 } elsif ($state eq 'file_b') {
3836 my $x = $mods[$#mods] or croak "Empty array\n";
3837 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3838 croak "Error parsing $_, $x->{chg}\n";
3840 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3841 croak "Error parsing $_, $x->{chg}\n";
3843 $x->{file_b} = $_;
3844 $state = 'meta';
3845 } else {
3846 croak "Error parsing $_\n";
3849 command_close_pipe($diff_fh, $ctx);
3850 \@mods;
3853 sub check_diff_paths {
3854 my ($ra, $pfx, $rev, $mods) = @_;
3855 my %types;
3856 $pfx .= '/' if length $pfx;
3858 sub type_diff_paths {
3859 my ($ra, $types, $path, $rev) = @_;
3860 my @p = split m#/+#, $path;
3861 my $c = shift @p;
3862 unless (defined $types->{$c}) {
3863 $types->{$c} = $ra->check_path($c, $rev);
3865 while (@p) {
3866 $c .= '/' . shift @p;
3867 next if defined $types->{$c};
3868 $types->{$c} = $ra->check_path($c, $rev);
3872 foreach my $m (@$mods) {
3873 foreach my $f (qw/file_a file_b/) {
3874 next unless defined $m->{$f};
3875 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3876 if (length $pfx.$dir && ! defined $types{$dir}) {
3877 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3881 \%types;
3884 sub split_path {
3885 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3888 sub repo_path {
3889 my ($self, $path) = @_;
3890 $self->{path_prefix}.(defined $path ? $path : '');
3893 sub url_path {
3894 my ($self, $path) = @_;
3895 if ($self->{url} =~ m#^https?://#) {
3896 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3898 $self->{url} . '/' . $self->repo_path($path);
3901 sub rmdirs {
3902 my ($self) = @_;
3903 my $rm = $self->{rm};
3904 delete $rm->{''}; # we never delete the url we're tracking
3905 return unless %$rm;
3907 foreach (keys %$rm) {
3908 my @d = split m#/#, $_;
3909 my $c = shift @d;
3910 $rm->{$c} = 1;
3911 while (@d) {
3912 $c .= '/' . shift @d;
3913 $rm->{$c} = 1;
3916 delete $rm->{$self->{svn_path}};
3917 delete $rm->{''}; # we never delete the url we're tracking
3918 return unless %$rm;
3920 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3921 $self->{tree_b});
3922 local $/ = "\0";
3923 while (<$fh>) {
3924 chomp;
3925 my @dn = split m#/#, $_;
3926 while (pop @dn) {
3927 delete $rm->{join '/', @dn};
3929 unless (%$rm) {
3930 close $fh;
3931 return;
3934 command_close_pipe($fh, $ctx);
3936 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3937 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3938 $self->close_directory($bat->{$d}, $p);
3939 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3940 print "\tD+\t$d/\n" unless $::_q;
3941 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3942 delete $bat->{$d};
3946 sub open_or_add_dir {
3947 my ($self, $full_path, $baton) = @_;
3948 my $t = $self->{types}->{$full_path};
3949 if (!defined $t) {
3950 die "$full_path not known in r$self->{r} or we have a bug!\n";
3953 no warnings 'once';
3954 # SVN::Node::none and SVN::Node::file are used only once,
3955 # so we're shutting up Perl's warnings about them.
3956 if ($t == $SVN::Node::none) {
3957 return $self->add_directory($full_path, $baton,
3958 undef, -1, $self->{pool});
3959 } elsif ($t == $SVN::Node::dir) {
3960 return $self->open_directory($full_path, $baton,
3961 $self->{r}, $self->{pool});
3962 } # no warnings 'once'
3963 print STDERR "$full_path already exists in repository at ",
3964 "r$self->{r} and it is not a directory (",
3965 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3966 } # no warnings 'once'
3967 exit 1;
3970 sub ensure_path {
3971 my ($self, $path) = @_;
3972 my $bat = $self->{bat};
3973 my $repo_path = $self->repo_path($path);
3974 return $bat->{''} unless (length $repo_path);
3975 my @p = split m#/+#, $repo_path;
3976 my $c = shift @p;
3977 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3978 while (@p) {
3979 my $c0 = $c;
3980 $c .= '/' . shift @p;
3981 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3983 return $bat->{$c};
3986 # Subroutine to convert a globbing pattern to a regular expression.
3987 # From perl cookbook.
3988 sub glob2pat {
3989 my $globstr = shift;
3990 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3991 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3992 return '^' . $globstr . '$';
3995 sub check_autoprop {
3996 my ($self, $pattern, $properties, $file, $fbat) = @_;
3997 # Convert the globbing pattern to a regular expression.
3998 my $regex = glob2pat($pattern);
3999 # Check if the pattern matches the file name.
4000 if($file =~ m/($regex)/) {
4001 # Parse the list of properties to set.
4002 my @props = split(/;/, $properties);
4003 foreach my $prop (@props) {
4004 # Parse 'name=value' syntax and set the property.
4005 if ($prop =~ /([^=]+)=(.*)/) {
4006 my ($n,$v) = ($1,$2);
4007 for ($n, $v) {
4008 s/^\s+//; s/\s+$//;
4010 $self->change_file_prop($fbat, $n, $v);
4016 sub apply_autoprops {
4017 my ($self, $file, $fbat) = @_;
4018 my $conf_t = ${$self->{config}}{'config'};
4019 no warnings 'once';
4020 # Check [miscellany]/enable-auto-props in svn configuration.
4021 if (SVN::_Core::svn_config_get_bool(
4022 $conf_t,
4023 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4024 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4025 0)) {
4026 # Auto-props are enabled. Enumerate them to look for matches.
4027 my $callback = sub {
4028 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4030 SVN::_Core::svn_config_enumerate(
4031 $conf_t,
4032 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4033 $callback);
4037 sub A {
4038 my ($self, $m) = @_;
4039 my ($dir, $file) = split_path($m->{file_b});
4040 my $pbat = $self->ensure_path($dir);
4041 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4042 undef, -1);
4043 print "\tA\t$m->{file_b}\n" unless $::_q;
4044 $self->apply_autoprops($file, $fbat);
4045 $self->chg_file($fbat, $m);
4046 $self->close_file($fbat,undef,$self->{pool});
4049 sub C {
4050 my ($self, $m) = @_;
4051 my ($dir, $file) = split_path($m->{file_b});
4052 my $pbat = $self->ensure_path($dir);
4053 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4054 $self->url_path($m->{file_a}), $self->{r});
4055 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4056 $self->chg_file($fbat, $m);
4057 $self->close_file($fbat,undef,$self->{pool});
4060 sub delete_entry {
4061 my ($self, $path, $pbat) = @_;
4062 my $rpath = $self->repo_path($path);
4063 my ($dir, $file) = split_path($rpath);
4064 $self->{rm}->{$dir} = 1;
4065 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4068 sub R {
4069 my ($self, $m) = @_;
4070 my ($dir, $file) = split_path($m->{file_b});
4071 my $pbat = $self->ensure_path($dir);
4072 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4073 $self->url_path($m->{file_a}), $self->{r});
4074 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4075 $self->apply_autoprops($file, $fbat);
4076 $self->chg_file($fbat, $m);
4077 $self->close_file($fbat,undef,$self->{pool});
4079 ($dir, $file) = split_path($m->{file_a});
4080 $pbat = $self->ensure_path($dir);
4081 $self->delete_entry($m->{file_a}, $pbat);
4084 sub M {
4085 my ($self, $m) = @_;
4086 my ($dir, $file) = split_path($m->{file_b});
4087 my $pbat = $self->ensure_path($dir);
4088 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4089 $pbat,$self->{r},$self->{pool});
4090 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4091 $self->chg_file($fbat, $m);
4092 $self->close_file($fbat,undef,$self->{pool});
4095 sub T { shift->M(@_) }
4097 sub change_file_prop {
4098 my ($self, $fbat, $pname, $pval) = @_;
4099 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4102 sub _chg_file_get_blob ($$$$) {
4103 my ($self, $fbat, $m, $which) = @_;
4104 my $fh = $::_repository->temp_acquire("git_blob_$which");
4105 if ($m->{"mode_$which"} =~ /^120/) {
4106 print $fh 'link ' or croak $!;
4107 $self->change_file_prop($fbat,'svn:special','*');
4108 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4109 $self->change_file_prop($fbat,'svn:special',undef);
4111 my $blob = $m->{"sha1_$which"};
4112 return ($fh,) if ($blob =~ /^0{40}$/);
4113 my $size = $::_repository->cat_blob($blob, $fh);
4114 croak "Failed to read object $blob" if ($size < 0);
4115 $fh->flush == 0 or croak $!;
4116 seek $fh, 0, 0 or croak $!;
4118 my $exp = ::md5sum($fh);
4119 seek $fh, 0, 0 or croak $!;
4120 return ($fh, $exp);
4123 sub chg_file {
4124 my ($self, $fbat, $m) = @_;
4125 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4126 $self->change_file_prop($fbat,'svn:executable','*');
4127 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4128 $self->change_file_prop($fbat,'svn:executable',undef);
4130 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4131 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4132 my $pool = SVN::Pool->new;
4133 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4134 if (-s $fh_a) {
4135 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4136 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4137 if (defined $res) {
4138 die "Unexpected result from send_txstream: $res\n",
4139 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4141 } else {
4142 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4143 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4144 if ($got ne $exp_b);
4146 Git::temp_release($fh_b, 1);
4147 Git::temp_release($fh_a, 1);
4148 $pool->clear;
4151 sub D {
4152 my ($self, $m) = @_;
4153 my ($dir, $file) = split_path($m->{file_b});
4154 my $pbat = $self->ensure_path($dir);
4155 print "\tD\t$m->{file_b}\n" unless $::_q;
4156 $self->delete_entry($m->{file_b}, $pbat);
4159 sub close_edit {
4160 my ($self) = @_;
4161 my ($p,$bat) = ($self->{pool}, $self->{bat});
4162 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4163 next if $_ eq '';
4164 $self->close_directory($bat->{$_}, $p);
4166 $self->close_directory($bat->{''}, $p);
4167 $self->SUPER::close_edit($p);
4168 $p->clear;
4171 sub abort_edit {
4172 my ($self) = @_;
4173 $self->SUPER::abort_edit($self->{pool});
4176 sub DESTROY {
4177 my $self = shift;
4178 $self->SUPER::DESTROY(@_);
4179 $self->{pool}->clear;
4182 # this drives the editor
4183 sub apply_diff {
4184 my ($self) = @_;
4185 my $mods = $self->{mods};
4186 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4187 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4188 my $f = $m->{chg};
4189 if (defined $o{$f}) {
4190 $self->$f($m);
4191 } else {
4192 fatal("Invalid change type: $f");
4195 $self->rmdirs if $_rmdir;
4196 if (@$mods == 0) {
4197 $self->abort_edit;
4198 } else {
4199 $self->close_edit;
4201 return scalar @$mods;
4204 package Git::SVN::Ra;
4205 use vars qw/@ISA $config_dir $_log_window_size/;
4206 use strict;
4207 use warnings;
4208 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4210 BEGIN {
4211 # enforce temporary pool usage for some simple functions
4212 no strict 'refs';
4213 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4214 get_file/) {
4215 my $SUPER = "SUPER::$f";
4216 *$f = sub {
4217 my $self = shift;
4218 my $pool = SVN::Pool->new;
4219 my @ret = $self->$SUPER(@_,$pool);
4220 $pool->clear;
4221 wantarray ? @ret : $ret[0];
4226 sub _auth_providers () {
4228 SVN::Client::get_simple_provider(),
4229 SVN::Client::get_ssl_server_trust_file_provider(),
4230 SVN::Client::get_simple_prompt_provider(
4231 \&Git::SVN::Prompt::simple, 2),
4232 SVN::Client::get_ssl_client_cert_file_provider(),
4233 SVN::Client::get_ssl_client_cert_prompt_provider(
4234 \&Git::SVN::Prompt::ssl_client_cert, 2),
4235 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4236 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4237 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4238 SVN::Client::get_username_provider(),
4239 SVN::Client::get_ssl_server_trust_prompt_provider(
4240 \&Git::SVN::Prompt::ssl_server_trust),
4241 SVN::Client::get_username_prompt_provider(
4242 \&Git::SVN::Prompt::username, 2)
4246 sub escape_uri_only {
4247 my ($uri) = @_;
4248 my @tmp;
4249 foreach (split m{/}, $uri) {
4250 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4251 push @tmp, $_;
4253 join('/', @tmp);
4256 sub escape_url {
4257 my ($url) = @_;
4258 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4259 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4260 $url = "$scheme://$domain$uri";
4262 $url;
4265 sub new {
4266 my ($class, $url) = @_;
4267 $url =~ s!/+$!!;
4268 return $RA if ($RA && $RA->{url} eq $url);
4270 SVN::_Core::svn_config_ensure($config_dir, undef);
4271 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4272 my $config = SVN::Core::config_get_config($config_dir);
4273 $RA = undef;
4274 my $dont_store_passwords = 1;
4275 my $conf_t = ${$config}{'config'};
4277 no warnings 'once';
4278 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4279 # produces warnings that variables are used only once.
4280 # I had not found the better way to shut them up, so
4281 # the warnings of type 'once' are disabled in this block.
4282 if (SVN::_Core::svn_config_get_bool($conf_t,
4283 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4284 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4285 1) == 0) {
4286 SVN::_Core::svn_auth_set_parameter($baton,
4287 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4288 bless (\$dont_store_passwords, "_p_void"));
4290 if (SVN::_Core::svn_config_get_bool($conf_t,
4291 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4292 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4293 1) == 0) {
4294 $Git::SVN::Prompt::_no_auth_cache = 1;
4296 } # no warnings 'once'
4297 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4298 config => $config,
4299 pool => SVN::Pool->new,
4300 auth_provider_callbacks => $callbacks);
4301 $self->{url} = $url;
4302 $self->{svn_path} = $url;
4303 $self->{repos_root} = $self->get_repos_root;
4304 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4305 $self->{cache} = { check_path => { r => 0, data => {} },
4306 get_dir => { r => 0, data => {} } };
4307 $RA = bless $self, $class;
4310 sub check_path {
4311 my ($self, $path, $r) = @_;
4312 my $cache = $self->{cache}->{check_path};
4313 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4314 return $cache->{data}->{$path};
4316 my $pool = SVN::Pool->new;
4317 my $t = $self->SUPER::check_path($path, $r, $pool);
4318 $pool->clear;
4319 if ($r != $cache->{r}) {
4320 %{$cache->{data}} = ();
4321 $cache->{r} = $r;
4323 $cache->{data}->{$path} = $t;
4326 sub get_dir {
4327 my ($self, $dir, $r) = @_;
4328 my $cache = $self->{cache}->{get_dir};
4329 if ($r == $cache->{r}) {
4330 if (my $x = $cache->{data}->{$dir}) {
4331 return wantarray ? @$x : $x->[0];
4334 my $pool = SVN::Pool->new;
4335 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4336 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4337 $pool->clear;
4338 if ($r != $cache->{r}) {
4339 %{$cache->{data}} = ();
4340 $cache->{r} = $r;
4342 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4343 wantarray ? (\%dirents, $r, $props) : \%dirents;
4346 sub DESTROY {
4347 # do not call the real DESTROY since we store ourselves in $RA
4350 # get_log(paths, start, end, limit,
4351 # discover_changed_paths, strict_node_history, receiver)
4352 sub get_log {
4353 my ($self, @args) = @_;
4354 my $pool = SVN::Pool->new;
4356 # the limit parameter was not supported in SVN 1.1.x, so we
4357 # drop it. Therefore, the receiver callback passed to it
4358 # is made aware of this limitation by being wrapped if
4359 # the limit passed to is being wrapped.
4360 if ($SVN::Core::VERSION le '1.2.0') {
4361 my $limit = splice(@args, 3, 1);
4362 if ($limit > 0) {
4363 my $receiver = pop @args;
4364 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4367 my $ret = $self->SUPER::get_log(@args, $pool);
4368 $pool->clear;
4369 $ret;
4372 sub trees_match {
4373 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4374 my $ctx = SVN::Client->new(auth => _auth_providers);
4375 my $out = IO::File->new_tmpfile;
4377 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4378 # $ctx->diff(), so we'll create a default one
4379 my $pool = SVN::Pool->new_default_sub;
4381 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4382 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4383 $out->flush;
4384 my $ret = (($out->stat)[7] == 0);
4385 close $out or croak $!;
4387 $ret;
4390 sub get_commit_editor {
4391 my ($self, $log, $cb, $pool) = @_;
4392 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4393 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4396 sub gs_do_update {
4397 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4398 my $new = ($rev_a == $rev_b);
4399 my $path = $gs->{path};
4401 if ($new && -e $gs->{index}) {
4402 unlink $gs->{index} or die
4403 "Couldn't unlink index: $gs->{index}: $!\n";
4405 my $pool = SVN::Pool->new;
4406 $editor->set_path_strip($path);
4407 my (@pc) = split m#/#, $path;
4408 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4409 1, $editor, $pool);
4410 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4412 # Since we can't rely on svn_ra_reparent being available, we'll
4413 # just have to do some magic with set_path to make it so
4414 # we only want a partial path.
4415 my $sp = '';
4416 my $final = join('/', @pc);
4417 while (@pc) {
4418 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4419 $sp .= '/' if length $sp;
4420 $sp .= shift @pc;
4422 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4424 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4426 $reporter->finish_report($pool);
4427 $pool->clear;
4428 $editor->{git_commit_ok};
4431 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4432 # svn_ra_reparent didn't work before 1.4)
4433 sub gs_do_switch {
4434 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4435 my $path = $gs->{path};
4436 my $pool = SVN::Pool->new;
4438 my $full_url = $self->{url};
4439 my $old_url = $full_url;
4440 $full_url .= '/' . escape_uri_only($path) if length $path;
4441 my ($ra, $reparented);
4443 if ($old_url =~ m#^svn(\+ssh)?://#) {
4444 $_[0] = undef;
4445 $self = undef;
4446 $RA = undef;
4447 $ra = Git::SVN::Ra->new($full_url);
4448 $ra_invalid = 1;
4449 } elsif ($old_url ne $full_url) {
4450 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4451 $self->{url} = $full_url;
4452 $reparented = 1;
4455 $ra ||= $self;
4456 $url_b = escape_url($url_b);
4457 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4458 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4459 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4460 $reporter->finish_report($pool);
4462 if ($reparented) {
4463 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4464 $self->{url} = $old_url;
4467 $pool->clear;
4468 $editor->{git_commit_ok};
4471 sub longest_common_path {
4472 my ($gsv, $globs) = @_;
4473 my %common;
4474 my $common_max = scalar @$gsv;
4476 foreach my $gs (@$gsv) {
4477 my @tmp = split m#/#, $gs->{path};
4478 my $p = '';
4479 foreach (@tmp) {
4480 $p .= length($p) ? "/$_" : $_;
4481 $common{$p} ||= 0;
4482 $common{$p}++;
4485 $globs ||= [];
4486 $common_max += scalar @$globs;
4487 foreach my $glob (@$globs) {
4488 my @tmp = split m#/#, $glob->{path}->{left};
4489 my $p = '';
4490 foreach (@tmp) {
4491 $p .= length($p) ? "/$_" : $_;
4492 $common{$p} ||= 0;
4493 $common{$p}++;
4497 my $longest_path = '';
4498 foreach (sort {length $b <=> length $a} keys %common) {
4499 if ($common{$_} == $common_max) {
4500 $longest_path = $_;
4501 last;
4504 $longest_path;
4507 sub gs_fetch_loop_common {
4508 my ($self, $base, $head, $gsv, $globs) = @_;
4509 return if ($base > $head);
4510 my $inc = $_log_window_size;
4511 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4512 my $longest_path = longest_common_path($gsv, $globs);
4513 my $ra_url = $self->{url};
4514 my $find_trailing_edge;
4515 while (1) {
4516 my %revs;
4517 my $err;
4518 my $err_handler = $SVN::Error::handler;
4519 $SVN::Error::handler = sub {
4520 ($err) = @_;
4521 skip_unknown_revs($err);
4523 sub _cb {
4524 my ($paths, $r, $author, $date, $log) = @_;
4525 [ dup_changed_paths($paths),
4526 { author => $author, date => $date, log => $log } ];
4528 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4529 sub { $revs{$_[1]} = _cb(@_) });
4530 if ($err) {
4531 print "Checked through r$max\r";
4532 } else {
4533 $find_trailing_edge = 1;
4535 if ($err and $find_trailing_edge) {
4536 print STDERR "Path '$longest_path' ",
4537 "was probably deleted:\n",
4538 $err->expanded_message,
4539 "\nWill attempt to follow ",
4540 "revisions r$min .. r$max ",
4541 "committed before the deletion\n";
4542 my $hi = $max;
4543 while (--$hi >= $min) {
4544 my $ok;
4545 $self->get_log([$longest_path], $min, $hi,
4546 0, 1, 1, sub {
4547 $ok = $_[1];
4548 $revs{$_[1]} = _cb(@_) });
4549 if ($ok) {
4550 print STDERR "r$min .. r$ok OK\n";
4551 last;
4554 $find_trailing_edge = 0;
4556 $SVN::Error::handler = $err_handler;
4558 my %exists = map { $_->{path} => $_ } @$gsv;
4559 foreach my $r (sort {$a <=> $b} keys %revs) {
4560 my ($paths, $logged) = @{$revs{$r}};
4562 foreach my $gs ($self->match_globs(\%exists, $paths,
4563 $globs, $r)) {
4564 if ($gs->rev_map_max >= $r) {
4565 next;
4567 next unless $gs->match_paths($paths, $r);
4568 $gs->{logged_rev_props} = $logged;
4569 if (my $last_commit = $gs->last_commit) {
4570 $gs->assert_index_clean($last_commit);
4572 my $log_entry = $gs->do_fetch($paths, $r);
4573 if ($log_entry) {
4574 $gs->do_git_commit($log_entry);
4576 $INDEX_FILES{$gs->{index}} = 1;
4578 foreach my $g (@$globs) {
4579 my $k = "svn-remote.$g->{remote}." .
4580 "$g->{t}-maxRev";
4581 Git::SVN::tmp_config($k, $r);
4583 if ($ra_invalid) {
4584 $_[0] = undef;
4585 $self = undef;
4586 $RA = undef;
4587 $self = Git::SVN::Ra->new($ra_url);
4588 $ra_invalid = undef;
4591 # pre-fill the .rev_db since it'll eventually get filled in
4592 # with '0' x40 if something new gets committed
4593 foreach my $gs (@$gsv) {
4594 next if $gs->rev_map_max >= $max;
4595 next if defined $gs->rev_map_get($max);
4596 $gs->rev_map_set($max, 0 x40);
4598 foreach my $g (@$globs) {
4599 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4600 Git::SVN::tmp_config($k, $max);
4602 last if $max >= $head;
4603 $min = $max + 1;
4604 $max += $inc;
4605 $max = $head if ($max > $head);
4607 Git::SVN::gc();
4610 sub get_dir_globbed {
4611 my ($self, $left, $depth, $r) = @_;
4613 my @x = eval { $self->get_dir($left, $r) };
4614 return unless scalar @x == 3;
4615 my $dirents = $x[0];
4616 my @finalents;
4617 foreach my $de (keys %$dirents) {
4618 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4619 if ($depth > 1) {
4620 my @args = ("$left/$de", $depth - 1, $r);
4621 foreach my $dir ($self->get_dir_globbed(@args)) {
4622 push @finalents, "$de/$dir";
4624 } else {
4625 push @finalents, $de;
4628 @finalents;
4631 sub match_globs {
4632 my ($self, $exists, $paths, $globs, $r) = @_;
4634 sub get_dir_check {
4635 my ($self, $exists, $g, $r) = @_;
4637 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4638 $g->{path}->{depth},
4639 $r);
4641 foreach my $de (@dirs) {
4642 my $p = $g->{path}->full_path($de);
4643 next if $exists->{$p};
4644 next if (length $g->{path}->{right} &&
4645 ($self->check_path($p, $r) !=
4646 $SVN::Node::dir));
4647 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4648 $g->{ref}->full_path($de), 1);
4651 foreach my $g (@$globs) {
4652 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4653 if ($path->{action} =~ /^[AR]$/) {
4654 get_dir_check($self, $exists, $g, $r);
4657 foreach (keys %$paths) {
4658 if (/$g->{path}->{left_regex}/ &&
4659 !/$g->{path}->{regex}/) {
4660 next if $paths->{$_}->{action} !~ /^[AR]$/;
4661 get_dir_check($self, $exists, $g, $r);
4663 next unless /$g->{path}->{regex}/;
4664 my $p = $1;
4665 my $pathname = $g->{path}->full_path($p);
4666 next if $exists->{$pathname};
4667 next if ($self->check_path($pathname, $r) !=
4668 $SVN::Node::dir);
4669 $exists->{$pathname} = Git::SVN->init(
4670 $self->{url}, $pathname, undef,
4671 $g->{ref}->full_path($p), 1);
4673 my $c = '';
4674 foreach (split m#/#, $g->{path}->{left}) {
4675 $c .= "/$_";
4676 next unless ($paths->{$c} &&
4677 ($paths->{$c}->{action} =~ /^[AR]$/));
4678 get_dir_check($self, $exists, $g, $r);
4681 values %$exists;
4684 sub minimize_url {
4685 my ($self) = @_;
4686 return $self->{url} if ($self->{url} eq $self->{repos_root});
4687 my $url = $self->{repos_root};
4688 my @components = split(m!/!, $self->{svn_path});
4689 my $c = '';
4690 do {
4691 $url .= "/$c" if length $c;
4692 eval { (ref $self)->new($url)->get_latest_revnum };
4693 } while ($@ && ($c = shift @components));
4694 $url;
4697 sub can_do_switch {
4698 my $self = shift;
4699 unless (defined $can_do_switch) {
4700 my $pool = SVN::Pool->new;
4701 my $rep = eval {
4702 $self->do_switch(1, '', 0, $self->{url},
4703 SVN::Delta::Editor->new, $pool);
4705 if ($@) {
4706 $can_do_switch = 0;
4707 } else {
4708 $rep->abort_report($pool);
4709 $can_do_switch = 1;
4711 $pool->clear;
4713 $can_do_switch;
4716 sub skip_unknown_revs {
4717 my ($err) = @_;
4718 my $errno = $err->apr_err();
4719 # Maybe the branch we're tracking didn't
4720 # exist when the repo started, so it's
4721 # not an error if it doesn't, just continue
4723 # Wonderfully consistent library, eh?
4724 # 160013 - svn:// and file://
4725 # 175002 - http(s)://
4726 # 175007 - http(s):// (this repo required authorization, too...)
4727 # More codes may be discovered later...
4728 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4729 my $err_key = $err->expanded_message;
4730 # revision numbers change every time, filter them out
4731 $err_key =~ s/\d+/\0/g;
4732 $err_key = "$errno\0$err_key";
4733 unless ($ignored_err{$err_key}) {
4734 warn "W: Ignoring error from SVN, path probably ",
4735 "does not exist: ($errno): ",
4736 $err->expanded_message,"\n";
4737 warn "W: Do not be alarmed at the above message ",
4738 "git-svn is just searching aggressively for ",
4739 "old history.\n",
4740 "This may take a while on large repositories\n";
4741 $ignored_err{$err_key} = 1;
4743 return;
4745 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4748 # svn_log_changed_path_t objects passed to get_log are likely to be
4749 # overwritten even if only the refs are copied to an external variable,
4750 # so we should dup the structures in their entirety. Using an externally
4751 # passed pool (instead of our temporary and quickly cleared pool in
4752 # Git::SVN::Ra) does not help matters at all...
4753 sub dup_changed_paths {
4754 my ($paths) = @_;
4755 return undef unless $paths;
4756 my %ret;
4757 foreach my $p (keys %$paths) {
4758 my $i = $paths->{$p};
4759 my %s = map { $_ => $i->$_ }
4760 qw/copyfrom_path copyfrom_rev action/;
4761 $ret{$p} = \%s;
4763 \%ret;
4766 package Git::SVN::Log;
4767 use strict;
4768 use warnings;
4769 use POSIX qw/strftime/;
4770 use Time::Local;
4771 use constant commit_log_separator => ('-' x 72) . "\n";
4772 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4773 %rusers $show_commit $incremental/;
4774 my $l_fmt;
4776 sub cmt_showable {
4777 my ($c) = @_;
4778 return 1 if defined $c->{r};
4780 # big commit message got truncated by the 16k pretty buffer in rev-list
4781 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4782 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4783 @{$c->{l}} = ();
4784 my @log = command(qw/cat-file commit/, $c->{c});
4786 # shift off the headers
4787 shift @log while ($log[0] ne '');
4788 shift @log;
4790 # TODO: make $c->{l} not have a trailing newline in the future
4791 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4793 (undef, $c->{r}, undef) = ::extract_metadata(
4794 (grep(/^git-svn-id: /, @log))[-1]);
4796 return defined $c->{r};
4799 sub log_use_color {
4800 return $color || Git->repository->get_colorbool('color.diff');
4803 sub git_svn_log_cmd {
4804 my ($r_min, $r_max, @args) = @_;
4805 my $head = 'HEAD';
4806 my (@files, @log_opts);
4807 foreach my $x (@args) {
4808 if ($x eq '--' || @files) {
4809 push @files, $x;
4810 } else {
4811 if (::verify_ref("$x^0")) {
4812 $head = $x;
4813 } else {
4814 push @log_opts, $x;
4819 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4820 $gs ||= Git::SVN->_new;
4821 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4822 $gs->refname);
4823 push @cmd, '-r' unless $non_recursive;
4824 push @cmd, qw/--raw --name-status/ if $verbose;
4825 push @cmd, '--color' if log_use_color();
4826 push @cmd, @log_opts;
4827 if (defined $r_max && $r_max == $r_min) {
4828 push @cmd, '--max-count=1';
4829 if (my $c = $gs->rev_map_get($r_max)) {
4830 push @cmd, $c;
4832 } elsif (defined $r_max) {
4833 if ($r_max < $r_min) {
4834 ($r_min, $r_max) = ($r_max, $r_min);
4836 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4837 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4838 # If there are no commits in the range, both $c_max and $c_min
4839 # will be undefined. If there is at least 1 commit in the
4840 # range, both will be defined.
4841 return () if !defined $c_min || !defined $c_max;
4842 if ($c_min eq $c_max) {
4843 push @cmd, '--max-count=1', $c_min;
4844 } else {
4845 push @cmd, '--boundary', "$c_min..$c_max";
4848 return (@cmd, @files);
4851 # adapted from pager.c
4852 sub config_pager {
4853 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4854 if (!defined $pager) {
4855 $pager = 'less';
4856 } elsif (length $pager == 0 || $pager eq 'cat') {
4857 $pager = undef;
4859 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4862 sub run_pager {
4863 return unless -t *STDOUT && defined $pager;
4864 pipe my ($rfd, $wfd) or return;
4865 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4866 if (!$pid) {
4867 open STDOUT, '>&', $wfd or
4868 ::fatal "Can't redirect to stdout: $!";
4869 return;
4871 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4872 $ENV{LESS} ||= 'FRSX';
4873 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4876 sub format_svn_date {
4877 # some systmes don't handle or mishandle %z, so be creative.
4878 my $t = shift || time;
4879 my $gm = timelocal(gmtime($t));
4880 my $sign = qw( + + - )[ $t <=> $gm ];
4881 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4882 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4885 sub parse_git_date {
4886 my ($t, $tz) = @_;
4887 # Date::Parse isn't in the standard Perl distro :(
4888 if ($tz =~ s/^\+//) {
4889 $t += tz_to_s_offset($tz);
4890 } elsif ($tz =~ s/^\-//) {
4891 $t -= tz_to_s_offset($tz);
4893 return $t;
4896 sub set_local_timezone {
4897 if (defined $TZ) {
4898 $ENV{TZ} = $TZ;
4899 } else {
4900 delete $ENV{TZ};
4904 sub tz_to_s_offset {
4905 my ($tz) = @_;
4906 $tz =~ s/(\d\d)$//;
4907 return ($1 * 60) + ($tz * 3600);
4910 sub get_author_info {
4911 my ($dest, $author, $t, $tz) = @_;
4912 $author =~ s/(?:^\s*|\s*$)//g;
4913 $dest->{a_raw} = $author;
4914 my $au;
4915 if ($::_authors) {
4916 $au = $rusers{$author} || undef;
4918 if (!$au) {
4919 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4921 $dest->{t} = $t;
4922 $dest->{tz} = $tz;
4923 $dest->{a} = $au;
4924 $dest->{t_utc} = parse_git_date($t, $tz);
4927 sub process_commit {
4928 my ($c, $r_min, $r_max, $defer) = @_;
4929 if (defined $r_min && defined $r_max) {
4930 if ($r_min == $c->{r} && $r_min == $r_max) {
4931 show_commit($c);
4932 return 0;
4934 return 1 if $r_min == $r_max;
4935 if ($r_min < $r_max) {
4936 # we need to reverse the print order
4937 return 0 if (defined $limit && --$limit < 0);
4938 push @$defer, $c;
4939 return 1;
4941 if ($r_min != $r_max) {
4942 return 1 if ($r_min < $c->{r});
4943 return 1 if ($r_max > $c->{r});
4946 return 0 if (defined $limit && --$limit < 0);
4947 show_commit($c);
4948 return 1;
4951 sub show_commit {
4952 my $c = shift;
4953 if ($oneline) {
4954 my $x = "\n";
4955 if (my $l = $c->{l}) {
4956 while ($l->[0] =~ /^\s*$/) { shift @$l }
4957 $x = $l->[0];
4959 $l_fmt ||= 'A' . length($c->{r});
4960 print 'r',pack($l_fmt, $c->{r}),' | ';
4961 print "$c->{c} | " if $show_commit;
4962 print $x;
4963 } else {
4964 show_commit_normal($c);
4968 sub show_commit_changed_paths {
4969 my ($c) = @_;
4970 return unless $c->{changed};
4971 print "Changed paths:\n", @{$c->{changed}};
4974 sub show_commit_normal {
4975 my ($c) = @_;
4976 print commit_log_separator, "r$c->{r} | ";
4977 print "$c->{c} | " if $show_commit;
4978 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4979 my $nr_line = 0;
4981 if (my $l = $c->{l}) {
4982 while ($l->[$#$l] eq "\n" && $#$l > 0
4983 && $l->[($#$l - 1)] eq "\n") {
4984 pop @$l;
4986 $nr_line = scalar @$l;
4987 if (!$nr_line) {
4988 print "1 line\n\n\n";
4989 } else {
4990 if ($nr_line == 1) {
4991 $nr_line = '1 line';
4992 } else {
4993 $nr_line .= ' lines';
4995 print $nr_line, "\n";
4996 show_commit_changed_paths($c);
4997 print "\n";
4998 print $_ foreach @$l;
5000 } else {
5001 print "1 line\n";
5002 show_commit_changed_paths($c);
5003 print "\n";
5006 foreach my $x (qw/raw stat diff/) {
5007 if ($c->{$x}) {
5008 print "\n";
5009 print $_ foreach @{$c->{$x}}
5014 sub cmd_show_log {
5015 my (@args) = @_;
5016 my ($r_min, $r_max);
5017 my $r_last = -1; # prevent dupes
5018 set_local_timezone();
5019 if (defined $::_revision) {
5020 if ($::_revision =~ /^(\d+):(\d+)$/) {
5021 ($r_min, $r_max) = ($1, $2);
5022 } elsif ($::_revision =~ /^\d+$/) {
5023 $r_min = $r_max = $::_revision;
5024 } else {
5025 ::fatal "-r$::_revision is not supported, use ",
5026 "standard 'git log' arguments instead";
5030 config_pager();
5031 @args = git_svn_log_cmd($r_min, $r_max, @args);
5032 if (!@args) {
5033 print commit_log_separator unless $incremental || $oneline;
5034 return;
5036 my $log = command_output_pipe(@args);
5037 run_pager();
5038 my (@k, $c, $d, $stat);
5039 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5040 while (<$log>) {
5041 if (/^${esc_color}commit -?($::sha1_short)/o) {
5042 my $cmt = $1;
5043 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5044 $r_last = $c->{r};
5045 process_commit($c, $r_min, $r_max, \@k) or
5046 goto out;
5048 $d = undef;
5049 $c = { c => $cmt };
5050 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5051 get_author_info($c, $1, $2, $3);
5052 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5053 # ignore
5054 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5055 push @{$c->{raw}}, $_;
5056 } elsif (/^${esc_color}[ACRMDT]\t/) {
5057 # we could add $SVN->{svn_path} here, but that requires
5058 # remote access at the moment (repo_path_split)...
5059 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5060 push @{$c->{changed}}, $_;
5061 } elsif (/^${esc_color}diff /o) {
5062 $d = 1;
5063 push @{$c->{diff}}, $_;
5064 } elsif ($d) {
5065 push @{$c->{diff}}, $_;
5066 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5067 $esc_color*[\+\-]*$esc_color$/x) {
5068 $stat = 1;
5069 push @{$c->{stat}}, $_;
5070 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5071 push @{$c->{stat}}, $_;
5072 $stat = undef;
5073 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5074 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5075 } elsif (s/^${esc_color} //o) {
5076 push @{$c->{l}}, $_;
5079 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5080 $r_last = $c->{r};
5081 process_commit($c, $r_min, $r_max, \@k);
5083 if (@k) {
5084 ($r_min, $r_max) = ($r_max, $r_min);
5085 process_commit($_, $r_min, $r_max) foreach reverse @k;
5087 out:
5088 close $log;
5089 print commit_log_separator unless $incremental || $oneline;
5092 sub cmd_blame {
5093 my $path = pop;
5095 config_pager();
5096 run_pager();
5098 my ($fh, $ctx, $rev);
5100 if ($_git_format) {
5101 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5102 while (my $line = <$fh>) {
5103 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5104 # Uncommitted edits show up as a rev ID of
5105 # all zeros, which we can't look up with
5106 # cmt_metadata
5107 if ($1 !~ /^0+$/) {
5108 (undef, $rev, undef) =
5109 ::cmt_metadata($1);
5110 $rev = '0' if (!$rev);
5111 } else {
5112 $rev = '0';
5114 $rev = sprintf('%-10s', $rev);
5115 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5117 print $line;
5119 } else {
5120 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5121 '--', $path);
5122 my ($sha1);
5123 my %authors;
5124 my @buffer;
5125 my %dsha; #distinct sha keys
5127 while (my $line = <$fh>) {
5128 push @buffer, $line;
5129 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5130 $dsha{$1} = 1;
5134 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5136 foreach my $line (@buffer) {
5137 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5138 $rev = $s2r->{$1};
5139 $rev = '0' if (!$rev)
5141 elsif ($line =~ /^author (.*)/) {
5142 $authors{$rev} = $1;
5143 $authors{$rev} =~ s/\s/_/g;
5145 elsif ($line =~ /^\t(.*)$/) {
5146 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5150 command_close_pipe($fh, $ctx);
5153 package Git::SVN::Migration;
5154 # these version numbers do NOT correspond to actual version numbers
5155 # of git nor git-svn. They are just relative.
5157 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5159 # v1 layout: .git/$id/info/url, refs/remotes/$id
5161 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5163 # v3 layout: .git/svn/$id, refs/remotes/$id
5164 # - info/url may remain for backwards compatibility
5165 # - this is what we migrate up to this layout automatically,
5166 # - this will be used by git svn init on single branches
5167 # v3.1 layout (auto migrated):
5168 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5169 # for backwards compatibility
5171 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5172 # - this is only created for newly multi-init-ed
5173 # repositories. Similar in spirit to the
5174 # --use-separate-remotes option in git-clone (now default)
5175 # - we do not automatically migrate to this (following
5176 # the example set by core git)
5178 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5179 # - newer, more-efficient format that uses 24-bytes per record
5180 # with no filler space.
5181 # - use xxd -c24 < .rev_map.$UUID to view and debug
5182 # - This is a one-way migration, repositories updated to the
5183 # new format will not be able to use old git-svn without
5184 # rebuilding the .rev_db. Rebuilding the rev_db is not
5185 # possible if noMetadata or useSvmProps are set; but should
5186 # be no problem for users that use the (sensible) defaults.
5187 use strict;
5188 use warnings;
5189 use Carp qw/croak/;
5190 use File::Path qw/mkpath/;
5191 use File::Basename qw/dirname basename/;
5192 use vars qw/$_minimize/;
5194 sub migrate_from_v0 {
5195 my $git_dir = $ENV{GIT_DIR};
5196 return undef unless -d $git_dir;
5197 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5198 my $migrated = 0;
5199 while (<$fh>) {
5200 chomp;
5201 my ($id, $orig_ref) = ($_, $_);
5202 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5203 next unless -f "$git_dir/$id/info/url";
5204 my $new_ref = "refs/remotes/$id";
5205 if (::verify_ref("$new_ref^0")) {
5206 print STDERR "W: $orig_ref is probably an old ",
5207 "branch used by an ancient version of ",
5208 "git-svn.\n",
5209 "However, $new_ref also exists.\n",
5210 "We will not be able ",
5211 "to use this branch until this ",
5212 "ambiguity is resolved.\n";
5213 next;
5215 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5216 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5217 command_noisy('update-ref', $new_ref, $orig_ref);
5218 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5219 $migrated++;
5221 command_close_pipe($fh, $ctx);
5222 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5223 $migrated;
5226 sub migrate_from_v1 {
5227 my $git_dir = $ENV{GIT_DIR};
5228 my $migrated = 0;
5229 return $migrated unless -d $git_dir;
5230 my $svn_dir = "$git_dir/svn";
5232 # just in case somebody used 'svn' as their $id at some point...
5233 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5235 print STDERR "Migrating from a git-svn v1 layout...\n";
5236 mkpath([$svn_dir]);
5237 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5238 "$svn_dir\n\t(required for this version ",
5239 "($::VERSION) of git-svn) does not exist.\n";
5240 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5241 while (<$fh>) {
5242 my $x = $_;
5243 next unless $x =~ s#^refs/remotes/##;
5244 chomp $x;
5245 next unless -f "$git_dir/$x/info/url";
5246 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5247 next unless $u;
5248 my $dn = dirname("$git_dir/svn/$x");
5249 mkpath([$dn]) unless -d $dn;
5250 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5251 mkpath(["$git_dir/svn/svn"]);
5252 print STDERR " - $git_dir/$x/info => ",
5253 "$git_dir/svn/$x/info\n";
5254 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5255 croak "$!: $x";
5256 # don't worry too much about these, they probably
5257 # don't exist with repos this old (save for index,
5258 # and we can easily regenerate that)
5259 foreach my $f (qw/unhandled.log index .rev_db/) {
5260 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5262 } else {
5263 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5264 rename "$git_dir/$x", "$git_dir/svn/$x" or
5265 croak "$!: $x";
5267 $migrated++;
5269 command_close_pipe($fh, $ctx);
5270 print STDERR "Done migrating from a git-svn v1 layout\n";
5271 $migrated;
5274 sub read_old_urls {
5275 my ($l_map, $pfx, $path) = @_;
5276 my @dir;
5277 foreach (<$path/*>) {
5278 if (-r "$_/info/url") {
5279 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5280 my $ref_id = $pfx . basename $_;
5281 my $url = ::file_to_s("$_/info/url");
5282 $l_map->{$ref_id} = $url;
5283 } elsif (-d $_) {
5284 push @dir, $_;
5287 foreach (@dir) {
5288 my $x = $_;
5289 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5290 read_old_urls($l_map, $x, $_);
5294 sub migrate_from_v2 {
5295 my @cfg = command(qw/config -l/);
5296 return if grep /^svn-remote\..+\.url=/, @cfg;
5297 my %l_map;
5298 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5299 my $migrated = 0;
5301 foreach my $ref_id (sort keys %l_map) {
5302 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5303 if ($@) {
5304 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5306 $migrated++;
5308 $migrated;
5311 sub minimize_connections {
5312 my $r = Git::SVN::read_all_remotes();
5313 my $new_urls = {};
5314 my $root_repos = {};
5315 foreach my $repo_id (keys %$r) {
5316 my $url = $r->{$repo_id}->{url} or next;
5317 my $fetch = $r->{$repo_id}->{fetch} or next;
5318 my $ra = Git::SVN::Ra->new($url);
5320 # skip existing cases where we already connect to the root
5321 if (($ra->{url} eq $ra->{repos_root}) ||
5322 ($ra->{repos_root} eq $repo_id)) {
5323 $root_repos->{$ra->{url}} = $repo_id;
5324 next;
5327 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5328 my $root_path = $ra->{url};
5329 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5330 foreach my $path (keys %$fetch) {
5331 my $ref_id = $fetch->{$path};
5332 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5334 # make sure we can read when connecting to
5335 # a higher level of a repository
5336 my ($last_rev, undef) = $gs->last_rev_commit;
5337 if (!defined $last_rev) {
5338 $last_rev = eval {
5339 $root_ra->get_latest_revnum;
5341 next if $@;
5343 my $new = $root_path;
5344 $new .= length $path ? "/$path" : '';
5345 eval {
5346 $root_ra->get_log([$new], $last_rev, $last_rev,
5347 0, 0, 1, sub { });
5349 next if $@;
5350 $new_urls->{$ra->{repos_root}}->{$new} =
5351 { ref_id => $ref_id,
5352 old_repo_id => $repo_id,
5353 old_path => $path };
5357 my @emptied;
5358 foreach my $url (keys %$new_urls) {
5359 # see if we can re-use an existing [svn-remote "repo_id"]
5360 # instead of creating a(n ugly) new section:
5361 my $repo_id = $root_repos->{$url} || $url;
5363 my $fetch = $new_urls->{$url};
5364 foreach my $path (keys %$fetch) {
5365 my $x = $fetch->{$path};
5366 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5367 my $pfx = "svn-remote.$x->{old_repo_id}";
5369 my $old_fetch = quotemeta("$x->{old_path}:".
5370 "refs/remotes/$x->{ref_id}");
5371 command_noisy(qw/config --unset/,
5372 "$pfx.fetch", '^'. $old_fetch . '$');
5373 delete $r->{$x->{old_repo_id}}->
5374 {fetch}->{$x->{old_path}};
5375 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5376 command_noisy(qw/config --unset/,
5377 "$pfx.url");
5378 push @emptied, $x->{old_repo_id}
5382 if (@emptied) {
5383 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5384 print STDERR <<EOF;
5385 The following [svn-remote] sections in your config file ($file) are empty
5386 and can be safely removed:
5388 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5392 sub migration_check {
5393 migrate_from_v0();
5394 migrate_from_v1();
5395 migrate_from_v2();
5396 minimize_connections() if $_minimize;
5399 package Git::IndexInfo;
5400 use strict;
5401 use warnings;
5402 use Git qw/command_input_pipe command_close_pipe/;
5404 sub new {
5405 my ($class) = @_;
5406 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5407 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5410 sub remove {
5411 my ($self, $path) = @_;
5412 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5413 return ++$self->{nr};
5415 undef;
5418 sub update {
5419 my ($self, $mode, $hash, $path) = @_;
5420 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5421 return ++$self->{nr};
5423 undef;
5426 sub DESTROY {
5427 my ($self) = @_;
5428 command_close_pipe($self->{gui}, $self->{ctx});
5431 package Git::SVN::GlobSpec;
5432 use strict;
5433 use warnings;
5435 sub new {
5436 my ($class, $glob) = @_;
5437 my $re = $glob;
5438 $re =~ s!/+$!!g; # no need for trailing slashes
5439 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5440 my $temp = $re;
5441 my ($left, $right) = ($1, $3);
5442 $re = $2;
5443 my $depth = $re =~ tr/*/*/;
5444 if ($depth != $temp =~ tr/*/*/) {
5445 die "Only one set of wildcard directories " .
5446 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5448 if ($depth == 0) {
5449 die "One '*' is needed for glob: '$glob'\n";
5451 $re =~ s!\*!\[^/\]*!g;
5452 $re = quotemeta($left) . "($re)" . quotemeta($right);
5453 if (length $left && !($left =~ s!/+$!!g)) {
5454 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5456 if (length $right && !($right =~ s!^/+!!g)) {
5457 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5459 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5460 bless { left => $left, right => $right, left_regex => $left_re,
5461 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5464 sub full_path {
5465 my ($self, $path) = @_;
5466 return (length $self->{left} ? "$self->{left}/" : '') .
5467 $path . (length $self->{right} ? "/$self->{right}" : '');
5470 __END__
5472 Data structures:
5475 $remotes = { # returned by read_all_remotes()
5476 'svn' => {
5477 # svn-remote.svn.url=https://svn.musicpd.org
5478 url => 'https://svn.musicpd.org',
5479 # svn-remote.svn.fetch=mpd/trunk:trunk
5480 fetch => {
5481 'mpd/trunk' => 'trunk',
5483 # svn-remote.svn.tags=mpd/tags/*:tags/*
5484 tags => {
5485 path => {
5486 left => 'mpd/tags',
5487 right => '',
5488 regex => qr!mpd/tags/([^/]+)$!,
5489 glob => 'tags/*',
5491 ref => {
5492 left => 'tags',
5493 right => '',
5494 regex => qr!tags/([^/]+)$!,
5495 glob => 'tags/*',
5501 $log_entry hashref as returned by libsvn_log_entry()
5503 log => 'whitespace-formatted log entry
5504 ', # trailing newline is preserved
5505 revision => '8', # integer
5506 date => '2004-02-24T17:01:44.108345Z', # commit date
5507 author => 'committer name'
5511 # this is generated by generate_diff();
5512 @mods = array of diff-index line hashes, each element represents one line
5513 of diff-index output
5515 diff-index line ($m hash)
5517 mode_a => first column of diff-index output, no leading ':',
5518 mode_b => second column of diff-index output,
5519 sha1_b => sha1sum of the final blob,
5520 chg => change type [MCRADT],
5521 file_a => original file name of a file (iff chg is 'C' or 'R')
5522 file_b => new/current file name of a file (any chg)
5526 # retval of read_url_paths{,_all}();
5527 $l_map = {
5528 # repository root url
5529 'https://svn.musicpd.org' => {
5530 # repository path # GIT_SVN_ID
5531 'mpd/trunk' => 'trunk',
5532 'mpd/tags/0.11.5' => 'tags/0.11.5',
5536 Notes:
5537 I don't trust the each() function on unless I created %hash myself
5538 because the internal iterator may not have started at base.