t5516: Use test_cmp when appropriate
[git/mingw.git] / git-svn.perl
blob265852f4596bfe5aeca12be06f78631320b8ebb4
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;
22 $Git::SVN::_minimize_url = 'unset';
24 if (! exists $ENV{SVN_SSH}) {
25 if (exists $ENV{GIT_SSH}) {
26 $ENV{SVN_SSH} = $ENV{GIT_SSH};
27 if ($^O eq 'msys') {
28 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
29 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
34 $Git::SVN::Log::TZ = $ENV{TZ};
35 $ENV{TZ} = 'UTC';
36 $| = 1; # unbuffer STDOUT
38 sub fatal (@) { print STDERR "@_\n"; exit 1 }
39 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
40 require SVN::Ra;
41 require SVN::Delta;
42 if ($SVN::Core::VERSION lt '1.1.0') {
43 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
45 my $can_compress = eval { require Compress::Zlib; 1};
46 push @Git::SVN::Ra::ISA, 'SVN::Ra';
47 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
48 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
49 use Carp qw/croak/;
50 use Digest::MD5;
51 use IO::File qw//;
52 use File::Basename qw/dirname basename/;
53 use File::Path qw/mkpath/;
54 use File::Spec;
55 use File::Find;
56 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
57 use IPC::Open3;
58 use Git;
60 BEGIN {
61 # import functions from Git into our packages, en masse
62 no strict 'refs';
63 foreach (qw/command command_oneline command_noisy command_output_pipe
64 command_input_pipe command_close_pipe
65 command_bidi_pipe command_close_bidi_pipe/) {
66 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
67 Git::SVN::Migration Git::SVN::Log Git::SVN),
68 __PACKAGE__) {
69 *{"${package}::$_"} = \&{"Git::$_"};
74 my ($SVN);
76 $sha1 = qr/[a-f\d]{40}/;
77 $sha1_short = qr/[a-f\d]{4,40}/;
78 my ($_stdin, $_help, $_edit,
79 $_message, $_file, $_branch_dest,
80 $_template, $_shared,
81 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
82 $_merge, $_strategy, $_dry_run, $_local,
83 $_prefix, $_no_checkout, $_url, $_verbose,
84 $_git_format, $_commit_url, $_tag);
85 $Git::SVN::_follow_parent = 1;
86 $_q ||= 0;
87 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
88 'config-dir=s' => \$Git::SVN::Ra::config_dir,
89 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
90 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
91 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
92 'authors-file|A=s' => \$_authors,
93 'authors-prog=s' => \$_authors_prog,
94 'repack:i' => \$Git::SVN::_repack,
95 'noMetadata' => \$Git::SVN::_no_metadata,
96 'useSvmProps' => \$Git::SVN::_use_svm_props,
97 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
98 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
99 'no-checkout' => \$_no_checkout,
100 'quiet|q+' => \$_q,
101 'repack-flags|repack-args|repack-opts=s' =>
102 \$Git::SVN::_repack_flags,
103 'use-log-author' => \$Git::SVN::_use_log_author,
104 'add-author-from' => \$Git::SVN::_add_author_from,
105 'localtime' => \$Git::SVN::_localtime,
106 %remote_opts );
108 my ($_trunk, @_tags, @_branches, $_stdlayout);
109 my %icv;
110 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
111 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
112 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
113 'stdlayout|s' => \$_stdlayout,
114 'minimize-url|m!' => \$Git::SVN::_minimize_url,
115 'no-metadata' => sub { $icv{noMetadata} = 1 },
116 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
117 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
118 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
119 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
120 %remote_opts );
121 my %cmt_opts = ( 'edit|e' => \$_edit,
122 'rmdir' => \$SVN::Git::Editor::_rmdir,
123 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
124 'l=i' => \$SVN::Git::Editor::_rename_limit,
125 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
128 my %cmd = (
129 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
130 { 'revision|r=s' => \$_revision,
131 'fetch-all|all' => \$_fetch_all,
132 'parent|p' => \$_fetch_parent,
133 %fc_opts } ],
134 clone => [ \&cmd_clone, "Initialize and fetch revisions",
135 { 'revision|r=s' => \$_revision,
136 %fc_opts, %init_opts } ],
137 init => [ \&cmd_init, "Initialize a repo for tracking" .
138 " (requires URL argument)",
139 \%init_opts ],
140 'multi-init' => [ \&cmd_multi_init,
141 "Deprecated alias for ".
142 "'$0 init -T<trunk> -b<branches> -t<tags>'",
143 \%init_opts ],
144 dcommit => [ \&cmd_dcommit,
145 'Commit several diffs to merge with upstream',
146 { 'merge|m|M' => \$_merge,
147 'strategy|s=s' => \$_strategy,
148 'verbose|v' => \$_verbose,
149 'dry-run|n' => \$_dry_run,
150 'fetch-all|all' => \$_fetch_all,
151 'commit-url=s' => \$_commit_url,
152 'revision|r=i' => \$_revision,
153 'no-rebase' => \$_no_rebase,
154 %cmt_opts, %fc_opts } ],
155 branch => [ \&cmd_branch,
156 'Create a branch in the SVN repository',
157 { 'message|m=s' => \$_message,
158 'destination|d=s' => \$_branch_dest,
159 'dry-run|n' => \$_dry_run,
160 'tag|t' => \$_tag,
161 'username=s' => \$Git::SVN::Prompt::_username,
162 'commit-url=s' => \$_commit_url } ],
163 tag => [ sub { $_tag = 1; cmd_branch(@_) },
164 'Create a tag in the SVN repository',
165 { 'message|m=s' => \$_message,
166 'destination|d=s' => \$_branch_dest,
167 'dry-run|n' => \$_dry_run,
168 'username=s' => \$Git::SVN::Prompt::_username,
169 'commit-url=s' => \$_commit_url } ],
170 'set-tree' => [ \&cmd_set_tree,
171 "Set an SVN repository to a git tree-ish",
172 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
173 'create-ignore' => [ \&cmd_create_ignore,
174 'Create a .gitignore per svn:ignore',
175 { 'revision|r=i' => \$_revision
176 } ],
177 'mkdirs' => [ \&cmd_mkdirs ,
178 "recreate empty directories after a checkout",
179 { 'revision|r=i' => \$_revision } ],
180 'propget' => [ \&cmd_propget,
181 'Print the value of a property on a file or directory',
182 { 'revision|r=i' => \$_revision } ],
183 'proplist' => [ \&cmd_proplist,
184 'List all properties of a file or directory',
185 { 'revision|r=i' => \$_revision } ],
186 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
187 { 'revision|r=i' => \$_revision
188 } ],
189 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
190 { 'revision|r=i' => \$_revision
191 } ],
192 'multi-fetch' => [ \&cmd_multi_fetch,
193 "Deprecated alias for $0 fetch --all",
194 { 'revision|r=s' => \$_revision, %fc_opts } ],
195 'migrate' => [ sub { },
196 # no-op, we automatically run this anyways,
197 'Migrate configuration/metadata/layout from
198 previous versions of git-svn',
199 { 'minimize' => \$Git::SVN::Migration::_minimize,
200 %remote_opts } ],
201 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
202 { 'limit=i' => \$Git::SVN::Log::limit,
203 'revision|r=s' => \$_revision,
204 'verbose|v' => \$Git::SVN::Log::verbose,
205 'incremental' => \$Git::SVN::Log::incremental,
206 'oneline' => \$Git::SVN::Log::oneline,
207 'show-commit' => \$Git::SVN::Log::show_commit,
208 'non-recursive' => \$Git::SVN::Log::non_recursive,
209 'authors-file|A=s' => \$_authors,
210 'color' => \$Git::SVN::Log::color,
211 'pager=s' => \$Git::SVN::Log::pager
212 } ],
213 'find-rev' => [ \&cmd_find_rev,
214 "Translate between SVN revision numbers and tree-ish",
215 {} ],
216 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
217 { 'merge|m|M' => \$_merge,
218 'verbose|v' => \$_verbose,
219 'strategy|s=s' => \$_strategy,
220 'local|l' => \$_local,
221 'fetch-all|all' => \$_fetch_all,
222 'dry-run|n' => \$_dry_run,
223 %fc_opts } ],
224 'commit-diff' => [ \&cmd_commit_diff,
225 'Commit a diff between two trees',
226 { 'message|m=s' => \$_message,
227 'file|F=s' => \$_file,
228 'revision|r=s' => \$_revision,
229 %cmt_opts } ],
230 'info' => [ \&cmd_info,
231 "Show info about the latest SVN revision
232 on the current branch",
233 { 'url' => \$_url, } ],
234 'blame' => [ \&Git::SVN::Log::cmd_blame,
235 "Show what revision and author last modified each line of a file",
236 { 'git-format' => \$_git_format } ],
237 'reset' => [ \&cmd_reset,
238 "Undo fetches back to the specified SVN revision",
239 { 'revision|r=s' => \$_revision,
240 'parent|p' => \$_fetch_parent } ],
241 'gc' => [ \&cmd_gc,
242 "Compress unhandled.log files in .git/svn and remove " .
243 "index files in .git/svn",
244 {} ],
247 my $cmd;
248 for (my $i = 0; $i < @ARGV; $i++) {
249 if (defined $cmd{$ARGV[$i]}) {
250 $cmd = $ARGV[$i];
251 splice @ARGV, $i, 1;
252 last;
253 } elsif ($ARGV[$i] eq 'help') {
254 $cmd = $ARGV[$i+1];
255 usage(0);
259 # make sure we're always running at the top-level working directory
260 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
261 unless (-d $ENV{GIT_DIR}) {
262 if ($git_dir_user_set) {
263 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
264 "but it is not a directory\n";
266 my $git_dir = delete $ENV{GIT_DIR};
267 my $cdup = undef;
268 git_cmd_try {
269 $cdup = command_oneline(qw/rev-parse --show-cdup/);
270 $git_dir = '.' unless ($cdup);
271 chomp $cdup if ($cdup);
272 $cdup = "." unless ($cdup && length $cdup);
273 } "Already at toplevel, but $git_dir not found\n";
274 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
275 unless (-d $git_dir) {
276 die "$git_dir still not found after going to ",
277 "'$cdup'\n";
279 $ENV{GIT_DIR} = $git_dir;
281 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
284 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
286 read_git_config(\%opts);
287 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
288 Getopt::Long::Configure('pass_through');
290 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
291 'minimize-connections' => \$Git::SVN::Migration::_minimize,
292 'id|i=s' => \$Git::SVN::default_ref_id,
293 'svn-remote|remote|R=s' => sub {
294 $Git::SVN::no_reuse_existing = 1;
295 $Git::SVN::default_repo_id = $_[1] });
296 exit 1 if (!$rv && $cmd && $cmd ne 'log');
298 usage(0) if $_help;
299 version() if $_version;
300 usage(1) unless defined $cmd;
301 load_authors() if $_authors;
302 if (defined $_authors_prog) {
303 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
306 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
307 Git::SVN::Migration::migration_check();
309 Git::SVN::init_vars();
310 eval {
311 Git::SVN::verify_remotes_sanity();
312 $cmd{$cmd}->[0]->(@ARGV);
314 fatal $@ if $@;
315 post_fetch_checkout();
316 exit 0;
318 ####################### primary functions ######################
319 sub usage {
320 my $exit = shift || 0;
321 my $fd = $exit ? \*STDERR : \*STDOUT;
322 print $fd <<"";
323 git-svn - bidirectional operations between a single Subversion tree and git
324 Usage: git svn <command> [options] [arguments]\n
326 print $fd "Available commands:\n" unless $cmd;
328 foreach (sort keys %cmd) {
329 next if $cmd && $cmd ne $_;
330 next if /^multi-/; # don't show deprecated commands
331 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
332 foreach (sort keys %{$cmd{$_}->[2]}) {
333 # mixed-case options are for .git/config only
334 next if /[A-Z]/ && /^[a-z]+$/i;
335 # prints out arguments as they should be passed:
336 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
337 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
338 "--$_" : "-$_" }
339 split /\|/,$_)," $x\n";
342 print $fd <<"";
343 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
344 arbitrary identifier if you're tracking multiple SVN branches/repositories in
345 one git repository and want to keep them separate. See git-svn(1) for more
346 information.
348 exit $exit;
351 sub version {
352 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
353 exit 0;
356 sub do_git_init_db {
357 unless (-d $ENV{GIT_DIR}) {
358 my @init_db = ('init');
359 push @init_db, "--template=$_template" if defined $_template;
360 if (defined $_shared) {
361 if ($_shared =~ /[a-z]/) {
362 push @init_db, "--shared=$_shared";
363 } else {
364 push @init_db, "--shared";
367 command_noisy(@init_db);
368 $_repository = Git->repository(Repository => ".git");
370 command_noisy('config', 'core.autocrlf', 'false');
371 my $set;
372 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
373 foreach my $i (keys %icv) {
374 die "'$set' and '$i' cannot both be set\n" if $set;
375 next unless defined $icv{$i};
376 command_noisy('config', "$pfx.$i", $icv{$i});
377 $set = $i;
379 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
380 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
381 if defined $$ignore_regex;
384 sub init_subdir {
385 my $repo_path = shift or return;
386 mkpath([$repo_path]) unless -d $repo_path;
387 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
388 $ENV{GIT_DIR} = '.git';
389 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
392 sub cmd_clone {
393 my ($url, $path) = @_;
394 if (!defined $path &&
395 (defined $_trunk || @_branches || @_tags ||
396 defined $_stdlayout) &&
397 $url !~ m#^[a-z\+]+://#) {
398 $path = $url;
400 $path = basename($url) if !defined $path || !length $path;
401 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
402 cmd_init($url, $path);
403 command_oneline('config', 'svn.authorsfile', $authors_absolute)
404 if $_authors;
405 Git::SVN::fetch_all($Git::SVN::default_repo_id);
408 sub cmd_init {
409 if (defined $_stdlayout) {
410 $_trunk = 'trunk' if (!defined $_trunk);
411 @_tags = 'tags' if (! @_tags);
412 @_branches = 'branches' if (! @_branches);
414 if (defined $_trunk || @_branches || @_tags) {
415 return cmd_multi_init(@_);
417 my $url = shift or die "SVN repository location required ",
418 "as a command-line argument\n";
419 $url = canonicalize_url($url);
420 init_subdir(@_);
421 do_git_init_db();
423 if ($Git::SVN::_minimize_url eq 'unset') {
424 $Git::SVN::_minimize_url = 0;
427 Git::SVN->init($url);
430 sub cmd_fetch {
431 if (grep /^\d+=./, @_) {
432 die "'<rev>=<commit>' fetch arguments are ",
433 "no longer supported.\n";
435 my ($remote) = @_;
436 if (@_ > 1) {
437 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
439 $Git::SVN::no_reuse_existing = undef;
440 if ($_fetch_parent) {
441 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
442 unless ($gs) {
443 die "Unable to determine upstream SVN information from ",
444 "working tree history\n";
446 # just fetch, don't checkout.
447 $_no_checkout = 'true';
448 $_fetch_all ? $gs->fetch_all : $gs->fetch;
449 } elsif ($_fetch_all) {
450 cmd_multi_fetch();
451 } else {
452 $remote ||= $Git::SVN::default_repo_id;
453 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
457 sub cmd_set_tree {
458 my (@commits) = @_;
459 if ($_stdin || !@commits) {
460 print "Reading from stdin...\n";
461 @commits = ();
462 while (<STDIN>) {
463 if (/\b($sha1_short)\b/o) {
464 unshift @commits, $1;
468 my @revs;
469 foreach my $c (@commits) {
470 my @tmp = command('rev-parse',$c);
471 if (scalar @tmp == 1) {
472 push @revs, $tmp[0];
473 } elsif (scalar @tmp > 1) {
474 push @revs, reverse(command('rev-list',@tmp));
475 } else {
476 fatal "Failed to rev-parse $c";
479 my $gs = Git::SVN->new;
480 my ($r_last, $cmt_last) = $gs->last_rev_commit;
481 $gs->fetch;
482 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
483 fatal "There are new revisions that were fetched ",
484 "and need to be merged (or acknowledged) ",
485 "before committing.\nlast rev: $r_last\n",
486 " current: $gs->{last_rev}";
488 $gs->set_tree($_) foreach @revs;
489 print "Done committing ",scalar @revs," revisions to SVN\n";
490 unlink $gs->{index};
493 sub cmd_dcommit {
494 my $head = shift;
495 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
496 'Cannot dcommit with a dirty index. Commit your changes first, '
497 . "or stash them with `git stash'.\n";
498 $head ||= 'HEAD';
500 my $old_head;
501 if ($head ne 'HEAD') {
502 $old_head = eval {
503 command_oneline([qw/symbolic-ref -q HEAD/])
505 if ($old_head) {
506 $old_head =~ s{^refs/heads/}{};
507 } else {
508 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
510 command(['checkout', $head], STDERR => 0);
513 my @refs;
514 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
515 unless ($gs) {
516 die "Unable to determine upstream SVN information from ",
517 "$head history.\nPerhaps the repository is empty.";
520 if (defined $_commit_url) {
521 $url = $_commit_url;
522 } else {
523 $url = eval { command_oneline('config', '--get',
524 "svn-remote.$gs->{repo_id}.commiturl") };
525 if (!$url) {
526 $url = $gs->full_url
530 my $last_rev = $_revision if defined $_revision;
531 if ($url) {
532 print "Committing to $url ...\n";
534 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
535 if ($_no_rebase && scalar(@$linear_refs) > 1) {
536 warn "Attempting to commit more than one change while ",
537 "--no-rebase is enabled.\n",
538 "If these changes depend on each other, re-running ",
539 "without --no-rebase may be required."
541 my $expect_url = $url;
542 Git::SVN::remove_username($expect_url);
543 while (1) {
544 my $d = shift @$linear_refs or last;
545 unless (defined $last_rev) {
546 (undef, $last_rev, undef) = cmt_metadata("$d~1");
547 unless (defined $last_rev) {
548 fatal "Unable to extract revision information ",
549 "from commit $d~1";
552 if ($_dry_run) {
553 print "diff-tree $d~1 $d\n";
554 } else {
555 my $cmt_rev;
556 my %ed_opts = ( r => $last_rev,
557 log => get_commit_entry($d)->{log},
558 ra => Git::SVN::Ra->new($url),
559 config => SVN::Core::config_get_config(
560 $Git::SVN::Ra::config_dir
562 tree_a => "$d~1",
563 tree_b => $d,
564 editor_cb => sub {
565 print "Committed r$_[0]\n";
566 $cmt_rev = $_[0];
568 svn_path => '');
569 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
570 print "No changes\n$d~1 == $d\n";
571 } elsif ($parents->{$d} && @{$parents->{$d}}) {
572 $gs->{inject_parents_dcommit}->{$cmt_rev} =
573 $parents->{$d};
575 $_fetch_all ? $gs->fetch_all : $gs->fetch;
576 $last_rev = $cmt_rev;
577 next if $_no_rebase;
579 # we always want to rebase against the current HEAD,
580 # not any head that was passed to us
581 my @diff = command('diff-tree', $d,
582 $gs->refname, '--');
583 my @finish;
584 if (@diff) {
585 @finish = rebase_cmd();
586 print STDERR "W: $d and ", $gs->refname,
587 " differ, using @finish:\n",
588 join("\n", @diff), "\n";
589 } else {
590 print "No changes between current HEAD and ",
591 $gs->refname,
592 "\nResetting to the latest ",
593 $gs->refname, "\n";
594 @finish = qw/reset --mixed/;
596 command_noisy(@finish, $gs->refname);
597 if (@diff) {
598 @refs = ();
599 my ($url_, $rev_, $uuid_, $gs_) =
600 working_head_info('HEAD', \@refs);
601 my ($linear_refs_, $parents_) =
602 linearize_history($gs_, \@refs);
603 if (scalar(@$linear_refs) !=
604 scalar(@$linear_refs_)) {
605 fatal "# of revisions changed ",
606 "\nbefore:\n",
607 join("\n", @$linear_refs),
608 "\n\nafter:\n",
609 join("\n", @$linear_refs_), "\n",
610 'If you are attempting to commit ',
611 "merges, try running:\n\t",
612 'git rebase --interactive',
613 '--preserve-merges ',
614 $gs->refname,
615 "\nBefore dcommitting";
617 if ($url_ ne $expect_url) {
618 if ($url_ eq $gs->metadata_url) {
619 print
620 "Accepting rewritten URL:",
621 " $url_\n";
622 } else {
623 fatal
624 "URL mismatch after rebase:",
625 " $url_ != $expect_url";
628 if ($uuid_ ne $uuid) {
629 fatal "uuid mismatch after rebase: ",
630 "$uuid_ != $uuid";
632 # remap parents
633 my (%p, @l, $i);
634 for ($i = 0; $i < scalar @$linear_refs; $i++) {
635 my $new = $linear_refs_->[$i] or next;
636 $p{$new} =
637 $parents->{$linear_refs->[$i]};
638 push @l, $new;
640 $parents = \%p;
641 $linear_refs = \@l;
646 if ($old_head) {
647 my $new_head = command_oneline(qw/rev-parse HEAD/);
648 my $new_is_symbolic = eval {
649 command_oneline(qw/symbolic-ref -q HEAD/);
651 if ($new_is_symbolic) {
652 print "dcommitted the branch ", $head, "\n";
653 } else {
654 print "dcommitted on a detached HEAD because you gave ",
655 "a revision argument.\n",
656 "The rewritten commit is: ", $new_head, "\n";
658 command(['checkout', $old_head], STDERR => 0);
661 unlink $gs->{index};
664 sub cmd_branch {
665 my ($branch_name, $head) = @_;
667 unless (defined $branch_name && length $branch_name) {
668 die(($_tag ? "tag" : "branch") . " name required\n");
670 $head ||= 'HEAD';
672 my (undef, $rev, undef, $gs) = working_head_info($head);
673 my $src = $gs->full_url;
675 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
676 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
677 my $glob;
678 if ($#{$allglobs} == 0) {
679 $glob = $allglobs->[0];
680 } else {
681 unless(defined $_branch_dest) {
682 die "Multiple ",
683 $_tag ? "tag" : "branch",
684 " paths defined for Subversion repository.\n",
685 "You must specify where you want to create the ",
686 $_tag ? "tag" : "branch",
687 " with the --destination argument.\n";
689 foreach my $g (@{$allglobs}) {
690 # SVN::Git::Editor could probably be moved to Git.pm..
691 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
692 if ($_branch_dest =~ /$re/) {
693 $glob = $g;
694 last;
697 unless (defined $glob) {
698 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
699 foreach my $g (@{$allglobs}) {
700 $g->{path}->{left} =~ /$dest_re/ or next;
701 if (defined $glob) {
702 die "Ambiguous destination: ",
703 $_branch_dest, "\nmatches both '",
704 $glob->{path}->{left}, "' and '",
705 $g->{path}->{left}, "'\n";
707 $glob = $g;
709 unless (defined $glob) {
710 die "Unknown ",
711 $_tag ? "tag" : "branch",
712 " destination $_branch_dest\n";
716 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
717 my $url;
718 if (defined $_commit_url) {
719 $url = $_commit_url;
720 } else {
721 $url = eval { command_oneline('config', '--get',
722 "svn-remote.$gs->{repo_id}.commiturl") };
723 if (!$url) {
724 $url = $remote->{url};
727 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
729 if ($dst =~ /^https:/ && $src =~ /^http:/) {
730 $src=~s/^http:/https:/;
733 my $ctx = SVN::Client->new(
734 auth => Git::SVN::Ra::_auth_providers(),
735 log_msg => sub {
736 ${ $_[0] } = defined $_message
737 ? $_message
738 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
739 . $branch_name;
743 eval {
744 $ctx->ls($dst, 'HEAD', 0);
745 } and die "branch ${branch_name} already exists\n";
747 print "Copying ${src} at r${rev} to ${dst}...\n";
748 $ctx->copy($src, $rev, $dst)
749 unless $_dry_run;
751 $gs->fetch_all;
754 sub cmd_find_rev {
755 my $revision_or_hash = shift or die "SVN or git revision required ",
756 "as a command-line argument\n";
757 my $result;
758 if ($revision_or_hash =~ /^r\d+$/) {
759 my $head = shift;
760 $head ||= 'HEAD';
761 my @refs;
762 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
763 unless ($gs) {
764 die "Unable to determine upstream SVN information from ",
765 "$head history\n";
767 my $desired_revision = substr($revision_or_hash, 1);
768 $result = $gs->rev_map_get($desired_revision, $uuid);
769 } else {
770 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
771 $result = $rev;
773 print "$result\n" if $result;
776 sub cmd_rebase {
777 command_noisy(qw/update-index --refresh/);
778 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
779 unless ($gs) {
780 die "Unable to determine upstream SVN information from ",
781 "working tree history\n";
783 if ($_dry_run) {
784 print "Remote Branch: " . $gs->refname . "\n";
785 print "SVN URL: " . $url . "\n";
786 return;
788 if (command(qw/diff-index HEAD --/)) {
789 print STDERR "Cannot rebase with uncommited changes:\n";
790 command_noisy('status');
791 exit 1;
793 unless ($_local) {
794 # rebase will checkout for us, so no need to do it explicitly
795 $_no_checkout = 'true';
796 $_fetch_all ? $gs->fetch_all : $gs->fetch;
798 command_noisy(rebase_cmd(), $gs->refname);
799 $gs->mkemptydirs;
802 sub cmd_show_ignore {
803 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
804 $gs ||= Git::SVN->new;
805 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
806 $gs->prop_walk($gs->{path}, $r, sub {
807 my ($gs, $path, $props) = @_;
808 print STDOUT "\n# $path\n";
809 my $s = $props->{'svn:ignore'} or return;
810 $s =~ s/[\r\n]+/\n/g;
811 $s =~ s/^\n+//;
812 chomp $s;
813 $s =~ s#^#$path#gm;
814 print STDOUT "$s\n";
818 sub cmd_show_externals {
819 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
820 $gs ||= Git::SVN->new;
821 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
822 $gs->prop_walk($gs->{path}, $r, sub {
823 my ($gs, $path, $props) = @_;
824 print STDOUT "\n# $path\n";
825 my $s = $props->{'svn:externals'} or return;
826 $s =~ s/[\r\n]+/\n/g;
827 chomp $s;
828 $s =~ s#^#$path#gm;
829 print STDOUT "$s\n";
833 sub cmd_create_ignore {
834 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
835 $gs ||= Git::SVN->new;
836 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
837 $gs->prop_walk($gs->{path}, $r, sub {
838 my ($gs, $path, $props) = @_;
839 # $path is of the form /path/to/dir/
840 $path = '.' . $path;
841 # SVN can have attributes on empty directories,
842 # which git won't track
843 mkpath([$path]) unless -d $path;
844 my $ignore = $path . '.gitignore';
845 my $s = $props->{'svn:ignore'} or return;
846 open(GITIGNORE, '>', $ignore)
847 or fatal("Failed to open `$ignore' for writing: $!");
848 $s =~ s/[\r\n]+/\n/g;
849 $s =~ s/^\n+//;
850 chomp $s;
851 # Prefix all patterns so that the ignore doesn't apply
852 # to sub-directories.
853 $s =~ s#^#/#gm;
854 print GITIGNORE "$s\n";
855 close(GITIGNORE)
856 or fatal("Failed to close `$ignore': $!");
857 command_noisy('add', '-f', $ignore);
861 sub cmd_mkdirs {
862 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
863 $gs ||= Git::SVN->new;
864 $gs->mkemptydirs($_revision);
867 sub canonicalize_path {
868 my ($path) = @_;
869 my $dot_slash_added = 0;
870 if (substr($path, 0, 1) ne "/") {
871 $path = "./" . $path;
872 $dot_slash_added = 1;
874 # File::Spec->canonpath doesn't collapse x/../y into y (for a
875 # good reason), so let's do this manually.
876 $path =~ s#/+#/#g;
877 $path =~ s#/\.(?:/|$)#/#g;
878 $path =~ s#/[^/]+/\.\.##g;
879 $path =~ s#/$##g;
880 $path =~ s#^\./## if $dot_slash_added;
881 $path =~ s#^/##;
882 $path =~ s#^\.$##;
883 return $path;
886 sub canonicalize_url {
887 my ($url) = @_;
888 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
889 return $url;
892 # get_svnprops(PATH)
893 # ------------------
894 # Helper for cmd_propget and cmd_proplist below.
895 sub get_svnprops {
896 my $path = shift;
897 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
898 $gs ||= Git::SVN->new;
900 # prefix THE PATH by the sub-directory from which the user
901 # invoked us.
902 $path = $cmd_dir_prefix . $path;
903 fatal("No such file or directory: $path") unless -e $path;
904 my $is_dir = -d $path ? 1 : 0;
905 $path = $gs->{path} . '/' . $path;
907 # canonicalize the path (otherwise libsvn will abort or fail to
908 # find the file)
909 $path = canonicalize_path($path);
911 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
912 my $props;
913 if ($is_dir) {
914 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
916 else {
917 (undef, $props) = $gs->ra->get_file($path, $r, undef);
919 return $props;
922 # cmd_propget (PROP, PATH)
923 # ------------------------
924 # Print the SVN property PROP for PATH.
925 sub cmd_propget {
926 my ($prop, $path) = @_;
927 $path = '.' if not defined $path;
928 usage(1) if not defined $prop;
929 my $props = get_svnprops($path);
930 if (not defined $props->{$prop}) {
931 fatal("`$path' does not have a `$prop' SVN property.");
933 print $props->{$prop} . "\n";
936 # cmd_proplist (PATH)
937 # -------------------
938 # Print the list of SVN properties for PATH.
939 sub cmd_proplist {
940 my $path = shift;
941 $path = '.' if not defined $path;
942 my $props = get_svnprops($path);
943 print "Properties on '$path':\n";
944 foreach (sort keys %{$props}) {
945 print " $_\n";
949 sub cmd_multi_init {
950 my $url = shift;
951 unless (defined $_trunk || @_branches || @_tags) {
952 usage(1);
955 $_prefix = '' unless defined $_prefix;
956 if (defined $url) {
957 $url = canonicalize_url($url);
958 init_subdir(@_);
960 do_git_init_db();
961 if (defined $_trunk) {
962 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
963 # try both old-style and new-style lookups:
964 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
965 unless ($gs_trunk) {
966 my ($trunk_url, $trunk_path) =
967 complete_svn_url($url, $_trunk);
968 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
969 undef, $trunk_ref);
972 return unless @_branches || @_tags;
973 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
974 foreach my $path (@_branches) {
975 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
977 foreach my $path (@_tags) {
978 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
982 sub cmd_multi_fetch {
983 $Git::SVN::no_reuse_existing = undef;
984 my $remotes = Git::SVN::read_all_remotes();
985 foreach my $repo_id (sort keys %$remotes) {
986 if ($remotes->{$repo_id}->{url}) {
987 Git::SVN::fetch_all($repo_id, $remotes);
992 # this command is special because it requires no metadata
993 sub cmd_commit_diff {
994 my ($ta, $tb, $url) = @_;
995 my $usage = "Usage: $0 commit-diff -r<revision> ".
996 "<tree-ish> <tree-ish> [<URL>]";
997 fatal($usage) if (!defined $ta || !defined $tb);
998 my $svn_path = '';
999 if (!defined $url) {
1000 my $gs = eval { Git::SVN->new };
1001 if (!$gs) {
1002 fatal("Needed URL or usable git-svn --id in ",
1003 "the command-line\n", $usage);
1005 $url = $gs->{url};
1006 $svn_path = $gs->{path};
1008 unless (defined $_revision) {
1009 fatal("-r|--revision is a required argument\n", $usage);
1011 if (defined $_message && defined $_file) {
1012 fatal("Both --message/-m and --file/-F specified ",
1013 "for the commit message.\n",
1014 "I have no idea what you mean");
1016 if (defined $_file) {
1017 $_message = file_to_s($_file);
1018 } else {
1019 $_message ||= get_commit_entry($tb)->{log};
1021 my $ra ||= Git::SVN::Ra->new($url);
1022 my $r = $_revision;
1023 if ($r eq 'HEAD') {
1024 $r = $ra->get_latest_revnum;
1025 } elsif ($r !~ /^\d+$/) {
1026 die "revision argument: $r not understood by git-svn\n";
1028 my %ed_opts = ( r => $r,
1029 log => $_message,
1030 ra => $ra,
1031 tree_a => $ta,
1032 tree_b => $tb,
1033 editor_cb => sub { print "Committed r$_[0]\n" },
1034 svn_path => $svn_path );
1035 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1036 print "No changes\n$ta == $tb\n";
1040 sub escape_uri_only {
1041 my ($uri) = @_;
1042 my @tmp;
1043 foreach (split m{/}, $uri) {
1044 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1045 push @tmp, $_;
1047 join('/', @tmp);
1050 sub escape_url {
1051 my ($url) = @_;
1052 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1053 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1054 $url = "$scheme://$domain$uri";
1056 $url;
1059 sub cmd_info {
1060 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1061 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1062 if (exists $_[1]) {
1063 die "Too many arguments specified\n";
1066 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1068 if (!$file_type && !$diff_status) {
1069 print STDERR "svn: '$path' is not under version control\n";
1070 exit 1;
1073 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1074 unless ($gs) {
1075 die "Unable to determine upstream SVN information from ",
1076 "working tree history\n";
1079 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1080 $path = "." if $path eq "";
1082 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1084 if ($_url) {
1085 print escape_url($full_url), "\n";
1086 return;
1089 my $result = "Path: $path\n";
1090 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1091 $result .= "URL: " . escape_url($full_url) . "\n";
1093 eval {
1094 my $repos_root = $gs->repos_root;
1095 Git::SVN::remove_username($repos_root);
1096 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1098 if ($@) {
1099 $result .= "Repository Root: (offline)\n";
1101 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1102 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1103 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1105 $result .= "Node Kind: " .
1106 ($file_type eq "dir" ? "directory" : "file") . "\n";
1108 my $schedule = $diff_status eq "A"
1109 ? "add"
1110 : ($diff_status eq "D" ? "delete" : "normal");
1111 $result .= "Schedule: $schedule\n";
1113 if ($diff_status eq "A") {
1114 print $result, "\n";
1115 return;
1118 my ($lc_author, $lc_rev, $lc_date_utc);
1119 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1120 my $log = command_output_pipe(@args);
1121 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1122 while (<$log>) {
1123 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1124 $lc_author = $1;
1125 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1126 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1127 (undef, $lc_rev, undef) = ::extract_metadata($1);
1130 close $log;
1132 Git::SVN::Log::set_local_timezone();
1134 $result .= "Last Changed Author: $lc_author\n";
1135 $result .= "Last Changed Rev: $lc_rev\n";
1136 $result .= "Last Changed Date: " .
1137 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1139 if ($file_type ne "dir") {
1140 my $text_last_updated_date =
1141 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1142 $result .=
1143 "Text Last Updated: " .
1144 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1145 "\n";
1146 my $checksum;
1147 if ($diff_status eq "D") {
1148 my ($fh, $ctx) =
1149 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1150 if ($file_type eq "link") {
1151 my $file_name = <$fh>;
1152 $checksum = md5sum("link $file_name");
1153 } else {
1154 $checksum = md5sum($fh);
1156 command_close_pipe($fh, $ctx);
1157 } elsif ($file_type eq "link") {
1158 my $file_name =
1159 command(qw(cat-file blob), "HEAD:$path");
1160 $checksum =
1161 md5sum("link " . $file_name);
1162 } else {
1163 open FILE, "<", $path or die $!;
1164 $checksum = md5sum(\*FILE);
1165 close FILE or die $!;
1167 $result .= "Checksum: " . $checksum . "\n";
1170 print $result, "\n";
1173 sub cmd_reset {
1174 my $target = shift || $_revision or die "SVN revision required\n";
1175 $target = $1 if $target =~ /^r(\d+)$/;
1176 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1177 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1178 unless ($gs) {
1179 die "Unable to determine upstream SVN information from ".
1180 "history\n";
1182 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1183 $gs->rev_map_set($r, $c, 'reset', $uuid);
1184 print "r$r = $c ($gs->{ref_id})\n";
1187 sub cmd_gc {
1188 if (!$can_compress) {
1189 warn "Compress::Zlib could not be found; unhandled.log " .
1190 "files will not be compressed.\n";
1192 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1195 ########################### utility functions #########################
1197 sub rebase_cmd {
1198 my @cmd = qw/rebase/;
1199 push @cmd, '-v' if $_verbose;
1200 push @cmd, qw/--merge/ if $_merge;
1201 push @cmd, "--strategy=$_strategy" if $_strategy;
1202 @cmd;
1205 sub post_fetch_checkout {
1206 return if $_no_checkout;
1207 my $gs = $Git::SVN::_head or return;
1208 return if verify_ref('refs/heads/master^0');
1210 # look for "trunk" ref if it exists
1211 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1212 my $fetch = $remote->{fetch};
1213 if ($fetch) {
1214 foreach my $p (keys %$fetch) {
1215 basename($fetch->{$p}) eq 'trunk' or next;
1216 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1217 last;
1221 my $valid_head = verify_ref('HEAD^0');
1222 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1223 return if ($valid_head || !verify_ref('HEAD^0'));
1225 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1226 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1227 return if -f $index;
1229 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1230 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1231 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1232 print STDERR "Checked out HEAD:\n ",
1233 $gs->full_url, " r", $gs->last_rev, "\n";
1234 $gs->mkemptydirs($gs->last_rev);
1237 sub complete_svn_url {
1238 my ($url, $path) = @_;
1239 $path =~ s#/+$##;
1240 if ($path !~ m#^[a-z\+]+://#) {
1241 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1242 fatal("E: '$path' is not a complete URL ",
1243 "and a separate URL is not specified");
1245 return ($url, $path);
1247 return ($path, '');
1250 sub complete_url_ls_init {
1251 my ($ra, $repo_path, $switch, $pfx) = @_;
1252 unless ($repo_path) {
1253 print STDERR "W: $switch not specified\n";
1254 return;
1256 $repo_path =~ s#/+$##;
1257 if ($repo_path =~ m#^[a-z\+]+://#) {
1258 $ra = Git::SVN::Ra->new($repo_path);
1259 $repo_path = '';
1260 } else {
1261 $repo_path =~ s#^/+##;
1262 unless ($ra) {
1263 fatal("E: '$repo_path' is not a complete URL ",
1264 "and a separate URL is not specified");
1267 my $url = $ra->{url};
1268 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1269 my $k = "svn-remote.$gs->{repo_id}.url";
1270 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1271 if ($orig_url && ($orig_url ne $gs->{url})) {
1272 die "$k already set: $orig_url\n",
1273 "wanted to set to: $gs->{url}\n";
1275 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1276 my $remote_path = "$gs->{path}/$repo_path";
1277 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1278 $remote_path =~ s#/+#/#g;
1279 $remote_path =~ s#^/##g;
1280 $remote_path .= "/*" if $remote_path !~ /\*/;
1281 my ($n) = ($switch =~ /^--(\w+)/);
1282 if (length $pfx && $pfx !~ m#/$#) {
1283 die "--prefix='$pfx' must have a trailing slash '/'\n";
1285 command_noisy('config',
1286 '--add',
1287 "svn-remote.$gs->{repo_id}.$n",
1288 "$remote_path:refs/remotes/$pfx*" .
1289 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1292 sub verify_ref {
1293 my ($ref) = @_;
1294 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1295 { STDERR => 0 }); };
1298 sub get_tree_from_treeish {
1299 my ($treeish) = @_;
1300 # $treeish can be a symbolic ref, too:
1301 my $type = command_oneline(qw/cat-file -t/, $treeish);
1302 my $expected;
1303 while ($type eq 'tag') {
1304 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1306 if ($type eq 'commit') {
1307 $expected = (grep /^tree /, command(qw/cat-file commit/,
1308 $treeish))[0];
1309 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1310 die "Unable to get tree from $treeish\n" unless $expected;
1311 } elsif ($type eq 'tree') {
1312 $expected = $treeish;
1313 } else {
1314 die "$treeish is a $type, expected tree, tag or commit\n";
1316 return $expected;
1319 sub get_commit_entry {
1320 my ($treeish) = shift;
1321 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1322 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1323 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1324 open my $log_fh, '>', $commit_editmsg or croak $!;
1326 my $type = command_oneline(qw/cat-file -t/, $treeish);
1327 if ($type eq 'commit' || $type eq 'tag') {
1328 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1329 $type, $treeish);
1330 my $in_msg = 0;
1331 my $author;
1332 my $saw_from = 0;
1333 my $msgbuf = "";
1334 while (<$msg_fh>) {
1335 if (!$in_msg) {
1336 $in_msg = 1 if (/^\s*$/);
1337 $author = $1 if (/^author (.*>)/);
1338 } elsif (/^git-svn-id: /) {
1339 # skip this for now, we regenerate the
1340 # correct one on re-fetch anyways
1341 # TODO: set *:merge properties or like...
1342 } else {
1343 if (/^From:/ || /^Signed-off-by:/) {
1344 $saw_from = 1;
1346 $msgbuf .= $_;
1349 $msgbuf =~ s/\s+$//s;
1350 if ($Git::SVN::_add_author_from && defined($author)
1351 && !$saw_from) {
1352 $msgbuf .= "\n\nFrom: $author";
1354 print $log_fh $msgbuf or croak $!;
1355 command_close_pipe($msg_fh, $ctx);
1357 close $log_fh or croak $!;
1359 if ($_edit || ($type eq 'tree')) {
1360 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1361 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1363 rename $commit_editmsg, $commit_msg or croak $!;
1365 require Encode;
1366 # SVN requires messages to be UTF-8 when entering the repo
1367 local $/;
1368 open $log_fh, '<', $commit_msg or croak $!;
1369 binmode $log_fh;
1370 chomp($log_entry{log} = <$log_fh>);
1372 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1373 my $msg = $log_entry{log};
1375 eval { $msg = Encode::decode($enc, $msg, 1) };
1376 if ($@) {
1377 die "Could not decode as $enc:\n", $msg,
1378 "\nPerhaps you need to set i18n.commitencoding\n";
1381 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1382 die "Could not encode as UTF-8:\n$msg\n" if $@;
1384 $log_entry{log} = $msg;
1386 close $log_fh or croak $!;
1388 unlink $commit_msg;
1389 \%log_entry;
1392 sub s_to_file {
1393 my ($str, $file, $mode) = @_;
1394 open my $fd,'>',$file or croak $!;
1395 print $fd $str,"\n" or croak $!;
1396 close $fd or croak $!;
1397 chmod ($mode &~ umask, $file) if (defined $mode);
1400 sub file_to_s {
1401 my $file = shift;
1402 open my $fd,'<',$file or croak "$!: file: $file\n";
1403 local $/;
1404 my $ret = <$fd>;
1405 close $fd or croak $!;
1406 $ret =~ s/\s*$//s;
1407 return $ret;
1410 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1411 sub load_authors {
1412 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1413 my $log = $cmd eq 'log';
1414 while (<$authors>) {
1415 chomp;
1416 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1417 my ($user, $name, $email) = ($1, $2, $3);
1418 if ($log) {
1419 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1420 } else {
1421 $users{$user} = [$name, $email];
1424 close $authors or croak $!;
1427 # convert GetOpt::Long specs for use by git-config
1428 sub read_git_config {
1429 my $opts = shift;
1430 my @config_only;
1431 foreach my $o (keys %$opts) {
1432 # if we have mixedCase and a long option-only, then
1433 # it's a config-only variable that we don't need for
1434 # the command-line.
1435 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1436 my $v = $opts->{$o};
1437 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1438 $key =~ s/-//g;
1439 my $arg = 'git config';
1440 $arg .= ' --int' if ($o =~ /[:=]i$/);
1441 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1442 if (ref $v eq 'ARRAY') {
1443 chomp(my @tmp = `$arg --get-all svn.$key`);
1444 @$v = @tmp if @tmp;
1445 } else {
1446 chomp(my $tmp = `$arg --get svn.$key`);
1447 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1448 $$v = $tmp;
1452 delete @$opts{@config_only} if @config_only;
1455 sub extract_metadata {
1456 my $id = shift or return (undef, undef, undef);
1457 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1458 \s([a-f\d\-]+)$/ix);
1459 if (!defined $rev || !$uuid || !$url) {
1460 # some of the original repositories I made had
1461 # identifiers like this:
1462 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1464 return ($url, $rev, $uuid);
1467 sub cmt_metadata {
1468 return extract_metadata((grep(/^git-svn-id: /,
1469 command(qw/cat-file commit/, shift)))[-1]);
1472 sub cmt_sha2rev_batch {
1473 my %s2r;
1474 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1475 my $list = shift;
1477 foreach my $sha (@{$list}) {
1478 my $first = 1;
1479 my $size = 0;
1480 print $out $sha, "\n";
1482 while (my $line = <$in>) {
1483 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1484 last;
1485 } elsif ($first &&
1486 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1487 $first = 0;
1488 $size = $1;
1489 next;
1490 } elsif ($line =~ /^(git-svn-id: )/) {
1491 my (undef, $rev, undef) =
1492 extract_metadata($line);
1493 $s2r{$sha} = $rev;
1496 $size -= length($line);
1497 last if ($size == 0);
1501 command_close_bidi_pipe($pid, $in, $out, $ctx);
1503 return \%s2r;
1506 sub working_head_info {
1507 my ($head, $refs) = @_;
1508 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1509 my ($fh, $ctx) = command_output_pipe(@args, $head);
1510 my $hash;
1511 my %max;
1512 while (<$fh>) {
1513 if ( m{^commit ($::sha1)$} ) {
1514 unshift @$refs, $hash if $hash and $refs;
1515 $hash = $1;
1516 next;
1518 next unless s{^\s*(git-svn-id:)}{$1};
1519 my ($url, $rev, $uuid) = extract_metadata($_);
1520 if (defined $url && defined $rev) {
1521 next if $max{$url} and $max{$url} < $rev;
1522 if (my $gs = Git::SVN->find_by_url($url)) {
1523 my $c = $gs->rev_map_get($rev, $uuid);
1524 if ($c && $c eq $hash) {
1525 close $fh; # break the pipe
1526 return ($url, $rev, $uuid, $gs);
1527 } else {
1528 $max{$url} ||= $gs->rev_map_max;
1533 command_close_pipe($fh, $ctx);
1534 (undef, undef, undef, undef);
1537 sub read_commit_parents {
1538 my ($parents, $c) = @_;
1539 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1540 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1541 @{$parents->{$c}} = split(/ /, $p);
1544 sub linearize_history {
1545 my ($gs, $refs) = @_;
1546 my %parents;
1547 foreach my $c (@$refs) {
1548 read_commit_parents(\%parents, $c);
1551 my @linear_refs;
1552 my %skip = ();
1553 my $last_svn_commit = $gs->last_commit;
1554 foreach my $c (reverse @$refs) {
1555 next if $c eq $last_svn_commit;
1556 last if $skip{$c};
1558 unshift @linear_refs, $c;
1559 $skip{$c} = 1;
1561 # we only want the first parent to diff against for linear
1562 # history, we save the rest to inject when we finalize the
1563 # svn commit
1564 my $fp_a = verify_ref("$c~1");
1565 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1566 if (!$fp_a || !$fp_b) {
1567 die "Commit $c\n",
1568 "has no parent commit, and therefore ",
1569 "nothing to diff against.\n",
1570 "You should be working from a repository ",
1571 "originally created by git-svn\n";
1573 if ($fp_a ne $fp_b) {
1574 die "$c~1 = $fp_a, however parsing commit $c ",
1575 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1578 foreach my $p (@{$parents{$c}}) {
1579 $skip{$p} = 1;
1582 (\@linear_refs, \%parents);
1585 sub find_file_type_and_diff_status {
1586 my ($path) = @_;
1587 return ('dir', '') if $path eq '';
1589 my $diff_output =
1590 command_oneline(qw(diff --cached --name-status --), $path) || "";
1591 my $diff_status = (split(' ', $diff_output))[0] || "";
1593 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1595 return (undef, undef) if !$diff_status && !$ls_tree;
1597 if ($diff_status eq "A") {
1598 return ("link", $diff_status) if -l $path;
1599 return ("dir", $diff_status) if -d $path;
1600 return ("file", $diff_status);
1603 my $mode = (split(' ', $ls_tree))[0] || "";
1605 return ("link", $diff_status) if $mode eq "120000";
1606 return ("dir", $diff_status) if $mode eq "040000";
1607 return ("file", $diff_status);
1610 sub md5sum {
1611 my $arg = shift;
1612 my $ref = ref $arg;
1613 my $md5 = Digest::MD5->new();
1614 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1615 $md5->addfile($arg) or croak $!;
1616 } elsif ($ref eq 'SCALAR') {
1617 $md5->add($$arg) or croak $!;
1618 } elsif (!$ref) {
1619 $md5->add($arg) or croak $!;
1620 } else {
1621 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1623 return $md5->hexdigest();
1626 sub gc_directory {
1627 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1628 my $out_filename = $_ . ".gz";
1629 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1630 binmode $in_fh;
1631 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1632 die "Unable to open $out_filename: $!\n";
1634 my $res;
1635 while ($res = sysread($in_fh, my $str, 1024)) {
1636 $gz->gzwrite($str) or
1637 die "Unable to write: ".$gz->gzerror()."!\n";
1639 unlink $_ or die "unlink $File::Find::name: $!\n";
1640 } elsif (-f $_ && basename($_) eq "index") {
1641 unlink $_ or die "unlink $_: $!\n";
1645 package Git::SVN;
1646 use strict;
1647 use warnings;
1648 use Fcntl qw/:DEFAULT :seek/;
1649 use constant rev_map_fmt => 'NH40';
1650 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1651 $_repack $_repack_flags $_use_svm_props $_head
1652 $_use_svnsync_props $no_reuse_existing $_minimize_url
1653 $_use_log_author $_add_author_from $_localtime/;
1654 use Carp qw/croak/;
1655 use File::Path qw/mkpath/;
1656 use File::Copy qw/copy/;
1657 use IPC::Open3;
1658 use Memoize; # core since 5.8.0, Jul 2002
1659 use Memoize::Storable;
1661 my ($_gc_nr, $_gc_period);
1663 # properties that we do not log:
1664 my %SKIP_PROP;
1665 BEGIN {
1666 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1667 svn:special svn:executable
1668 svn:entry:committed-rev
1669 svn:entry:last-author
1670 svn:entry:uuid
1671 svn:entry:committed-date/;
1673 # some options are read globally, but can be overridden locally
1674 # per [svn-remote "..."] section. Command-line options will *NOT*
1675 # override options set in an [svn-remote "..."] section
1676 no strict 'refs';
1677 for my $option (qw/follow_parent no_metadata use_svm_props
1678 use_svnsync_props/) {
1679 my $key = $option;
1680 $key =~ tr/_//d;
1681 my $prop = "-$option";
1682 *$option = sub {
1683 my ($self) = @_;
1684 return $self->{$prop} if exists $self->{$prop};
1685 my $k = "svn-remote.$self->{repo_id}.$key";
1686 eval { command_oneline(qw/config --get/, $k) };
1687 if ($@) {
1688 $self->{$prop} = ${"Git::SVN::_$option"};
1689 } else {
1690 my $v = command_oneline(qw/config --bool/,$k);
1691 $self->{$prop} = $v eq 'false' ? 0 : 1;
1693 return $self->{$prop};
1699 my (%LOCKFILES, %INDEX_FILES);
1700 END {
1701 unlink keys %LOCKFILES if %LOCKFILES;
1702 unlink keys %INDEX_FILES if %INDEX_FILES;
1705 sub resolve_local_globs {
1706 my ($url, $fetch, $glob_spec) = @_;
1707 return unless defined $glob_spec;
1708 my $ref = $glob_spec->{ref};
1709 my $path = $glob_spec->{path};
1710 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1711 next unless m#^$ref->{regex}$#;
1712 my $p = $1;
1713 my $pathname = desanitize_refname($path->full_path($p));
1714 my $refname = desanitize_refname($ref->full_path($p));
1715 if (my $existing = $fetch->{$pathname}) {
1716 if ($existing ne $refname) {
1717 die "Refspec conflict:\n",
1718 "existing: $existing\n",
1719 " globbed: $refname\n";
1721 my $u = (::cmt_metadata("$refname"))[0];
1722 $u =~ s!^\Q$url\E(/|$)!! or die
1723 "$refname: '$url' not found in '$u'\n";
1724 if ($pathname ne $u) {
1725 warn "W: Refspec glob conflict ",
1726 "(ref: $refname):\n",
1727 "expected path: $pathname\n",
1728 " real path: $u\n",
1729 "Continuing ahead with $u\n";
1730 next;
1732 } else {
1733 $fetch->{$pathname} = $refname;
1738 sub parse_revision_argument {
1739 my ($base, $head) = @_;
1740 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1741 return ($base, $head);
1743 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1744 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1745 return ($head, $head) if ($::_revision eq 'HEAD');
1746 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1747 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1748 die "revision argument: $::_revision not understood by git-svn\n";
1751 sub fetch_all {
1752 my ($repo_id, $remotes) = @_;
1753 if (ref $repo_id) {
1754 my $gs = $repo_id;
1755 $repo_id = undef;
1756 $repo_id = $gs->{repo_id};
1758 $remotes ||= read_all_remotes();
1759 my $remote = $remotes->{$repo_id} or
1760 die "[svn-remote \"$repo_id\"] unknown\n";
1761 my $fetch = $remote->{fetch};
1762 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1763 my (@gs, @globs);
1764 my $ra = Git::SVN::Ra->new($url);
1765 my $uuid = $ra->get_uuid;
1766 my $head = $ra->get_latest_revnum;
1768 # ignore errors, $head revision may not even exist anymore
1769 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1770 warn "W: $@\n" if $@;
1772 my $base = defined $fetch ? $head : 0;
1774 # read the max revs for wildcard expansion (branches/*, tags/*)
1775 foreach my $t (qw/branches tags/) {
1776 defined $remote->{$t} or next;
1777 push @globs, @{$remote->{$t}};
1779 my $max_rev = eval { tmp_config(qw/--int --get/,
1780 "svn-remote.$repo_id.${t}-maxRev") };
1781 if (defined $max_rev && ($max_rev < $base)) {
1782 $base = $max_rev;
1783 } elsif (!defined $max_rev) {
1784 $base = 0;
1788 if ($fetch) {
1789 foreach my $p (sort keys %$fetch) {
1790 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1791 my $lr = $gs->rev_map_max;
1792 if (defined $lr) {
1793 $base = $lr if ($lr < $base);
1795 push @gs, $gs;
1799 ($base, $head) = parse_revision_argument($base, $head);
1800 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1803 sub read_all_remotes {
1804 my $r = {};
1805 my $use_svm_props = eval { command_oneline(qw/config --bool
1806 svn.useSvmProps/) };
1807 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1808 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1809 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1810 if (m!^(.+)\.fetch=$svn_refspec$!) {
1811 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1812 die("svn-remote.$remote: remote ref '$remote_ref' "
1813 . "must start with 'refs/'\n")
1814 unless $remote_ref =~ m{^refs/};
1815 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1816 $r->{$remote}->{svm} = {} if $use_svm_props;
1817 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1818 $r->{$1}->{svm} = {};
1819 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1820 $r->{$1}->{url} = $2;
1821 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1822 my ($remote, $t, $local_ref, $remote_ref) =
1823 ($1, $2, $3, $4);
1824 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1825 . "must start with 'refs/'\n")
1826 unless $remote_ref =~ m{^refs/};
1827 my $rs = {
1828 t => $t,
1829 remote => $remote,
1830 path => Git::SVN::GlobSpec->new($local_ref, 1),
1831 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1832 if (length($rs->{ref}->{right}) != 0) {
1833 die "The '*' glob character must be the last ",
1834 "character of '$remote_ref'\n";
1836 push @{ $r->{$remote}->{$t} }, $rs;
1840 map {
1841 if (defined $r->{$_}->{svm}) {
1842 my $svm;
1843 eval {
1844 my $section = "svn-remote.$_";
1845 $svm = {
1846 source => tmp_config('--get',
1847 "$section.svm-source"),
1848 replace => tmp_config('--get',
1849 "$section.svm-replace"),
1852 $r->{$_}->{svm} = $svm;
1854 } keys %$r;
1859 sub init_vars {
1860 $_gc_nr = $_gc_period = 1000;
1861 if (defined $_repack || defined $_repack_flags) {
1862 warn "Repack options are obsolete; they have no effect.\n";
1866 sub verify_remotes_sanity {
1867 return unless -d $ENV{GIT_DIR};
1868 my %seen;
1869 foreach (command(qw/config -l/)) {
1870 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1871 if ($seen{$1}) {
1872 die "Remote ref refs/remote/$1 is tracked by",
1873 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1874 "Please resolve this ambiguity in ",
1875 "your git configuration file before ",
1876 "continuing\n";
1878 $seen{$1} = $_;
1883 sub find_existing_remote {
1884 my ($url, $remotes) = @_;
1885 return undef if $no_reuse_existing;
1886 my $existing;
1887 foreach my $repo_id (keys %$remotes) {
1888 my $u = $remotes->{$repo_id}->{url} or next;
1889 next if $u ne $url;
1890 $existing = $repo_id;
1891 last;
1893 $existing;
1896 sub init_remote_config {
1897 my ($self, $url, $no_write) = @_;
1898 $url =~ s!/+$!!; # strip trailing slash
1899 my $r = read_all_remotes();
1900 my $existing = find_existing_remote($url, $r);
1901 if ($existing) {
1902 unless ($no_write) {
1903 print STDERR "Using existing ",
1904 "[svn-remote \"$existing\"]\n";
1906 $self->{repo_id} = $existing;
1907 } elsif ($_minimize_url) {
1908 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1909 $existing = find_existing_remote($min_url, $r);
1910 if ($existing) {
1911 unless ($no_write) {
1912 print STDERR "Using existing ",
1913 "[svn-remote \"$existing\"]\n";
1915 $self->{repo_id} = $existing;
1917 if ($min_url ne $url) {
1918 unless ($no_write) {
1919 print STDERR "Using higher level of URL: ",
1920 "$url => $min_url\n";
1922 my $old_path = $self->{path};
1923 $self->{path} = $url;
1924 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1925 if (length $old_path) {
1926 $self->{path} .= "/$old_path";
1928 $url = $min_url;
1931 my $orig_url;
1932 if (!$existing) {
1933 # verify that we aren't overwriting anything:
1934 $orig_url = eval {
1935 command_oneline('config', '--get',
1936 "svn-remote.$self->{repo_id}.url")
1938 if ($orig_url && ($orig_url ne $url)) {
1939 die "svn-remote.$self->{repo_id}.url already set: ",
1940 "$orig_url\nwanted to set to: $url\n";
1943 my ($xrepo_id, $xpath) = find_ref($self->refname);
1944 if (!$no_write && defined $xpath) {
1945 die "svn-remote.$xrepo_id.fetch already set to track ",
1946 "$xpath:", $self->refname, "\n";
1948 unless ($no_write) {
1949 command_noisy('config',
1950 "svn-remote.$self->{repo_id}.url", $url);
1951 $self->{path} =~ s{^/}{};
1952 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1953 command_noisy('config', '--add',
1954 "svn-remote.$self->{repo_id}.fetch",
1955 "$self->{path}:".$self->refname);
1957 $self->{url} = $url;
1960 sub find_by_url { # repos_root and, path are optional
1961 my ($class, $full_url, $repos_root, $path) = @_;
1963 return undef unless defined $full_url;
1964 remove_username($full_url);
1965 remove_username($repos_root) if defined $repos_root;
1966 my $remotes = read_all_remotes();
1967 if (defined $full_url && defined $repos_root && !defined $path) {
1968 $path = $full_url;
1969 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1971 foreach my $repo_id (keys %$remotes) {
1972 my $u = $remotes->{$repo_id}->{url} or next;
1973 remove_username($u);
1974 next if defined $repos_root && $repos_root ne $u;
1976 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1977 foreach my $t (qw/branches tags/) {
1978 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1979 resolve_local_globs($u, $fetch, $globspec);
1982 my $p = $path;
1983 my $rwr = rewrite_root({repo_id => $repo_id});
1984 my $svm = $remotes->{$repo_id}->{svm}
1985 if defined $remotes->{$repo_id}->{svm};
1986 unless (defined $p) {
1987 $p = $full_url;
1988 my $z = $u;
1989 my $prefix = '';
1990 if ($rwr) {
1991 $z = $rwr;
1992 remove_username($z);
1993 } elsif (defined $svm) {
1994 $z = $svm->{source};
1995 $prefix = $svm->{replace};
1996 $prefix =~ s#^\Q$u\E(?:/|$)##;
1997 $prefix =~ s#/$##;
1999 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2001 foreach my $f (keys %$fetch) {
2002 next if $f ne $p;
2003 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2006 undef;
2009 sub init {
2010 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2011 my $self = _new($class, $repo_id, $ref_id, $path);
2012 if (defined $url) {
2013 $self->init_remote_config($url, $no_write);
2015 $self;
2018 sub find_ref {
2019 my ($ref_id) = @_;
2020 foreach (command(qw/config -l/)) {
2021 next unless m!^svn-remote\.(.+)\.fetch=
2022 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2023 my ($repo_id, $path, $ref) = ($1, $2, $3);
2024 if ($ref eq $ref_id) {
2025 $path = '' if ($path =~ m#^\./?#);
2026 return ($repo_id, $path);
2029 (undef, undef, undef);
2032 sub new {
2033 my ($class, $ref_id, $repo_id, $path) = @_;
2034 if (defined $ref_id && !defined $repo_id && !defined $path) {
2035 ($repo_id, $path) = find_ref($ref_id);
2036 if (!defined $repo_id) {
2037 die "Could not find a \"svn-remote.*.fetch\" key ",
2038 "in the repository configuration matching: ",
2039 "$ref_id\n";
2042 my $self = _new($class, $repo_id, $ref_id, $path);
2043 if (!defined $self->{path} || !length $self->{path}) {
2044 my $fetch = command_oneline('config', '--get',
2045 "svn-remote.$repo_id.fetch",
2046 ":$ref_id\$") or
2047 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2048 "\":$ref_id\$\" in config\n";
2049 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2051 $self->{url} = command_oneline('config', '--get',
2052 "svn-remote.$repo_id.url") or
2053 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2054 $self->rebuild;
2055 $self;
2058 sub refname {
2059 my ($refname) = $_[0]->{ref_id} ;
2061 # It cannot end with a slash /, we'll throw up on this because
2062 # SVN can't have directories with a slash in their name, either:
2063 if ($refname =~ m{/$}) {
2064 die "ref: '$refname' ends with a trailing slash, this is ",
2065 "not permitted by git nor Subversion\n";
2068 # It cannot have ASCII control character space, tilde ~, caret ^,
2069 # colon :, question-mark ?, asterisk *, space, or open bracket [
2070 # anywhere.
2072 # Additionally, % must be escaped because it is used for escaping
2073 # and we want our escaped refname to be reversible
2074 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2076 # no slash-separated component can begin with a dot .
2077 # /.* becomes /%2E*
2078 $refname =~ s{/\.}{/%2E}g;
2080 # It cannot have two consecutive dots .. anywhere
2081 # .. becomes %2E%2E
2082 $refname =~ s{\.\.}{%2E%2E}g;
2084 return $refname;
2087 sub desanitize_refname {
2088 my ($refname) = @_;
2089 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2090 return $refname;
2093 sub svm_uuid {
2094 my ($self) = @_;
2095 return $self->{svm}->{uuid} if $self->svm;
2096 $self->ra;
2097 unless ($self->{svm}) {
2098 die "SVM UUID not cached, and reading remotely failed\n";
2100 $self->{svm}->{uuid};
2103 sub svm {
2104 my ($self) = @_;
2105 return $self->{svm} if $self->{svm};
2106 my $svm;
2107 # see if we have it in our config, first:
2108 eval {
2109 my $section = "svn-remote.$self->{repo_id}";
2110 $svm = {
2111 source => tmp_config('--get', "$section.svm-source"),
2112 uuid => tmp_config('--get', "$section.svm-uuid"),
2113 replace => tmp_config('--get', "$section.svm-replace"),
2116 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2117 $self->{svm} = $svm;
2119 $self->{svm};
2122 sub _set_svm_vars {
2123 my ($self, $ra) = @_;
2124 return $ra if $self->svm;
2126 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2127 "(svm:source, svm:uuid) ",
2128 "from the following URLs:\n" );
2129 sub read_svm_props {
2130 my ($self, $ra, $path, $r) = @_;
2131 my $props = ($ra->get_dir($path, $r))[2];
2132 my $src = $props->{'svm:source'};
2133 my $uuid = $props->{'svm:uuid'};
2134 return undef if (!$src || !$uuid);
2136 chomp($src, $uuid);
2138 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2139 or die "doesn't look right - svm:uuid is '$uuid'\n";
2141 # the '!' is used to mark the repos_root!/relative/path
2142 $src =~ s{/?!/?}{/};
2143 $src =~ s{/+$}{}; # no trailing slashes please
2144 # username is of no interest
2145 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2147 my $replace = $ra->{url};
2148 $replace .= "/$path" if length $path;
2150 my $section = "svn-remote.$self->{repo_id}";
2151 tmp_config("$section.svm-source", $src);
2152 tmp_config("$section.svm-replace", $replace);
2153 tmp_config("$section.svm-uuid", $uuid);
2154 $self->{svm} = {
2155 source => $src,
2156 uuid => $uuid,
2157 replace => $replace
2161 my $r = $ra->get_latest_revnum;
2162 my $path = $self->{path};
2163 my %tried;
2164 while (length $path) {
2165 unless ($tried{"$self->{url}/$path"}) {
2166 return $ra if $self->read_svm_props($ra, $path, $r);
2167 $tried{"$self->{url}/$path"} = 1;
2169 $path =~ s#/?[^/]+$##;
2171 die "Path: '$path' should be ''\n" if $path ne '';
2172 return $ra if $self->read_svm_props($ra, $path, $r);
2173 $tried{"$self->{url}/$path"} = 1;
2175 if ($ra->{repos_root} eq $self->{url}) {
2176 die @err, (map { " $_\n" } keys %tried), "\n";
2179 # nope, make sure we're connected to the repository root:
2180 my $ok;
2181 my @tried_b;
2182 $path = $ra->{svn_path};
2183 $ra = Git::SVN::Ra->new($ra->{repos_root});
2184 while (length $path) {
2185 unless ($tried{"$ra->{url}/$path"}) {
2186 $ok = $self->read_svm_props($ra, $path, $r);
2187 last if $ok;
2188 $tried{"$ra->{url}/$path"} = 1;
2190 $path =~ s#/?[^/]+$##;
2192 die "Path: '$path' should be ''\n" if $path ne '';
2193 $ok ||= $self->read_svm_props($ra, $path, $r);
2194 $tried{"$ra->{url}/$path"} = 1;
2195 if (!$ok) {
2196 die @err, (map { " $_\n" } keys %tried), "\n";
2198 Git::SVN::Ra->new($self->{url});
2201 sub svnsync {
2202 my ($self) = @_;
2203 return $self->{svnsync} if $self->{svnsync};
2205 if ($self->no_metadata) {
2206 die "Can't have both 'noMetadata' and ",
2207 "'useSvnsyncProps' options set!\n";
2209 if ($self->rewrite_root) {
2210 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2211 "options set!\n";
2213 if ($self->rewrite_uuid) {
2214 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2215 "options set!\n";
2218 my $svnsync;
2219 # see if we have it in our config, first:
2220 eval {
2221 my $section = "svn-remote.$self->{repo_id}";
2223 my $url = tmp_config('--get', "$section.svnsync-url");
2224 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2225 die "doesn't look right - svn:sync-from-url is '$url'\n";
2227 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2228 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2229 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2231 $svnsync = { url => $url, uuid => $uuid }
2233 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2234 return $self->{svnsync} = $svnsync;
2237 my $err = "useSvnsyncProps set, but failed to read " .
2238 "svnsync property: svn:sync-from-";
2239 my $rp = $self->ra->rev_proplist(0);
2241 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2242 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2243 die "doesn't look right - svn:sync-from-url is '$url'\n";
2245 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2246 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2247 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2249 my $section = "svn-remote.$self->{repo_id}";
2250 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2251 tmp_config('--add', "$section.svnsync-url", $url);
2252 return $self->{svnsync} = { url => $url, uuid => $uuid };
2255 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2256 # remote lookup (useful for 'git svn log').
2257 sub ra_uuid {
2258 my ($self) = @_;
2259 unless ($self->{ra_uuid}) {
2260 my $key = "svn-remote.$self->{repo_id}.uuid";
2261 my $uuid = eval { tmp_config('--get', $key) };
2262 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2263 $self->{ra_uuid} = $uuid;
2264 } else {
2265 die "ra_uuid called without URL\n" unless $self->{url};
2266 $self->{ra_uuid} = $self->ra->get_uuid;
2267 tmp_config('--add', $key, $self->{ra_uuid});
2270 $self->{ra_uuid};
2273 sub _set_repos_root {
2274 my ($self, $repos_root) = @_;
2275 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2276 $repos_root ||= $self->ra->{repos_root};
2277 tmp_config($k, $repos_root);
2278 $repos_root;
2281 sub repos_root {
2282 my ($self) = @_;
2283 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2284 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2287 sub ra {
2288 my ($self) = shift;
2289 my $ra = Git::SVN::Ra->new($self->{url});
2290 $self->_set_repos_root($ra->{repos_root});
2291 if ($self->use_svm_props && !$self->{svm}) {
2292 if ($self->no_metadata) {
2293 die "Can't have both 'noMetadata' and ",
2294 "'useSvmProps' options set!\n";
2295 } elsif ($self->use_svnsync_props) {
2296 die "Can't have both 'useSvnsyncProps' and ",
2297 "'useSvmProps' options set!\n";
2299 $ra = $self->_set_svm_vars($ra);
2300 $self->{-want_revprops} = 1;
2302 $ra;
2305 # prop_walk(PATH, REV, SUB)
2306 # -------------------------
2307 # Recursively traverse PATH at revision REV and invoke SUB for each
2308 # directory that contains a SVN property. SUB will be invoked as
2309 # follows: &SUB(gs, path, props); where `gs' is this instance of
2310 # Git::SVN, `path' the path to the directory where the properties
2311 # `props' were found. The `path' will be relative to point of checkout,
2312 # that is, if url://repo/trunk is the current Git branch, and that
2313 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2314 # as `path' (note the trailing `/').
2315 sub prop_walk {
2316 my ($self, $path, $rev, $sub) = @_;
2318 $path =~ s#^/##;
2319 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2320 $path =~ s#^/*#/#g;
2321 my $p = $path;
2322 # Strip the irrelevant part of the path.
2323 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2324 # Ensure the path is terminated by a `/'.
2325 $p =~ s#/*$#/#;
2327 # The properties contain all the internal SVN stuff nobody
2328 # (usually) cares about.
2329 my $interesting_props = 0;
2330 foreach (keys %{$props}) {
2331 # If it doesn't start with `svn:', it must be a
2332 # user-defined property.
2333 ++$interesting_props and next if $_ !~ /^svn:/;
2334 # FIXME: Fragile, if SVN adds new public properties,
2335 # this needs to be updated.
2336 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2337 |eol-style|mime-type
2338 |externals|needs-lock)$/x;
2340 &$sub($self, $p, $props) if $interesting_props;
2342 foreach (sort keys %$dirent) {
2343 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2344 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2348 sub last_rev { ($_[0]->last_rev_commit)[0] }
2349 sub last_commit { ($_[0]->last_rev_commit)[1] }
2351 # returns the newest SVN revision number and newest commit SHA1
2352 sub last_rev_commit {
2353 my ($self) = @_;
2354 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2355 return ($self->{last_rev}, $self->{last_commit});
2357 my $c = ::verify_ref($self->refname.'^0');
2358 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2359 my $rev = (::cmt_metadata($c))[1];
2360 if (defined $rev) {
2361 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2362 return ($rev, $c);
2365 my $map_path = $self->map_path;
2366 unless (-e $map_path) {
2367 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2368 return (undef, undef);
2370 my ($rev, $commit) = $self->rev_map_max(1);
2371 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2372 return ($rev, $commit);
2375 sub get_fetch_range {
2376 my ($self, $min, $max) = @_;
2377 $max ||= $self->ra->get_latest_revnum;
2378 $min ||= $self->rev_map_max;
2379 (++$min, $max);
2382 sub tmp_config {
2383 my (@args) = @_;
2384 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2385 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2386 if (! -f $config && -f $old_def_config) {
2387 rename $old_def_config, $config or
2388 die "Failed rename $old_def_config => $config: $!\n";
2390 my $old_config = $ENV{GIT_CONFIG};
2391 $ENV{GIT_CONFIG} = $config;
2392 $@ = undef;
2393 my @ret = eval {
2394 unless (-f $config) {
2395 mkfile($config);
2396 open my $fh, '>', $config or
2397 die "Can't open $config: $!\n";
2398 print $fh "; This file is used internally by ",
2399 "git-svn\n" or die
2400 "Couldn't write to $config: $!\n";
2401 print $fh "; You should not have to edit it\n" or
2402 die "Couldn't write to $config: $!\n";
2403 close $fh or die "Couldn't close $config: $!\n";
2405 command('config', @args);
2407 my $err = $@;
2408 if (defined $old_config) {
2409 $ENV{GIT_CONFIG} = $old_config;
2410 } else {
2411 delete $ENV{GIT_CONFIG};
2413 die $err if $err;
2414 wantarray ? @ret : $ret[0];
2417 sub tmp_index_do {
2418 my ($self, $sub) = @_;
2419 my $old_index = $ENV{GIT_INDEX_FILE};
2420 $ENV{GIT_INDEX_FILE} = $self->{index};
2421 $@ = undef;
2422 my @ret = eval {
2423 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2424 mkpath([$dir]) unless -d $dir;
2425 &$sub;
2427 my $err = $@;
2428 if (defined $old_index) {
2429 $ENV{GIT_INDEX_FILE} = $old_index;
2430 } else {
2431 delete $ENV{GIT_INDEX_FILE};
2433 die $err if $err;
2434 wantarray ? @ret : $ret[0];
2437 sub assert_index_clean {
2438 my ($self, $treeish) = @_;
2440 $self->tmp_index_do(sub {
2441 command_noisy('read-tree', $treeish) unless -e $self->{index};
2442 my $x = command_oneline('write-tree');
2443 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2444 /^tree ($::sha1)/mo);
2445 return if $y eq $x;
2447 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2448 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2449 command_noisy('read-tree', $treeish);
2450 $x = command_oneline('write-tree');
2451 if ($y ne $x) {
2452 ::fatal "trees ($treeish) $y != $x\n",
2453 "Something is seriously wrong...";
2458 sub get_commit_parents {
2459 my ($self, $log_entry) = @_;
2460 my (%seen, @ret, @tmp);
2461 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2462 if (my $ip = $self->{inject_parents}) {
2463 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2464 push @tmp, $commit;
2467 if (my $cur = ::verify_ref($self->refname.'^0')) {
2468 push @tmp, $cur;
2470 if (my $ipd = $self->{inject_parents_dcommit}) {
2471 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2472 push @tmp, @$commit;
2475 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2476 while (my $p = shift @tmp) {
2477 next if $seen{$p};
2478 $seen{$p} = 1;
2479 push @ret, $p;
2481 @ret;
2484 sub rewrite_root {
2485 my ($self) = @_;
2486 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2487 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2488 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2489 if ($rwr) {
2490 $rwr =~ s#/+$##;
2491 if ($rwr !~ m#^[a-z\+]+://#) {
2492 die "$rwr is not a valid URL (key: $k)\n";
2495 $self->{-rewrite_root} = $rwr;
2498 sub rewrite_uuid {
2499 my ($self) = @_;
2500 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2501 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2502 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2503 if ($rwid) {
2504 $rwid =~ s#/+$##;
2505 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2506 die "$rwid is not a valid UUID (key: $k)\n";
2509 $self->{-rewrite_uuid} = $rwid;
2512 sub metadata_url {
2513 my ($self) = @_;
2514 ($self->rewrite_root || $self->{url}) .
2515 (length $self->{path} ? '/' . $self->{path} : '');
2518 sub full_url {
2519 my ($self) = @_;
2520 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2524 sub set_commit_header_env {
2525 my ($log_entry) = @_;
2526 my %env;
2527 foreach my $ned (qw/NAME EMAIL DATE/) {
2528 foreach my $ac (qw/AUTHOR COMMITTER/) {
2529 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2533 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2534 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2535 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2537 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2538 ? $log_entry->{commit_name}
2539 : $log_entry->{name};
2540 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2541 ? $log_entry->{commit_email}
2542 : $log_entry->{email};
2543 \%env;
2546 sub restore_commit_header_env {
2547 my ($env) = @_;
2548 foreach my $ned (qw/NAME EMAIL DATE/) {
2549 foreach my $ac (qw/AUTHOR COMMITTER/) {
2550 my $k = "GIT_${ac}_${ned}";
2551 if (defined $env->{$k}) {
2552 $ENV{$k} = $env->{$k};
2553 } else {
2554 delete $ENV{$k};
2560 sub gc {
2561 command_noisy('gc', '--auto');
2564 sub do_git_commit {
2565 my ($self, $log_entry) = @_;
2566 my $lr = $self->last_rev;
2567 if (defined $lr && $lr >= $log_entry->{revision}) {
2568 die "Last fetched revision of ", $self->refname,
2569 " was r$lr, but we are about to fetch: ",
2570 "r$log_entry->{revision}!\n";
2572 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2573 croak "$log_entry->{revision} = $c already exists! ",
2574 "Why are we refetching it?\n";
2576 my $old_env = set_commit_header_env($log_entry);
2577 my $tree = $log_entry->{tree};
2578 if (!defined $tree) {
2579 $tree = $self->tmp_index_do(sub {
2580 command_oneline('write-tree') });
2582 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2584 my @exec = ('git', 'commit-tree', $tree);
2585 foreach ($self->get_commit_parents($log_entry)) {
2586 push @exec, '-p', $_;
2588 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2589 or croak $!;
2590 binmode $msg_fh;
2592 # we always get UTF-8 from SVN, but we may want our commits in
2593 # a different encoding.
2594 if (my $enc = Git::config('i18n.commitencoding')) {
2595 require Encode;
2596 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2598 print $msg_fh $log_entry->{log} or croak $!;
2599 restore_commit_header_env($old_env);
2600 unless ($self->no_metadata) {
2601 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2602 or croak $!;
2604 $msg_fh->flush == 0 or croak $!;
2605 close $msg_fh or croak $!;
2606 chomp(my $commit = do { local $/; <$out_fh> });
2607 close $out_fh or croak $!;
2608 waitpid $pid, 0;
2609 croak $? if $?;
2610 if ($commit !~ /^$::sha1$/o) {
2611 die "Failed to commit, invalid sha1: $commit\n";
2614 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2616 $self->{last_rev} = $log_entry->{revision};
2617 $self->{last_commit} = $commit;
2618 print "r$log_entry->{revision}" unless $::_q > 1;
2619 if (defined $log_entry->{svm_revision}) {
2620 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2621 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2622 0, $self->svm_uuid);
2624 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2625 if (--$_gc_nr == 0) {
2626 $_gc_nr = $_gc_period;
2627 gc();
2629 return $commit;
2632 sub match_paths {
2633 my ($self, $paths, $r) = @_;
2634 return 1 if $self->{path} eq '';
2635 if (my $path = $paths->{"/$self->{path}"}) {
2636 return ($path->{action} eq 'D') ? 0 : 1;
2638 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2639 if (grep /$self->{path_regex}/, keys %$paths) {
2640 return 1;
2642 my $c = '';
2643 foreach (split m#/#, $self->{path}) {
2644 $c .= "/$_";
2645 next unless ($paths->{$c} &&
2646 ($paths->{$c}->{action} =~ /^[AR]$/));
2647 if ($self->ra->check_path($self->{path}, $r) ==
2648 $SVN::Node::dir) {
2649 return 1;
2652 return 0;
2655 sub find_parent_branch {
2656 my ($self, $paths, $rev) = @_;
2657 return undef unless $self->follow_parent;
2658 unless (defined $paths) {
2659 my $err_handler = $SVN::Error::handler;
2660 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2661 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2662 sub { $paths = $_[0] });
2663 $SVN::Error::handler = $err_handler;
2665 return undef unless defined $paths;
2667 # look for a parent from another branch:
2668 my @b_path_components = split m#/#, $self->{path};
2669 my @a_path_components;
2670 my $i;
2671 while (@b_path_components) {
2672 $i = $paths->{'/'.join('/', @b_path_components)};
2673 last if $i && defined $i->{copyfrom_path};
2674 unshift(@a_path_components, pop(@b_path_components));
2676 return undef unless defined $i && defined $i->{copyfrom_path};
2677 my $branch_from = $i->{copyfrom_path};
2678 if (@a_path_components) {
2679 print STDERR "branch_from: $branch_from => ";
2680 $branch_from .= '/'.join('/', @a_path_components);
2681 print STDERR $branch_from, "\n";
2683 my $r = $i->{copyfrom_rev};
2684 my $repos_root = $self->ra->{repos_root};
2685 my $url = $self->ra->{url};
2686 my $new_url = $url . $branch_from;
2687 print STDERR "Found possible branch point: ",
2688 "$new_url => ", $self->full_url, ", $r\n"
2689 unless $::_q > 1;
2690 $branch_from =~ s#^/##;
2691 my $gs = $self->other_gs($new_url, $url,
2692 $branch_from, $r, $self->{ref_id});
2693 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2695 my ($base, $head);
2696 if (!defined $r0 || !defined $parent) {
2697 ($base, $head) = parse_revision_argument(0, $r);
2698 } else {
2699 if ($r0 < $r) {
2700 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2701 0, 1, sub { $base = $_[1] - 1 });
2704 if (defined $base && $base <= $r) {
2705 $gs->fetch($base, $r);
2707 ($r0, $parent) = $gs->find_rev_before($r, 1);
2709 if (defined $r0 && defined $parent) {
2710 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2711 unless $::_q > 1;
2712 my $ed;
2713 if ($self->ra->can_do_switch) {
2714 $self->assert_index_clean($parent);
2715 print STDERR "Following parent with do_switch\n"
2716 unless $::_q > 1;
2717 # do_switch works with svn/trunk >= r22312, but that
2718 # is not included with SVN 1.4.3 (the latest version
2719 # at the moment), so we can't rely on it
2720 $self->{last_rev} = $r0;
2721 $self->{last_commit} = $parent;
2722 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2723 $gs->ra->gs_do_switch($r0, $rev, $gs,
2724 $self->full_url, $ed)
2725 or die "SVN connection failed somewhere...\n";
2726 } elsif ($self->ra->trees_match($new_url, $r0,
2727 $self->full_url, $rev)) {
2728 print STDERR "Trees match:\n",
2729 " $new_url\@$r0\n",
2730 " ${\$self->full_url}\@$rev\n",
2731 "Following parent with no changes\n"
2732 unless $::_q > 1;
2733 $self->tmp_index_do(sub {
2734 command_noisy('read-tree', $parent);
2736 $self->{last_commit} = $parent;
2737 } else {
2738 print STDERR "Following parent with do_update\n"
2739 unless $::_q > 1;
2740 $ed = SVN::Git::Fetcher->new($self);
2741 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2742 or die "SVN connection failed somewhere...\n";
2744 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2745 return $self->make_log_entry($rev, [$parent], $ed);
2747 return undef;
2750 sub do_fetch {
2751 my ($self, $paths, $rev) = @_;
2752 my $ed;
2753 my ($last_rev, @parents);
2754 if (my $lc = $self->last_commit) {
2755 # we can have a branch that was deleted, then re-added
2756 # under the same name but copied from another path, in
2757 # which case we'll have multiple parents (we don't
2758 # want to break the original ref, nor lose copypath info):
2759 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2760 push @{$log_entry->{parents}}, $lc;
2761 return $log_entry;
2763 $ed = SVN::Git::Fetcher->new($self);
2764 $last_rev = $self->{last_rev};
2765 $ed->{c} = $lc;
2766 @parents = ($lc);
2767 } else {
2768 $last_rev = $rev;
2769 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2770 return $log_entry;
2772 $ed = SVN::Git::Fetcher->new($self);
2774 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2775 die "SVN connection failed somewhere...\n";
2777 $self->make_log_entry($rev, \@parents, $ed);
2780 sub mkemptydirs {
2781 my ($self, $r) = @_;
2783 sub scan {
2784 my ($r, $empty_dirs, $line) = @_;
2785 if (defined $r && $line =~ /^r(\d+)$/) {
2786 return 0 if $1 > $r;
2787 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2788 $empty_dirs->{$1} = 1;
2789 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2790 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2791 delete @$empty_dirs{@d};
2793 1; # continue
2796 my %empty_dirs = ();
2797 my $gz_file = "$self->{dir}/unhandled.log.gz";
2798 if (-f $gz_file) {
2799 if (!$can_compress) {
2800 warn "Compress::Zlib could not be found; ",
2801 "empty directories in $gz_file will not be read\n";
2802 } else {
2803 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2804 die "Unable to open $gz_file: $!\n";
2805 my $line;
2806 while ($gz->gzreadline($line) > 0) {
2807 scan($r, \%empty_dirs, $line) or last;
2809 $gz->gzclose;
2813 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2814 binmode $fh or croak "binmode: $!";
2815 while (<$fh>) {
2816 scan($r, \%empty_dirs, $_) or last;
2818 close $fh;
2821 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2822 foreach my $d (sort keys %empty_dirs) {
2823 $d = uri_decode($d);
2824 $d =~ s/$strip//;
2825 next if -d $d;
2826 if (-e _) {
2827 warn "$d exists but is not a directory\n";
2828 } else {
2829 print "creating empty directory: $d\n";
2830 mkpath([$d]);
2835 sub get_untracked {
2836 my ($self, $ed) = @_;
2837 my @out;
2838 my $h = $ed->{empty};
2839 foreach (sort keys %$h) {
2840 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2841 push @out, " $act: " . uri_encode($_);
2842 warn "W: $act: $_\n";
2844 foreach my $t (qw/dir_prop file_prop/) {
2845 $h = $ed->{$t} or next;
2846 foreach my $path (sort keys %$h) {
2847 my $ppath = $path eq '' ? '.' : $path;
2848 foreach my $prop (sort keys %{$h->{$path}}) {
2849 next if $SKIP_PROP{$prop};
2850 my $v = $h->{$path}->{$prop};
2851 my $t_ppath_prop = "$t: " .
2852 uri_encode($ppath) . ' ' .
2853 uri_encode($prop);
2854 if (defined $v) {
2855 push @out, " +$t_ppath_prop " .
2856 uri_encode($v);
2857 } else {
2858 push @out, " -$t_ppath_prop";
2863 foreach my $t (qw/absent_file absent_directory/) {
2864 $h = $ed->{$t} or next;
2865 foreach my $parent (sort keys %$h) {
2866 foreach my $path (sort @{$h->{$parent}}) {
2867 push @out, " $t: " .
2868 uri_encode("$parent/$path");
2869 warn "W: $t: $parent/$path ",
2870 "Insufficient permissions?\n";
2874 \@out;
2877 # parse_svn_date(DATE)
2878 # --------------------
2879 # Given a date (in UTC) from Subversion, return a string in the format
2880 # "<TZ Offset> <local date/time>" that Git will use.
2882 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2883 # is true we'll convert it to the local timezone instead.
2884 sub parse_svn_date {
2885 my $date = shift || return '+0000 1970-01-01 00:00:00';
2886 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2887 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2888 croak "Unable to parse date: $date\n";
2889 my $parsed_date; # Set next.
2891 if ($Git::SVN::_localtime) {
2892 # Translate the Subversion datetime to an epoch time.
2893 # Begin by switching ourselves to $date's timezone, UTC.
2894 my $old_env_TZ = $ENV{TZ};
2895 $ENV{TZ} = 'UTC';
2897 my $epoch_in_UTC =
2898 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2900 # Determine our local timezone (including DST) at the
2901 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2902 # value of TZ, if any, at the time we were run.
2903 if (defined $Git::SVN::Log::TZ) {
2904 $ENV{TZ} = $Git::SVN::Log::TZ;
2905 } else {
2906 delete $ENV{TZ};
2909 my $our_TZ =
2910 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2912 # This converts $epoch_in_UTC into our local timezone.
2913 my ($sec, $min, $hour, $mday, $mon, $year,
2914 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2916 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2917 $our_TZ, $year + 1900, $mon + 1,
2918 $mday, $hour, $min, $sec);
2920 # Reset us to the timezone in effect when we entered
2921 # this routine.
2922 if (defined $old_env_TZ) {
2923 $ENV{TZ} = $old_env_TZ;
2924 } else {
2925 delete $ENV{TZ};
2927 } else {
2928 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2931 return $parsed_date;
2934 sub other_gs {
2935 my ($self, $new_url, $url,
2936 $branch_from, $r, $old_ref_id) = @_;
2937 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2938 unless ($gs) {
2939 my $ref_id = $old_ref_id;
2940 $ref_id =~ s/\@\d+$//;
2941 $ref_id .= "\@$r";
2942 # just grow a tail if we're not unique enough :x
2943 $ref_id .= '-' while find_ref($ref_id);
2944 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2945 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2946 if ($u =~ s#^\Q$url\E(/|$)##) {
2947 $p = $u;
2948 $u = $url;
2949 $repo_id = $self->{repo_id};
2951 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2956 sub call_authors_prog {
2957 my ($orig_author) = @_;
2958 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2959 my $author = `$::_authors_prog $orig_author`;
2960 if ($? != 0) {
2961 die "$::_authors_prog failed with exit code $?\n"
2963 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2964 my ($name, $email) = ($1, $2);
2965 $email = undef if length $2 == 0;
2966 return [$name, $email];
2967 } else {
2968 die "Author: $orig_author: $::_authors_prog returned "
2969 . "invalid author format: $author\n";
2973 sub check_author {
2974 my ($author) = @_;
2975 if (!defined $author || length $author == 0) {
2976 $author = '(no author)';
2978 if (!defined $::users{$author}) {
2979 if (defined $::_authors_prog) {
2980 $::users{$author} = call_authors_prog($author);
2981 } elsif (defined $::_authors) {
2982 die "Author: $author not defined in $::_authors file\n";
2985 $author;
2988 sub find_extra_svk_parents {
2989 my ($self, $ed, $tickets, $parents) = @_;
2990 # aha! svk:merge property changed...
2991 my @tickets = split "\n", $tickets;
2992 my @known_parents;
2993 for my $ticket ( @tickets ) {
2994 my ($uuid, $path, $rev) = split /:/, $ticket;
2995 if ( $uuid eq $self->ra_uuid ) {
2996 my $url = $self->rewrite_root || $self->{url};
2997 my $repos_root = $url;
2998 my $branch_from = $path;
2999 $branch_from =~ s{^/}{};
3000 my $gs = $self->other_gs($repos_root."/".$branch_from,
3001 $url,
3002 $branch_from,
3003 $rev,
3004 $self->{ref_id});
3005 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3006 # wahey! we found it, but it might be
3007 # an old one (!)
3008 push @known_parents, [ $rev, $commit ];
3012 # Ordering matters; highest-numbered commit merge tickets
3013 # first, as they may account for later merge ticket additions
3014 # or changes.
3015 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3016 for my $parent ( @known_parents ) {
3017 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3018 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3019 my $new;
3020 while ( <$msg_fh> ) {
3021 $new=1;last;
3023 command_close_pipe($msg_fh, $ctx);
3024 if ( $new ) {
3025 print STDERR
3026 "Found merge parent (svk:merge ticket): $parent\n";
3027 push @$parents, $parent;
3032 sub lookup_svn_merge {
3033 my $uuid = shift;
3034 my $url = shift;
3035 my $merge = shift;
3037 my ($source, $revs) = split ":", $merge;
3038 my $path = $source;
3039 $path =~ s{^/}{};
3040 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3041 if ( !$gs ) {
3042 warn "Couldn't find revmap for $url$source\n";
3043 return;
3045 my @ranges = split ",", $revs;
3046 my ($tip, $tip_commit);
3047 my @merged_commit_ranges;
3048 # find the tip
3049 for my $range ( @ranges ) {
3050 my ($bottom, $top) = split "-", $range;
3051 $top ||= $bottom;
3052 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3053 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3055 unless ($top_commit and $bottom_commit) {
3056 warn "W:unknown path/rev in svn:mergeinfo "
3057 ."dirprop: $source:$range\n";
3058 next;
3061 push @merged_commit_ranges,
3062 "$bottom_commit^..$top_commit";
3064 if ( !defined $tip or $top > $tip ) {
3065 $tip = $top;
3066 $tip_commit = $top_commit;
3069 return ($tip_commit, @merged_commit_ranges);
3072 sub _rev_list {
3073 my ($msg_fh, $ctx) = command_output_pipe(
3074 "rev-list", @_,
3076 my @rv;
3077 while ( <$msg_fh> ) {
3078 chomp;
3079 push @rv, $_;
3081 command_close_pipe($msg_fh, $ctx);
3082 @rv;
3085 sub check_cherry_pick {
3086 my $base = shift;
3087 my $tip = shift;
3088 my @ranges = @_;
3089 my %commits = map { $_ => 1 }
3090 _rev_list("--no-merges", $tip, "--not", $base);
3091 for my $range ( @ranges ) {
3092 delete @commits{_rev_list($range)};
3094 for my $commit (keys %commits) {
3095 if (has_no_changes($commit)) {
3096 delete $commits{$commit};
3099 return (keys %commits);
3102 sub has_no_changes {
3103 my $commit = shift;
3105 my @revs = split / /, command_oneline(
3106 qw(rev-list --parents -1 -m), $commit);
3108 # Commits with no parents, e.g. the start of a partial branch,
3109 # have changes by definition.
3110 return 1 if (@revs < 2);
3112 # Commits with multiple parents, e.g a merge, have no changes
3113 # by definition.
3114 return 0 if (@revs > 2);
3116 return (command_oneline("rev-parse", "$commit^{tree}") eq
3117 command_oneline("rev-parse", "$commit~1^{tree}"));
3120 # The GIT_DIR environment variable is not always set until after the command
3121 # line arguments are processed, so we can't memoize in a BEGIN block.
3123 my $memoized = 0;
3125 sub memoize_svn_mergeinfo_functions {
3126 return if $memoized;
3127 $memoized = 1;
3129 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3130 mkpath([$cache_path]) unless -d $cache_path;
3132 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3133 "$cache_path/lookup_svn_merge.db", 'nstore';
3134 memoize 'lookup_svn_merge',
3135 SCALAR_CACHE => 'FAULT',
3136 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3139 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3140 "$cache_path/check_cherry_pick.db", 'nstore';
3141 memoize 'check_cherry_pick',
3142 SCALAR_CACHE => 'FAULT',
3143 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3146 tie my %has_no_changes_cache => 'Memoize::Storable',
3147 "$cache_path/has_no_changes.db", 'nstore';
3148 memoize 'has_no_changes',
3149 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3150 LIST_CACHE => 'FAULT',
3155 sub parents_exclude {
3156 my $parents = shift;
3157 my @commits = @_;
3158 return unless @commits;
3160 my @excluded;
3161 my $excluded;
3162 do {
3163 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3164 $excluded = command_oneline(@cmd);
3165 if ( $excluded ) {
3166 my @new;
3167 my $found;
3168 for my $commit ( @commits ) {
3169 if ( $commit eq $excluded ) {
3170 push @excluded, $commit;
3171 $found++;
3172 last;
3174 else {
3175 push @new, $commit;
3178 die "saw commit '$excluded' in rev-list output, "
3179 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3180 unless $found;
3181 @commits = @new;
3184 while ($excluded and @commits);
3186 return @excluded;
3190 # note: this function should only be called if the various dirprops
3191 # have actually changed
3192 sub find_extra_svn_parents {
3193 my ($self, $ed, $mergeinfo, $parents) = @_;
3194 # aha! svk:merge property changed...
3196 memoize_svn_mergeinfo_functions();
3198 # We first search for merged tips which are not in our
3199 # history. Then, we figure out which git revisions are in
3200 # that tip, but not this revision. If all of those revisions
3201 # are now marked as merge, we can add the tip as a parent.
3202 my @merges = split "\n", $mergeinfo;
3203 my @merge_tips;
3204 my $url = $self->rewrite_root || $self->{url};
3205 my $uuid = $self->ra_uuid;
3206 my %ranges;
3207 for my $merge ( @merges ) {
3208 my ($tip_commit, @ranges) =
3209 lookup_svn_merge( $uuid, $url, $merge );
3210 unless (!$tip_commit or
3211 grep { $_ eq $tip_commit } @$parents ) {
3212 push @merge_tips, $tip_commit;
3213 $ranges{$tip_commit} = \@ranges;
3214 } else {
3215 push @merge_tips, undef;
3219 my %excluded = map { $_ => 1 }
3220 parents_exclude($parents, grep { defined } @merge_tips);
3222 # check merge tips for new parents
3223 my @new_parents;
3224 for my $merge_tip ( @merge_tips ) {
3225 my $spec = shift @merges;
3226 next unless $merge_tip and $excluded{$merge_tip};
3228 my $ranges = $ranges{$merge_tip};
3230 # check out 'new' tips
3231 my $merge_base;
3232 eval {
3233 $merge_base = command_oneline(
3234 "merge-base",
3235 @$parents, $merge_tip,
3238 if ($@) {
3239 die "An error occurred during merge-base"
3240 unless $@->isa("Git::Error::Command");
3242 warn "W: Cannot find common ancestor between ".
3243 "@$parents and $merge_tip. Ignoring merge info.\n";
3244 next;
3247 # double check that there are no missing non-merge commits
3248 my (@incomplete) = check_cherry_pick(
3249 $merge_base, $merge_tip,
3250 @$ranges,
3253 if ( @incomplete ) {
3254 warn "W:svn cherry-pick ignored ($spec) - missing "
3255 .@incomplete." commit(s) (eg $incomplete[0])\n";
3256 } else {
3257 warn
3258 "Found merge parent (svn:mergeinfo prop): ",
3259 $merge_tip, "\n";
3260 push @new_parents, $merge_tip;
3264 # cater for merges which merge commits from multiple branches
3265 if ( @new_parents > 1 ) {
3266 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3267 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3268 next if $i == $j;
3269 next unless $new_parents[$i];
3270 next unless $new_parents[$j];
3271 my $revs = command_oneline(
3272 "rev-list", "-1",
3273 "$new_parents[$i]..$new_parents[$j]",
3275 if ( !$revs ) {
3276 undef($new_parents[$i]);
3281 push @$parents, grep { defined } @new_parents;
3284 sub make_log_entry {
3285 my ($self, $rev, $parents, $ed) = @_;
3286 my $untracked = $self->get_untracked($ed);
3288 my @parents = @$parents;
3289 my $ps = $ed->{path_strip} || "";
3290 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3291 my $props = $ed->{dir_prop}{$path};
3292 if ( $props->{"svk:merge"} ) {
3293 $self->find_extra_svk_parents
3294 ($ed, $props->{"svk:merge"}, \@parents);
3296 if ( $props->{"svn:mergeinfo"} ) {
3297 $self->find_extra_svn_parents
3298 ($ed,
3299 $props->{"svn:mergeinfo"},
3300 \@parents);
3304 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3305 print $un "r$rev\n" or croak $!;
3306 print $un $_, "\n" foreach @$untracked;
3307 my %log_entry = ( parents => \@parents, revision => $rev,
3308 log => '');
3310 my $headrev;
3311 my $logged = delete $self->{logged_rev_props};
3312 if (!$logged || $self->{-want_revprops}) {
3313 my $rp = $self->ra->rev_proplist($rev);
3314 foreach (sort keys %$rp) {
3315 my $v = $rp->{$_};
3316 if (/^svn:(author|date|log)$/) {
3317 $log_entry{$1} = $v;
3318 } elsif ($_ eq 'svm:headrev') {
3319 $headrev = $v;
3320 } else {
3321 print $un " rev_prop: ", uri_encode($_), ' ',
3322 uri_encode($v), "\n";
3325 } else {
3326 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3328 close $un or croak $!;
3330 $log_entry{date} = parse_svn_date($log_entry{date});
3331 $log_entry{log} .= "\n";
3332 my $author = $log_entry{author} = check_author($log_entry{author});
3333 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3334 : ($author, undef);
3336 my ($commit_name, $commit_email) = ($name, $email);
3337 if ($_use_log_author) {
3338 my $name_field;
3339 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3340 $name_field = $1;
3341 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3342 $name_field = $1;
3344 if (!defined $name_field) {
3345 if (!defined $email) {
3346 $email = $name;
3348 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3349 ($name, $email) = ($1, $2);
3350 } elsif ($name_field =~ /(.*)@/) {
3351 ($name, $email) = ($1, $name_field);
3352 } else {
3353 ($name, $email) = ($name_field, $name_field);
3356 if (defined $headrev && $self->use_svm_props) {
3357 if ($self->rewrite_root) {
3358 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3359 "options set!\n";
3361 if ($self->rewrite_uuid) {
3362 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3363 "options set!\n";
3365 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3366 # we don't want "SVM: initializing mirror for junk" ...
3367 return undef if $r == 0;
3368 my $svm = $self->svm;
3369 if ($uuid ne $svm->{uuid}) {
3370 die "UUID mismatch on SVM path:\n",
3371 "expected: $svm->{uuid}\n",
3372 " got: $uuid\n";
3374 my $full_url = $self->full_url;
3375 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3376 die "Failed to replace '$svm->{replace}' with ",
3377 "'$svm->{source}' in $full_url\n";
3378 # throw away username for storing in records
3379 remove_username($full_url);
3380 $log_entry{metadata} = "$full_url\@$r $uuid";
3381 $log_entry{svm_revision} = $r;
3382 $email ||= "$author\@$uuid";
3383 $commit_email ||= "$author\@$uuid";
3384 } elsif ($self->use_svnsync_props) {
3385 my $full_url = $self->svnsync->{url};
3386 $full_url .= "/$self->{path}" if length $self->{path};
3387 remove_username($full_url);
3388 my $uuid = $self->svnsync->{uuid};
3389 $log_entry{metadata} = "$full_url\@$rev $uuid";
3390 $email ||= "$author\@$uuid";
3391 $commit_email ||= "$author\@$uuid";
3392 } else {
3393 my $url = $self->metadata_url;
3394 remove_username($url);
3395 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3396 $log_entry{metadata} = "$url\@$rev " . $uuid;
3397 $email ||= "$author\@" . $uuid;
3398 $commit_email ||= "$author\@" . $uuid;
3400 $log_entry{name} = $name;
3401 $log_entry{email} = $email;
3402 $log_entry{commit_name} = $commit_name;
3403 $log_entry{commit_email} = $commit_email;
3404 \%log_entry;
3407 sub fetch {
3408 my ($self, $min_rev, $max_rev, @parents) = @_;
3409 my ($last_rev, $last_commit) = $self->last_rev_commit;
3410 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3411 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3414 sub set_tree_cb {
3415 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3416 $self->{inject_parents} = { $rev => $tree };
3417 $self->fetch(undef, undef);
3420 sub set_tree {
3421 my ($self, $tree) = (shift, shift);
3422 my $log_entry = ::get_commit_entry($tree);
3423 unless ($self->{last_rev}) {
3424 ::fatal("Must have an existing revision to commit");
3426 my %ed_opts = ( r => $self->{last_rev},
3427 log => $log_entry->{log},
3428 ra => $self->ra,
3429 tree_a => $self->{last_commit},
3430 tree_b => $tree,
3431 editor_cb => sub {
3432 $self->set_tree_cb($log_entry, $tree, @_) },
3433 svn_path => $self->{path} );
3434 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3435 print "No changes\nr$self->{last_rev} = $tree\n";
3439 sub rebuild_from_rev_db {
3440 my ($self, $path) = @_;
3441 my $r = -1;
3442 open my $fh, '<', $path or croak "open: $!";
3443 binmode $fh or croak "binmode: $!";
3444 while (<$fh>) {
3445 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3446 chomp($_);
3447 ++$r;
3448 next if $_ eq ('0' x 40);
3449 $self->rev_map_set($r, $_);
3450 print "r$r = $_\n";
3452 close $fh or croak "close: $!";
3453 unlink $path or croak "unlink: $!";
3456 sub rebuild {
3457 my ($self) = @_;
3458 my $map_path = $self->map_path;
3459 my $partial = (-e $map_path && ! -z $map_path);
3460 return unless ::verify_ref($self->refname.'^0');
3461 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3462 my $rev_db = $self->rev_db_path;
3463 $self->rebuild_from_rev_db($rev_db);
3464 if ($self->use_svm_props) {
3465 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3466 $self->rebuild_from_rev_db($svm_rev_db);
3468 $self->unlink_rev_db_symlink;
3469 return;
3471 print "Rebuilding $map_path ...\n" if (!$partial);
3472 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3473 (undef, undef));
3474 my ($log, $ctx) =
3475 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3476 ($head ? "$head.." : "") . $self->refname,
3477 '--');
3478 my $metadata_url = $self->metadata_url;
3479 remove_username($metadata_url);
3480 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3481 my $c;
3482 while (<$log>) {
3483 if ( m{^commit ($::sha1)$} ) {
3484 $c = $1;
3485 next;
3487 next unless s{^\s*(git-svn-id:)}{$1};
3488 my ($url, $rev, $uuid) = ::extract_metadata($_);
3489 remove_username($url);
3491 # ignore merges (from set-tree)
3492 next if (!defined $rev || !$uuid);
3494 # if we merged or otherwise started elsewhere, this is
3495 # how we break out of it
3496 if (($uuid ne $svn_uuid) ||
3497 ($metadata_url && $url && ($url ne $metadata_url))) {
3498 next;
3500 if ($partial && $head) {
3501 print "Partial-rebuilding $map_path ...\n";
3502 print "Currently at $base_rev = $head\n";
3503 $head = undef;
3506 $self->rev_map_set($rev, $c);
3507 print "r$rev = $c\n";
3509 command_close_pipe($log, $ctx);
3510 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3511 my $rev_db_path = $self->rev_db_path;
3512 if (-f $self->rev_db_path) {
3513 unlink $self->rev_db_path or croak "unlink: $!";
3515 $self->unlink_rev_db_symlink;
3518 # rev_map:
3519 # Tie::File seems to be prone to offset errors if revisions get sparse,
3520 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3521 # one of my favorite modules is out :< Next up would be one of the DBM
3522 # modules, but I'm not sure which is most portable...
3524 # This is the replacement for the rev_db format, which was too big
3525 # and inefficient for large repositories with a lot of sparse history
3526 # (mainly tags)
3528 # The format is this:
3529 # - 24 bytes for every record,
3530 # * 4 bytes for the integer representing an SVN revision number
3531 # * 20 bytes representing the sha1 of a git commit
3532 # - No empty padding records like the old format
3533 # (except the last record, which can be overwritten)
3534 # - new records are written append-only since SVN revision numbers
3535 # increase monotonically
3536 # - lookups on SVN revision number are done via a binary search
3537 # - Piping the file to xxd -c24 is a good way of dumping it for
3538 # viewing or editing (piped back through xxd -r), should the need
3539 # ever arise.
3540 # - The last record can be padding revision with an all-zero sha1
3541 # This is used to optimize fetch performance when using multiple
3542 # "fetch" directives in .git/config
3544 # These files are disposable unless noMetadata or useSvmProps is set
3546 sub _rev_map_set {
3547 my ($fh, $rev, $commit) = @_;
3549 binmode $fh or croak "binmode: $!";
3550 my $size = (stat($fh))[7];
3551 ($size % 24) == 0 or croak "inconsistent size: $size";
3553 my $wr_offset = 0;
3554 if ($size > 0) {
3555 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3556 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3557 $read == 24 or croak "read only $read bytes (!= 24)";
3558 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3559 if ($last_commit eq ('0' x40)) {
3560 if ($size >= 48) {
3561 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3562 $read = sysread($fh, $buf, 24) or
3563 croak "read: $!";
3564 $read == 24 or
3565 croak "read only $read bytes (!= 24)";
3566 ($last_rev, $last_commit) =
3567 unpack(rev_map_fmt, $buf);
3568 if ($last_commit eq ('0' x40)) {
3569 croak "inconsistent .rev_map\n";
3572 if ($last_rev >= $rev) {
3573 croak "last_rev is higher!: $last_rev >= $rev";
3575 $wr_offset = -24;
3578 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3579 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3580 croak "write: $!";
3583 sub _rev_map_reset {
3584 my ($fh, $rev, $commit) = @_;
3585 my $c = _rev_map_get($fh, $rev);
3586 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3587 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3588 truncate $fh, $offset or croak "truncate: $!";
3591 sub mkfile {
3592 my ($path) = @_;
3593 unless (-e $path) {
3594 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3595 mkpath([$dir]) unless -d $dir;
3596 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3597 close $fh or die "Couldn't close (create) $path: $!\n";
3601 sub rev_map_set {
3602 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3603 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3604 my $db = $self->map_path($uuid);
3605 my $db_lock = "$db.lock";
3606 my $sig;
3607 $update_ref ||= 0;
3608 if ($update_ref) {
3609 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3610 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3612 mkfile($db);
3614 $LOCKFILES{$db_lock} = 1;
3615 my $sync;
3616 # both of these options make our .rev_db file very, very important
3617 # and we can't afford to lose it because rebuild() won't work
3618 if ($self->use_svm_props || $self->no_metadata) {
3619 $sync = 1;
3620 copy($db, $db_lock) or die "rev_map_set(@_): ",
3621 "Failed to copy: ",
3622 "$db => $db_lock ($!)\n";
3623 } else {
3624 rename $db, $db_lock or die "rev_map_set(@_): ",
3625 "Failed to rename: ",
3626 "$db => $db_lock ($!)\n";
3629 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3630 or croak "Couldn't open $db_lock: $!\n";
3631 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3632 _rev_map_set($fh, $rev, $commit);
3633 if ($sync) {
3634 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3635 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3637 close $fh or croak $!;
3638 if ($update_ref) {
3639 $_head = $self;
3640 my $note = "";
3641 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3642 command_noisy('update-ref', '-m', "r$rev$note",
3643 $self->refname, $commit);
3645 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3646 "$db_lock => $db ($!)\n";
3647 delete $LOCKFILES{$db_lock};
3648 if ($update_ref) {
3649 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3650 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3651 kill $sig, $$ if defined $sig;
3655 # If want_commit, this will return an array of (rev, commit) where
3656 # commit _must_ be a valid commit in the archive.
3657 # Otherwise, it'll return the max revision (whether or not the
3658 # commit is valid or just a 0x40 placeholder).
3659 sub rev_map_max {
3660 my ($self, $want_commit) = @_;
3661 $self->rebuild;
3662 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3663 $want_commit ? ($r, $c) : $r;
3666 sub rev_map_max_norebuild {
3667 my ($self, $want_commit) = @_;
3668 my $map_path = $self->map_path;
3669 stat $map_path or return $want_commit ? (0, undef) : 0;
3670 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3671 binmode $fh or croak "binmode: $!";
3672 my $size = (stat($fh))[7];
3673 ($size % 24) == 0 or croak "inconsistent size: $size";
3675 if ($size == 0) {
3676 close $fh or croak "close: $!";
3677 return $want_commit ? (0, undef) : 0;
3680 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3681 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3682 my ($r, $c) = unpack(rev_map_fmt, $buf);
3683 if ($want_commit && $c eq ('0' x40)) {
3684 if ($size < 48) {
3685 return $want_commit ? (0, undef) : 0;
3687 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3688 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3689 ($r, $c) = unpack(rev_map_fmt, $buf);
3690 if ($c eq ('0'x40)) {
3691 croak "Penultimate record is all-zeroes in $map_path";
3694 close $fh or croak "close: $!";
3695 $want_commit ? ($r, $c) : $r;
3698 sub rev_map_get {
3699 my ($self, $rev, $uuid) = @_;
3700 my $map_path = $self->map_path($uuid);
3701 return undef unless -e $map_path;
3703 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3704 my $c = _rev_map_get($fh, $rev);
3705 close($fh) or croak "close: $!";
3709 sub _rev_map_get {
3710 my ($fh, $rev) = @_;
3712 binmode $fh or croak "binmode: $!";
3713 my $size = (stat($fh))[7];
3714 ($size % 24) == 0 or croak "inconsistent size: $size";
3716 if ($size == 0) {
3717 return undef;
3720 my ($l, $u) = (0, $size - 24);
3721 my ($r, $c, $buf);
3723 while ($l <= $u) {
3724 my $i = int(($l/24 + $u/24) / 2) * 24;
3725 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3726 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3727 my ($r, $c) = unpack(rev_map_fmt, $buf);
3729 if ($r < $rev) {
3730 $l = $i + 24;
3731 } elsif ($r > $rev) {
3732 $u = $i - 24;
3733 } else { # $r == $rev
3734 return $c eq ('0' x 40) ? undef : $c;
3737 undef;
3740 # Finds the first svn revision that exists on (if $eq_ok is true) or
3741 # before $rev for the current branch. It will not search any lower
3742 # than $min_rev. Returns the git commit hash and svn revision number
3743 # if found, else (undef, undef).
3744 sub find_rev_before {
3745 my ($self, $rev, $eq_ok, $min_rev) = @_;
3746 --$rev unless $eq_ok;
3747 $min_rev ||= 1;
3748 my $max_rev = $self->rev_map_max;
3749 $rev = $max_rev if ($rev > $max_rev);
3750 while ($rev >= $min_rev) {
3751 if (my $c = $self->rev_map_get($rev)) {
3752 return ($rev, $c);
3754 --$rev;
3756 return (undef, undef);
3759 # Finds the first svn revision that exists on (if $eq_ok is true) or
3760 # after $rev for the current branch. It will not search any higher
3761 # than $max_rev. Returns the git commit hash and svn revision number
3762 # if found, else (undef, undef).
3763 sub find_rev_after {
3764 my ($self, $rev, $eq_ok, $max_rev) = @_;
3765 ++$rev unless $eq_ok;
3766 $max_rev ||= $self->rev_map_max;
3767 while ($rev <= $max_rev) {
3768 if (my $c = $self->rev_map_get($rev)) {
3769 return ($rev, $c);
3771 ++$rev;
3773 return (undef, undef);
3776 sub _new {
3777 my ($class, $repo_id, $ref_id, $path) = @_;
3778 unless (defined $repo_id && length $repo_id) {
3779 $repo_id = $Git::SVN::default_repo_id;
3781 unless (defined $ref_id && length $ref_id) {
3782 $_prefix = '' unless defined($_prefix);
3783 $_[2] = $ref_id =
3784 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3786 $_[1] = $repo_id;
3787 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3789 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3790 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3791 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3792 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3793 if (-d $old_dir && ! -d $dir) {
3794 $dir = $old_dir;
3798 $_[3] = $path = '' unless (defined $path);
3799 mkpath([$dir]);
3800 bless {
3801 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3802 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3803 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3806 # for read-only access of old .rev_db formats
3807 sub unlink_rev_db_symlink {
3808 my ($self) = @_;
3809 my $link = $self->rev_db_path;
3810 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3811 if (-l $link) {
3812 unlink $link or croak "unlink: $link failed!";
3816 sub rev_db_path {
3817 my ($self, $uuid) = @_;
3818 my $db_path = $self->map_path($uuid);
3819 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3820 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3821 $db_path;
3824 # the new replacement for .rev_db
3825 sub map_path {
3826 my ($self, $uuid) = @_;
3827 $uuid ||= $self->ra_uuid;
3828 "$self->{map_root}.$uuid";
3831 sub uri_encode {
3832 my ($f) = @_;
3833 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3837 sub uri_decode {
3838 my ($f) = @_;
3839 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3843 sub remove_username {
3844 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3847 package Git::SVN::Prompt;
3848 use strict;
3849 use warnings;
3850 require SVN::Core;
3851 use vars qw/$_no_auth_cache $_username/;
3853 sub simple {
3854 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3855 $may_save = undef if $_no_auth_cache;
3856 $default_username = $_username if defined $_username;
3857 if (defined $default_username && length $default_username) {
3858 if (defined $realm && length $realm) {
3859 print STDERR "Authentication realm: $realm\n";
3860 STDERR->flush;
3862 $cred->username($default_username);
3863 } else {
3864 username($cred, $realm, $may_save, $pool);
3866 $cred->password(_read_password("Password for '" .
3867 $cred->username . "': ", $realm));
3868 $cred->may_save($may_save);
3869 $SVN::_Core::SVN_NO_ERROR;
3872 sub ssl_server_trust {
3873 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3874 $may_save = undef if $_no_auth_cache;
3875 print STDERR "Error validating server certificate for '$realm':\n";
3877 no warnings 'once';
3878 # All variables SVN::Auth::SSL::* are used only once,
3879 # so we're shutting up Perl warnings about this.
3880 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3881 print STDERR " - The certificate is not issued ",
3882 "by a trusted authority. Use the\n",
3883 " fingerprint to validate ",
3884 "the certificate manually!\n";
3886 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3887 print STDERR " - The certificate hostname ",
3888 "does not match.\n";
3890 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3891 print STDERR " - The certificate is not yet valid.\n";
3893 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3894 print STDERR " - The certificate has expired.\n";
3896 if ($failures & $SVN::Auth::SSL::OTHER) {
3897 print STDERR " - The certificate has ",
3898 "an unknown error.\n";
3900 } # no warnings 'once'
3901 printf STDERR
3902 "Certificate information:\n".
3903 " - Hostname: %s\n".
3904 " - Valid: from %s until %s\n".
3905 " - Issuer: %s\n".
3906 " - Fingerprint: %s\n",
3907 map $cert_info->$_, qw(hostname valid_from valid_until
3908 issuer_dname fingerprint);
3909 my $choice;
3910 prompt:
3911 print STDERR $may_save ?
3912 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3913 "(R)eject or accept (t)emporarily? ";
3914 STDERR->flush;
3915 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3916 if ($choice =~ /^t$/i) {
3917 $cred->may_save(undef);
3918 } elsif ($choice =~ /^r$/i) {
3919 return -1;
3920 } elsif ($may_save && $choice =~ /^p$/i) {
3921 $cred->may_save($may_save);
3922 } else {
3923 goto prompt;
3925 $cred->accepted_failures($failures);
3926 $SVN::_Core::SVN_NO_ERROR;
3929 sub ssl_client_cert {
3930 my ($cred, $realm, $may_save, $pool) = @_;
3931 $may_save = undef if $_no_auth_cache;
3932 print STDERR "Client certificate filename: ";
3933 STDERR->flush;
3934 chomp(my $filename = <STDIN>);
3935 $cred->cert_file($filename);
3936 $cred->may_save($may_save);
3937 $SVN::_Core::SVN_NO_ERROR;
3940 sub ssl_client_cert_pw {
3941 my ($cred, $realm, $may_save, $pool) = @_;
3942 $may_save = undef if $_no_auth_cache;
3943 $cred->password(_read_password("Password: ", $realm));
3944 $cred->may_save($may_save);
3945 $SVN::_Core::SVN_NO_ERROR;
3948 sub username {
3949 my ($cred, $realm, $may_save, $pool) = @_;
3950 $may_save = undef if $_no_auth_cache;
3951 if (defined $realm && length $realm) {
3952 print STDERR "Authentication realm: $realm\n";
3954 my $username;
3955 if (defined $_username) {
3956 $username = $_username;
3957 } else {
3958 print STDERR "Username: ";
3959 STDERR->flush;
3960 chomp($username = <STDIN>);
3962 $cred->username($username);
3963 $cred->may_save($may_save);
3964 $SVN::_Core::SVN_NO_ERROR;
3967 sub _read_password {
3968 my ($prompt, $realm) = @_;
3969 print STDERR $prompt;
3970 STDERR->flush;
3971 require Term::ReadKey;
3972 Term::ReadKey::ReadMode('noecho');
3973 my $password = '';
3974 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3975 last if $key =~ /[\012\015]/; # \n\r
3976 $password .= $key;
3978 Term::ReadKey::ReadMode('restore');
3979 print STDERR "\n";
3980 STDERR->flush;
3981 $password;
3984 package SVN::Git::Fetcher;
3985 use vars qw/@ISA/;
3986 use strict;
3987 use warnings;
3988 use Carp qw/croak/;
3989 use File::Temp qw/tempfile/;
3990 use IO::File qw//;
3991 use vars qw/$_ignore_regex/;
3993 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3994 sub new {
3995 my ($class, $git_svn, $switch_path) = @_;
3996 my $self = SVN::Delta::Editor->new;
3997 bless $self, $class;
3998 if (exists $git_svn->{last_commit}) {
3999 $self->{c} = $git_svn->{last_commit};
4000 $self->{empty_symlinks} =
4001 _mark_empty_symlinks($git_svn, $switch_path);
4003 $self->{ignore_regex} = eval { command_oneline('config', '--get',
4004 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
4005 $self->{empty} = {};
4006 $self->{dir_prop} = {};
4007 $self->{file_prop} = {};
4008 $self->{absent_dir} = {};
4009 $self->{absent_file} = {};
4010 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4011 $self;
4014 # this uses the Ra object, so it must be called before do_{switch,update},
4015 # not inside them (when the Git::SVN::Fetcher object is passed) to
4016 # do_{switch,update}
4017 sub _mark_empty_symlinks {
4018 my ($git_svn, $switch_path) = @_;
4019 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4020 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4022 my %ret;
4023 my ($rev, $cmt) = $git_svn->last_rev_commit;
4024 return {} unless ($rev && $cmt);
4026 # allow the warning to be printed for each revision we fetch to
4027 # ensure the user sees it. The user can also disable the workaround
4028 # on the repository even while git svn is running and the next
4029 # revision fetched will skip this expensive function.
4030 my $printed_warning;
4031 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4032 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4033 local $/ = "\0";
4034 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4035 $pfx .= '/' if length($pfx);
4036 while (<$ls>) {
4037 chomp;
4038 s/\A100644 blob $empty_blob\t//o or next;
4039 unless ($printed_warning) {
4040 print STDERR "Scanning for empty symlinks, ",
4041 "this may take a while if you have ",
4042 "many empty files\n",
4043 "You may disable this with `",
4044 "git config svn.brokenSymlinkWorkaround ",
4045 "false'.\n",
4046 "This may be done in a different ",
4047 "terminal without restarting ",
4048 "git svn\n";
4049 $printed_warning = 1;
4051 my $path = $_;
4052 my (undef, $props) =
4053 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4054 if ($props->{'svn:special'}) {
4055 $ret{$path} = 1;
4058 command_close_pipe($ls, $ctx);
4059 \%ret;
4062 # returns true if a given path is inside a ".git" directory
4063 sub in_dot_git {
4064 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4067 # return value: 0 -- don't ignore, 1 -- ignore
4068 sub is_path_ignored {
4069 my ($self, $path) = @_;
4070 return 1 if in_dot_git($path);
4071 return 1 if defined($self->{ignore_regex}) &&
4072 $path =~ m!$self->{ignore_regex}!;
4073 return 0 unless defined($_ignore_regex);
4074 return 1 if $path =~ m!$_ignore_regex!o;
4075 return 0;
4078 sub set_path_strip {
4079 my ($self, $path) = @_;
4080 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4083 sub open_root {
4084 { path => '' };
4087 sub open_directory {
4088 my ($self, $path, $pb, $rev) = @_;
4089 { path => $path };
4092 sub git_path {
4093 my ($self, $path) = @_;
4094 if ($self->{path_strip}) {
4095 $path =~ s!$self->{path_strip}!! or
4096 die "Failed to strip path '$path' ($self->{path_strip})\n";
4098 $path;
4101 sub delete_entry {
4102 my ($self, $path, $rev, $pb) = @_;
4103 return undef if $self->is_path_ignored($path);
4105 my $gpath = $self->git_path($path);
4106 return undef if ($gpath eq '');
4108 # remove entire directories.
4109 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4110 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4111 if ($tree) {
4112 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4113 -r --name-only -z/,
4114 $tree);
4115 local $/ = "\0";
4116 while (<$ls>) {
4117 chomp;
4118 my $rmpath = "$gpath/$_";
4119 $self->{gii}->remove($rmpath);
4120 print "\tD\t$rmpath\n" unless $::_q;
4122 print "\tD\t$gpath/\n" unless $::_q;
4123 command_close_pipe($ls, $ctx);
4124 } else {
4125 $self->{gii}->remove($gpath);
4126 print "\tD\t$gpath\n" unless $::_q;
4128 $self->{empty}->{$path} = 0;
4129 undef;
4132 sub open_file {
4133 my ($self, $path, $pb, $rev) = @_;
4134 my ($mode, $blob);
4136 goto out if $self->is_path_ignored($path);
4138 my $gpath = $self->git_path($path);
4139 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4140 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4141 unless (defined $mode && defined $blob) {
4142 die "$path was not found in commit $self->{c} (r$rev)\n";
4144 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4145 $mode = '120000';
4147 out:
4148 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4149 pool => SVN::Pool->new, action => 'M' };
4152 sub add_file {
4153 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4154 my $mode;
4156 if (!$self->is_path_ignored($path)) {
4157 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4158 delete $self->{empty}->{$dir};
4159 $mode = '100644';
4161 { path => $path, mode_a => $mode, mode_b => $mode,
4162 pool => SVN::Pool->new, action => 'A' };
4165 sub add_directory {
4166 my ($self, $path, $cp_path, $cp_rev) = @_;
4167 goto out if $self->is_path_ignored($path);
4168 my $gpath = $self->git_path($path);
4169 if ($gpath eq '') {
4170 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4171 -r --name-only -z/,
4172 $self->{c});
4173 local $/ = "\0";
4174 while (<$ls>) {
4175 chomp;
4176 $self->{gii}->remove($_);
4177 print "\tD\t$_\n" unless $::_q;
4179 command_close_pipe($ls, $ctx);
4180 $self->{empty}->{$path} = 0;
4182 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4183 delete $self->{empty}->{$dir};
4184 $self->{empty}->{$path} = 1;
4185 out:
4186 { path => $path };
4189 sub change_dir_prop {
4190 my ($self, $db, $prop, $value) = @_;
4191 return undef if $self->is_path_ignored($db->{path});
4192 $self->{dir_prop}->{$db->{path}} ||= {};
4193 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4194 undef;
4197 sub absent_directory {
4198 my ($self, $path, $pb) = @_;
4199 return undef if $self->is_path_ignored($path);
4200 $self->{absent_dir}->{$pb->{path}} ||= [];
4201 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4202 undef;
4205 sub absent_file {
4206 my ($self, $path, $pb) = @_;
4207 return undef if $self->is_path_ignored($path);
4208 $self->{absent_file}->{$pb->{path}} ||= [];
4209 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4210 undef;
4213 sub change_file_prop {
4214 my ($self, $fb, $prop, $value) = @_;
4215 return undef if $self->is_path_ignored($fb->{path});
4216 if ($prop eq 'svn:executable') {
4217 if ($fb->{mode_b} != 120000) {
4218 $fb->{mode_b} = defined $value ? 100755 : 100644;
4220 } elsif ($prop eq 'svn:special') {
4221 $fb->{mode_b} = defined $value ? 120000 : 100644;
4222 } else {
4223 $self->{file_prop}->{$fb->{path}} ||= {};
4224 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4226 undef;
4229 sub apply_textdelta {
4230 my ($self, $fb, $exp) = @_;
4231 return undef if $self->is_path_ignored($fb->{path});
4232 my $fh = $::_repository->temp_acquire('svn_delta');
4233 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4234 # (but $base does not,) so dup() it for reading in close_file
4235 open my $dup, '<&', $fh or croak $!;
4236 my $base = $::_repository->temp_acquire('git_blob');
4238 if ($fb->{blob}) {
4239 my ($base_is_link, $size);
4241 if ($fb->{mode_a} eq '120000' &&
4242 ! $self->{empty_symlinks}->{$fb->{path}}) {
4243 print $base 'link ' or die "print $!\n";
4244 $base_is_link = 1;
4246 retry:
4247 $size = $::_repository->cat_blob($fb->{blob}, $base);
4248 die "Failed to read object $fb->{blob}" if ($size < 0);
4250 if (defined $exp) {
4251 seek $base, 0, 0 or croak $!;
4252 my $got = ::md5sum($base);
4253 if ($got ne $exp) {
4254 my $err = "Checksum mismatch: ".
4255 "$fb->{path} $fb->{blob}\n" .
4256 "expected: $exp\n" .
4257 " got: $got\n";
4258 if ($base_is_link) {
4259 warn $err,
4260 "Retrying... (possibly ",
4261 "a bad symlink from SVN)\n";
4262 $::_repository->temp_reset($base);
4263 $base_is_link = 0;
4264 goto retry;
4266 die $err;
4270 seek $base, 0, 0 or croak $!;
4271 $fb->{fh} = $fh;
4272 $fb->{base} = $base;
4273 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4276 sub close_file {
4277 my ($self, $fb, $exp) = @_;
4278 return undef if $self->is_path_ignored($fb->{path});
4280 my $hash;
4281 my $path = $self->git_path($fb->{path});
4282 if (my $fh = $fb->{fh}) {
4283 if (defined $exp) {
4284 seek($fh, 0, 0) or croak $!;
4285 my $got = ::md5sum($fh);
4286 if ($got ne $exp) {
4287 die "Checksum mismatch: $path\n",
4288 "expected: $exp\n got: $got\n";
4291 if ($fb->{mode_b} == 120000) {
4292 sysseek($fh, 0, 0) or croak $!;
4293 my $rd = sysread($fh, my $buf, 5);
4295 if (!defined $rd) {
4296 croak "sysread: $!\n";
4297 } elsif ($rd == 0) {
4298 warn "$path has mode 120000",
4299 " but it points to nothing\n",
4300 "converting to an empty file with mode",
4301 " 100644\n";
4302 $fb->{mode_b} = '100644';
4303 } elsif ($buf ne 'link ') {
4304 warn "$path has mode 120000",
4305 " but is not a link\n";
4306 } else {
4307 my $tmp_fh = $::_repository->temp_acquire(
4308 'svn_hash');
4309 my $res;
4310 while ($res = sysread($fh, my $str, 1024)) {
4311 my $out = syswrite($tmp_fh, $str, $res);
4312 defined($out) && $out == $res
4313 or croak("write ",
4314 Git::temp_path($tmp_fh),
4315 ": $!\n");
4317 defined $res or croak $!;
4319 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4320 Git::temp_release($tmp_fh, 1);
4324 $hash = $::_repository->hash_and_insert_object(
4325 Git::temp_path($fh));
4326 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4328 Git::temp_release($fb->{base}, 1);
4329 Git::temp_release($fh, 1);
4330 } else {
4331 $hash = $fb->{blob} or die "no blob information\n";
4333 $fb->{pool}->clear;
4334 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4335 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4336 undef;
4339 sub abort_edit {
4340 my $self = shift;
4341 $self->{nr} = $self->{gii}->{nr};
4342 delete $self->{gii};
4343 $self->SUPER::abort_edit(@_);
4346 sub close_edit {
4347 my $self = shift;
4348 $self->{git_commit_ok} = 1;
4349 $self->{nr} = $self->{gii}->{nr};
4350 delete $self->{gii};
4351 $self->SUPER::close_edit(@_);
4354 package SVN::Git::Editor;
4355 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4356 use strict;
4357 use warnings;
4358 use Carp qw/croak/;
4359 use IO::File;
4361 sub new {
4362 my ($class, $opts) = @_;
4363 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4364 die "$_ required!\n" unless (defined $opts->{$_});
4367 my $pool = SVN::Pool->new;
4368 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4369 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4370 $opts->{r}, $mods);
4372 # $opts->{ra} functions should not be used after this:
4373 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4374 $opts->{editor_cb}, $pool);
4375 my $self = SVN::Delta::Editor->new(@ce, $pool);
4376 bless $self, $class;
4377 foreach (qw/svn_path r tree_a tree_b/) {
4378 $self->{$_} = $opts->{$_};
4380 $self->{url} = $opts->{ra}->{url};
4381 $self->{mods} = $mods;
4382 $self->{types} = $types;
4383 $self->{pool} = $pool;
4384 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4385 $self->{rm} = { };
4386 $self->{path_prefix} = length $self->{svn_path} ?
4387 "$self->{svn_path}/" : '';
4388 $self->{config} = $opts->{config};
4389 return $self;
4392 sub generate_diff {
4393 my ($tree_a, $tree_b) = @_;
4394 my @diff_tree = qw(diff-tree -z -r);
4395 if ($_cp_similarity) {
4396 push @diff_tree, "-C$_cp_similarity";
4397 } else {
4398 push @diff_tree, '-C';
4400 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4401 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4402 push @diff_tree, $tree_a, $tree_b;
4403 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4404 local $/ = "\0";
4405 my $state = 'meta';
4406 my @mods;
4407 while (<$diff_fh>) {
4408 chomp $_; # this gets rid of the trailing "\0"
4409 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4410 ($::sha1)\s($::sha1)\s
4411 ([MTCRAD])\d*$/xo) {
4412 push @mods, { mode_a => $1, mode_b => $2,
4413 sha1_a => $3, sha1_b => $4,
4414 chg => $5 };
4415 if ($5 =~ /^(?:C|R)$/) {
4416 $state = 'file_a';
4417 } else {
4418 $state = 'file_b';
4420 } elsif ($state eq 'file_a') {
4421 my $x = $mods[$#mods] or croak "Empty array\n";
4422 if ($x->{chg} !~ /^(?:C|R)$/) {
4423 croak "Error parsing $_, $x->{chg}\n";
4425 $x->{file_a} = $_;
4426 $state = 'file_b';
4427 } elsif ($state eq 'file_b') {
4428 my $x = $mods[$#mods] or croak "Empty array\n";
4429 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4430 croak "Error parsing $_, $x->{chg}\n";
4432 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4433 croak "Error parsing $_, $x->{chg}\n";
4435 $x->{file_b} = $_;
4436 $state = 'meta';
4437 } else {
4438 croak "Error parsing $_\n";
4441 command_close_pipe($diff_fh, $ctx);
4442 \@mods;
4445 sub check_diff_paths {
4446 my ($ra, $pfx, $rev, $mods) = @_;
4447 my %types;
4448 $pfx .= '/' if length $pfx;
4450 sub type_diff_paths {
4451 my ($ra, $types, $path, $rev) = @_;
4452 my @p = split m#/+#, $path;
4453 my $c = shift @p;
4454 unless (defined $types->{$c}) {
4455 $types->{$c} = $ra->check_path($c, $rev);
4457 while (@p) {
4458 $c .= '/' . shift @p;
4459 next if defined $types->{$c};
4460 $types->{$c} = $ra->check_path($c, $rev);
4464 foreach my $m (@$mods) {
4465 foreach my $f (qw/file_a file_b/) {
4466 next unless defined $m->{$f};
4467 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4468 if (length $pfx.$dir && ! defined $types{$dir}) {
4469 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4473 \%types;
4476 sub split_path {
4477 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4480 sub repo_path {
4481 my ($self, $path) = @_;
4482 $self->{path_prefix}.(defined $path ? $path : '');
4485 sub url_path {
4486 my ($self, $path) = @_;
4487 if ($self->{url} =~ m#^https?://#) {
4488 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4490 $self->{url} . '/' . $self->repo_path($path);
4493 sub rmdirs {
4494 my ($self) = @_;
4495 my $rm = $self->{rm};
4496 delete $rm->{''}; # we never delete the url we're tracking
4497 return unless %$rm;
4499 foreach (keys %$rm) {
4500 my @d = split m#/#, $_;
4501 my $c = shift @d;
4502 $rm->{$c} = 1;
4503 while (@d) {
4504 $c .= '/' . shift @d;
4505 $rm->{$c} = 1;
4508 delete $rm->{$self->{svn_path}};
4509 delete $rm->{''}; # we never delete the url we're tracking
4510 return unless %$rm;
4512 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4513 $self->{tree_b});
4514 local $/ = "\0";
4515 while (<$fh>) {
4516 chomp;
4517 my @dn = split m#/#, $_;
4518 while (pop @dn) {
4519 delete $rm->{join '/', @dn};
4521 unless (%$rm) {
4522 close $fh;
4523 return;
4526 command_close_pipe($fh, $ctx);
4528 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4529 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4530 $self->close_directory($bat->{$d}, $p);
4531 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4532 print "\tD+\t$d/\n" unless $::_q;
4533 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4534 delete $bat->{$d};
4538 sub open_or_add_dir {
4539 my ($self, $full_path, $baton) = @_;
4540 my $t = $self->{types}->{$full_path};
4541 if (!defined $t) {
4542 die "$full_path not known in r$self->{r} or we have a bug!\n";
4545 no warnings 'once';
4546 # SVN::Node::none and SVN::Node::file are used only once,
4547 # so we're shutting up Perl's warnings about them.
4548 if ($t == $SVN::Node::none) {
4549 return $self->add_directory($full_path, $baton,
4550 undef, -1, $self->{pool});
4551 } elsif ($t == $SVN::Node::dir) {
4552 return $self->open_directory($full_path, $baton,
4553 $self->{r}, $self->{pool});
4554 } # no warnings 'once'
4555 print STDERR "$full_path already exists in repository at ",
4556 "r$self->{r} and it is not a directory (",
4557 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4558 } # no warnings 'once'
4559 exit 1;
4562 sub ensure_path {
4563 my ($self, $path) = @_;
4564 my $bat = $self->{bat};
4565 my $repo_path = $self->repo_path($path);
4566 return $bat->{''} unless (length $repo_path);
4567 my @p = split m#/+#, $repo_path;
4568 my $c = shift @p;
4569 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4570 while (@p) {
4571 my $c0 = $c;
4572 $c .= '/' . shift @p;
4573 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4575 return $bat->{$c};
4578 # Subroutine to convert a globbing pattern to a regular expression.
4579 # From perl cookbook.
4580 sub glob2pat {
4581 my $globstr = shift;
4582 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4583 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4584 return '^' . $globstr . '$';
4587 sub check_autoprop {
4588 my ($self, $pattern, $properties, $file, $fbat) = @_;
4589 # Convert the globbing pattern to a regular expression.
4590 my $regex = glob2pat($pattern);
4591 # Check if the pattern matches the file name.
4592 if($file =~ m/($regex)/) {
4593 # Parse the list of properties to set.
4594 my @props = split(/;/, $properties);
4595 foreach my $prop (@props) {
4596 # Parse 'name=value' syntax and set the property.
4597 if ($prop =~ /([^=]+)=(.*)/) {
4598 my ($n,$v) = ($1,$2);
4599 for ($n, $v) {
4600 s/^\s+//; s/\s+$//;
4602 $self->change_file_prop($fbat, $n, $v);
4608 sub apply_autoprops {
4609 my ($self, $file, $fbat) = @_;
4610 my $conf_t = ${$self->{config}}{'config'};
4611 no warnings 'once';
4612 # Check [miscellany]/enable-auto-props in svn configuration.
4613 if (SVN::_Core::svn_config_get_bool(
4614 $conf_t,
4615 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4616 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4617 0)) {
4618 # Auto-props are enabled. Enumerate them to look for matches.
4619 my $callback = sub {
4620 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4622 SVN::_Core::svn_config_enumerate(
4623 $conf_t,
4624 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4625 $callback);
4629 sub A {
4630 my ($self, $m) = @_;
4631 my ($dir, $file) = split_path($m->{file_b});
4632 my $pbat = $self->ensure_path($dir);
4633 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4634 undef, -1);
4635 print "\tA\t$m->{file_b}\n" unless $::_q;
4636 $self->apply_autoprops($file, $fbat);
4637 $self->chg_file($fbat, $m);
4638 $self->close_file($fbat,undef,$self->{pool});
4641 sub C {
4642 my ($self, $m) = @_;
4643 my ($dir, $file) = split_path($m->{file_b});
4644 my $pbat = $self->ensure_path($dir);
4645 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4646 $self->url_path($m->{file_a}), $self->{r});
4647 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4648 $self->chg_file($fbat, $m);
4649 $self->close_file($fbat,undef,$self->{pool});
4652 sub delete_entry {
4653 my ($self, $path, $pbat) = @_;
4654 my $rpath = $self->repo_path($path);
4655 my ($dir, $file) = split_path($rpath);
4656 $self->{rm}->{$dir} = 1;
4657 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4660 sub R {
4661 my ($self, $m) = @_;
4662 my ($dir, $file) = split_path($m->{file_b});
4663 my $pbat = $self->ensure_path($dir);
4664 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4665 $self->url_path($m->{file_a}), $self->{r});
4666 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4667 $self->apply_autoprops($file, $fbat);
4668 $self->chg_file($fbat, $m);
4669 $self->close_file($fbat,undef,$self->{pool});
4671 ($dir, $file) = split_path($m->{file_a});
4672 $pbat = $self->ensure_path($dir);
4673 $self->delete_entry($m->{file_a}, $pbat);
4676 sub M {
4677 my ($self, $m) = @_;
4678 my ($dir, $file) = split_path($m->{file_b});
4679 my $pbat = $self->ensure_path($dir);
4680 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4681 $pbat,$self->{r},$self->{pool});
4682 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4683 $self->chg_file($fbat, $m);
4684 $self->close_file($fbat,undef,$self->{pool});
4687 sub T { shift->M(@_) }
4689 sub change_file_prop {
4690 my ($self, $fbat, $pname, $pval) = @_;
4691 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4694 sub _chg_file_get_blob ($$$$) {
4695 my ($self, $fbat, $m, $which) = @_;
4696 my $fh = $::_repository->temp_acquire("git_blob_$which");
4697 if ($m->{"mode_$which"} =~ /^120/) {
4698 print $fh 'link ' or croak $!;
4699 $self->change_file_prop($fbat,'svn:special','*');
4700 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4701 $self->change_file_prop($fbat,'svn:special',undef);
4703 my $blob = $m->{"sha1_$which"};
4704 return ($fh,) if ($blob =~ /^0{40}$/);
4705 my $size = $::_repository->cat_blob($blob, $fh);
4706 croak "Failed to read object $blob" if ($size < 0);
4707 $fh->flush == 0 or croak $!;
4708 seek $fh, 0, 0 or croak $!;
4710 my $exp = ::md5sum($fh);
4711 seek $fh, 0, 0 or croak $!;
4712 return ($fh, $exp);
4715 sub chg_file {
4716 my ($self, $fbat, $m) = @_;
4717 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4718 $self->change_file_prop($fbat,'svn:executable','*');
4719 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4720 $self->change_file_prop($fbat,'svn:executable',undef);
4722 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4723 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4724 my $pool = SVN::Pool->new;
4725 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4726 if (-s $fh_a) {
4727 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4728 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4729 if (defined $res) {
4730 die "Unexpected result from send_txstream: $res\n",
4731 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4733 } else {
4734 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4735 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4736 if ($got ne $exp_b);
4738 Git::temp_release($fh_b, 1);
4739 Git::temp_release($fh_a, 1);
4740 $pool->clear;
4743 sub D {
4744 my ($self, $m) = @_;
4745 my ($dir, $file) = split_path($m->{file_b});
4746 my $pbat = $self->ensure_path($dir);
4747 print "\tD\t$m->{file_b}\n" unless $::_q;
4748 $self->delete_entry($m->{file_b}, $pbat);
4751 sub close_edit {
4752 my ($self) = @_;
4753 my ($p,$bat) = ($self->{pool}, $self->{bat});
4754 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4755 next if $_ eq '';
4756 $self->close_directory($bat->{$_}, $p);
4758 $self->close_directory($bat->{''}, $p);
4759 $self->SUPER::close_edit($p);
4760 $p->clear;
4763 sub abort_edit {
4764 my ($self) = @_;
4765 $self->SUPER::abort_edit($self->{pool});
4768 sub DESTROY {
4769 my $self = shift;
4770 $self->SUPER::DESTROY(@_);
4771 $self->{pool}->clear;
4774 # this drives the editor
4775 sub apply_diff {
4776 my ($self) = @_;
4777 my $mods = $self->{mods};
4778 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4779 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4780 my $f = $m->{chg};
4781 if (defined $o{$f}) {
4782 $self->$f($m);
4783 } else {
4784 fatal("Invalid change type: $f");
4787 $self->rmdirs if $_rmdir;
4788 if (@$mods == 0) {
4789 $self->abort_edit;
4790 } else {
4791 $self->close_edit;
4793 return scalar @$mods;
4796 package Git::SVN::Ra;
4797 use vars qw/@ISA $config_dir $_log_window_size/;
4798 use strict;
4799 use warnings;
4800 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4802 BEGIN {
4803 # enforce temporary pool usage for some simple functions
4804 no strict 'refs';
4805 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4806 get_file/) {
4807 my $SUPER = "SUPER::$f";
4808 *$f = sub {
4809 my $self = shift;
4810 my $pool = SVN::Pool->new;
4811 my @ret = $self->$SUPER(@_,$pool);
4812 $pool->clear;
4813 wantarray ? @ret : $ret[0];
4818 sub _auth_providers () {
4820 SVN::Client::get_simple_provider(),
4821 SVN::Client::get_ssl_server_trust_file_provider(),
4822 SVN::Client::get_simple_prompt_provider(
4823 \&Git::SVN::Prompt::simple, 2),
4824 SVN::Client::get_ssl_client_cert_file_provider(),
4825 SVN::Client::get_ssl_client_cert_prompt_provider(
4826 \&Git::SVN::Prompt::ssl_client_cert, 2),
4827 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4828 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4829 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4830 SVN::Client::get_username_provider(),
4831 SVN::Client::get_ssl_server_trust_prompt_provider(
4832 \&Git::SVN::Prompt::ssl_server_trust),
4833 SVN::Client::get_username_prompt_provider(
4834 \&Git::SVN::Prompt::username, 2)
4838 sub escape_uri_only {
4839 my ($uri) = @_;
4840 my @tmp;
4841 foreach (split m{/}, $uri) {
4842 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4843 push @tmp, $_;
4845 join('/', @tmp);
4848 sub escape_url {
4849 my ($url) = @_;
4850 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4851 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4852 $url = "$scheme://$domain$uri";
4854 $url;
4857 sub new {
4858 my ($class, $url) = @_;
4859 $url =~ s!/+$!!;
4860 return $RA if ($RA && $RA->{url} eq $url);
4862 SVN::_Core::svn_config_ensure($config_dir, undef);
4863 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4864 my $config = SVN::Core::config_get_config($config_dir);
4865 $RA = undef;
4866 my $dont_store_passwords = 1;
4867 my $conf_t = ${$config}{'config'};
4869 no warnings 'once';
4870 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4871 # produces warnings that variables are used only once.
4872 # I had not found the better way to shut them up, so
4873 # the warnings of type 'once' are disabled in this block.
4874 if (SVN::_Core::svn_config_get_bool($conf_t,
4875 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4876 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4877 1) == 0) {
4878 SVN::_Core::svn_auth_set_parameter($baton,
4879 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4880 bless (\$dont_store_passwords, "_p_void"));
4882 if (SVN::_Core::svn_config_get_bool($conf_t,
4883 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4884 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4885 1) == 0) {
4886 $Git::SVN::Prompt::_no_auth_cache = 1;
4888 } # no warnings 'once'
4889 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4890 config => $config,
4891 pool => SVN::Pool->new,
4892 auth_provider_callbacks => $callbacks);
4893 $self->{url} = $url;
4894 $self->{svn_path} = $url;
4895 $self->{repos_root} = $self->get_repos_root;
4896 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4897 $self->{cache} = { check_path => { r => 0, data => {} },
4898 get_dir => { r => 0, data => {} } };
4899 $RA = bless $self, $class;
4902 sub check_path {
4903 my ($self, $path, $r) = @_;
4904 my $cache = $self->{cache}->{check_path};
4905 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4906 return $cache->{data}->{$path};
4908 my $pool = SVN::Pool->new;
4909 my $t = $self->SUPER::check_path($path, $r, $pool);
4910 $pool->clear;
4911 if ($r != $cache->{r}) {
4912 %{$cache->{data}} = ();
4913 $cache->{r} = $r;
4915 $cache->{data}->{$path} = $t;
4918 sub get_dir {
4919 my ($self, $dir, $r) = @_;
4920 my $cache = $self->{cache}->{get_dir};
4921 if ($r == $cache->{r}) {
4922 if (my $x = $cache->{data}->{$dir}) {
4923 return wantarray ? @$x : $x->[0];
4926 my $pool = SVN::Pool->new;
4927 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4928 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4929 $pool->clear;
4930 if ($r != $cache->{r}) {
4931 %{$cache->{data}} = ();
4932 $cache->{r} = $r;
4934 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4935 wantarray ? (\%dirents, $r, $props) : \%dirents;
4938 sub DESTROY {
4939 # do not call the real DESTROY since we store ourselves in $RA
4942 # get_log(paths, start, end, limit,
4943 # discover_changed_paths, strict_node_history, receiver)
4944 sub get_log {
4945 my ($self, @args) = @_;
4946 my $pool = SVN::Pool->new;
4948 # svn_log_changed_path_t objects passed to get_log are likely to be
4949 # overwritten even if only the refs are copied to an external variable,
4950 # so we should dup the structures in their entirety. Using an
4951 # externally passed pool (instead of our temporary and quickly cleared
4952 # pool in Git::SVN::Ra) does not help matters at all...
4953 my $receiver = pop @args;
4954 my $prefix = "/".$self->{svn_path};
4955 $prefix =~ s#/+($)##;
4956 my $prefix_regex = qr#^\Q$prefix\E#;
4957 push(@args, sub {
4958 my ($paths) = $_[0];
4959 return &$receiver(@_) unless $paths;
4960 $_[0] = ();
4961 foreach my $p (keys %$paths) {
4962 my $i = $paths->{$p};
4963 # Make path relative to our url, not repos_root
4964 $p =~ s/$prefix_regex//;
4965 my %s = map { $_ => $i->$_; }
4966 qw/copyfrom_path copyfrom_rev action/;
4967 if ($s{'copyfrom_path'}) {
4968 $s{'copyfrom_path'} =~ s/$prefix_regex//;
4970 $_[0]{$p} = \%s;
4972 &$receiver(@_);
4976 # the limit parameter was not supported in SVN 1.1.x, so we
4977 # drop it. Therefore, the receiver callback passed to it
4978 # is made aware of this limitation by being wrapped if
4979 # the limit passed to is being wrapped.
4980 if ($SVN::Core::VERSION le '1.2.0') {
4981 my $limit = splice(@args, 3, 1);
4982 if ($limit > 0) {
4983 my $receiver = pop @args;
4984 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4987 my $ret = $self->SUPER::get_log(@args, $pool);
4988 $pool->clear;
4989 $ret;
4992 sub trees_match {
4993 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4994 my $ctx = SVN::Client->new(auth => _auth_providers);
4995 my $out = IO::File->new_tmpfile;
4997 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4998 # $ctx->diff(), so we'll create a default one
4999 my $pool = SVN::Pool->new_default_sub;
5001 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5002 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5003 $out->flush;
5004 my $ret = (($out->stat)[7] == 0);
5005 close $out or croak $!;
5007 $ret;
5010 sub get_commit_editor {
5011 my ($self, $log, $cb, $pool) = @_;
5012 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5013 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5016 sub gs_do_update {
5017 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5018 my $new = ($rev_a == $rev_b);
5019 my $path = $gs->{path};
5021 if ($new && -e $gs->{index}) {
5022 unlink $gs->{index} or die
5023 "Couldn't unlink index: $gs->{index}: $!\n";
5025 my $pool = SVN::Pool->new;
5026 $editor->set_path_strip($path);
5027 my (@pc) = split m#/#, $path;
5028 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5029 1, $editor, $pool);
5030 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5032 # Since we can't rely on svn_ra_reparent being available, we'll
5033 # just have to do some magic with set_path to make it so
5034 # we only want a partial path.
5035 my $sp = '';
5036 my $final = join('/', @pc);
5037 while (@pc) {
5038 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5039 $sp .= '/' if length $sp;
5040 $sp .= shift @pc;
5042 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5044 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5046 $reporter->finish_report($pool);
5047 $pool->clear;
5048 $editor->{git_commit_ok};
5051 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5052 # svn_ra_reparent didn't work before 1.4)
5053 sub gs_do_switch {
5054 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5055 my $path = $gs->{path};
5056 my $pool = SVN::Pool->new;
5058 my $full_url = $self->{url};
5059 my $old_url = $full_url;
5060 $full_url .= '/' . $path if length $path;
5061 my ($ra, $reparented);
5063 if ($old_url =~ m#^svn(\+ssh)?://# ||
5064 ($full_url =~ m#^https?://# &&
5065 escape_url($full_url) ne $full_url)) {
5066 $_[0] = undef;
5067 $self = undef;
5068 $RA = undef;
5069 $ra = Git::SVN::Ra->new($full_url);
5070 $ra_invalid = 1;
5071 } elsif ($old_url ne $full_url) {
5072 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5073 $self->{url} = $full_url;
5074 $reparented = 1;
5077 $ra ||= $self;
5078 $url_b = escape_url($url_b);
5079 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5080 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5081 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5082 $reporter->finish_report($pool);
5084 if ($reparented) {
5085 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5086 $self->{url} = $old_url;
5089 $pool->clear;
5090 $editor->{git_commit_ok};
5093 sub longest_common_path {
5094 my ($gsv, $globs) = @_;
5095 my %common;
5096 my $common_max = scalar @$gsv;
5098 foreach my $gs (@$gsv) {
5099 my @tmp = split m#/#, $gs->{path};
5100 my $p = '';
5101 foreach (@tmp) {
5102 $p .= length($p) ? "/$_" : $_;
5103 $common{$p} ||= 0;
5104 $common{$p}++;
5107 $globs ||= [];
5108 $common_max += scalar @$globs;
5109 foreach my $glob (@$globs) {
5110 my @tmp = split m#/#, $glob->{path}->{left};
5111 my $p = '';
5112 foreach (@tmp) {
5113 $p .= length($p) ? "/$_" : $_;
5114 $common{$p} ||= 0;
5115 $common{$p}++;
5119 my $longest_path = '';
5120 foreach (sort {length $b <=> length $a} keys %common) {
5121 if ($common{$_} == $common_max) {
5122 $longest_path = $_;
5123 last;
5126 $longest_path;
5129 sub gs_fetch_loop_common {
5130 my ($self, $base, $head, $gsv, $globs) = @_;
5131 return if ($base > $head);
5132 my $inc = $_log_window_size;
5133 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5134 my $longest_path = longest_common_path($gsv, $globs);
5135 my $ra_url = $self->{url};
5136 my $find_trailing_edge;
5137 while (1) {
5138 my %revs;
5139 my $err;
5140 my $err_handler = $SVN::Error::handler;
5141 $SVN::Error::handler = sub {
5142 ($err) = @_;
5143 skip_unknown_revs($err);
5145 sub _cb {
5146 my ($paths, $r, $author, $date, $log) = @_;
5147 [ $paths,
5148 { author => $author, date => $date, log => $log } ];
5150 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5151 sub { $revs{$_[1]} = _cb(@_) });
5152 if ($err) {
5153 print "Checked through r$max\r";
5154 } else {
5155 $find_trailing_edge = 1;
5157 if ($err and $find_trailing_edge) {
5158 print STDERR "Path '$longest_path' ",
5159 "was probably deleted:\n",
5160 $err->expanded_message,
5161 "\nWill attempt to follow ",
5162 "revisions r$min .. r$max ",
5163 "committed before the deletion\n";
5164 my $hi = $max;
5165 while (--$hi >= $min) {
5166 my $ok;
5167 $self->get_log([$longest_path], $min, $hi,
5168 0, 1, 1, sub {
5169 $ok = $_[1];
5170 $revs{$_[1]} = _cb(@_) });
5171 if ($ok) {
5172 print STDERR "r$min .. r$ok OK\n";
5173 last;
5176 $find_trailing_edge = 0;
5178 $SVN::Error::handler = $err_handler;
5180 my %exists = map { $_->{path} => $_ } @$gsv;
5181 foreach my $r (sort {$a <=> $b} keys %revs) {
5182 my ($paths, $logged) = @{$revs{$r}};
5184 foreach my $gs ($self->match_globs(\%exists, $paths,
5185 $globs, $r)) {
5186 if ($gs->rev_map_max >= $r) {
5187 next;
5189 next unless $gs->match_paths($paths, $r);
5190 $gs->{logged_rev_props} = $logged;
5191 if (my $last_commit = $gs->last_commit) {
5192 $gs->assert_index_clean($last_commit);
5194 my $log_entry = $gs->do_fetch($paths, $r);
5195 if ($log_entry) {
5196 $gs->do_git_commit($log_entry);
5198 $INDEX_FILES{$gs->{index}} = 1;
5200 foreach my $g (@$globs) {
5201 my $k = "svn-remote.$g->{remote}." .
5202 "$g->{t}-maxRev";
5203 Git::SVN::tmp_config($k, $r);
5205 if ($ra_invalid) {
5206 $_[0] = undef;
5207 $self = undef;
5208 $RA = undef;
5209 $self = Git::SVN::Ra->new($ra_url);
5210 $ra_invalid = undef;
5213 # pre-fill the .rev_db since it'll eventually get filled in
5214 # with '0' x40 if something new gets committed
5215 foreach my $gs (@$gsv) {
5216 next if $gs->rev_map_max >= $max;
5217 next if defined $gs->rev_map_get($max);
5218 $gs->rev_map_set($max, 0 x40);
5220 foreach my $g (@$globs) {
5221 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5222 Git::SVN::tmp_config($k, $max);
5224 last if $max >= $head;
5225 $min = $max + 1;
5226 $max += $inc;
5227 $max = $head if ($max > $head);
5229 Git::SVN::gc();
5232 sub get_dir_globbed {
5233 my ($self, $left, $depth, $r) = @_;
5235 my @x = eval { $self->get_dir($left, $r) };
5236 return unless scalar @x == 3;
5237 my $dirents = $x[0];
5238 my @finalents;
5239 foreach my $de (keys %$dirents) {
5240 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5241 if ($depth > 1) {
5242 my @args = ("$left/$de", $depth - 1, $r);
5243 foreach my $dir ($self->get_dir_globbed(@args)) {
5244 push @finalents, "$de/$dir";
5246 } else {
5247 push @finalents, $de;
5250 @finalents;
5253 sub match_globs {
5254 my ($self, $exists, $paths, $globs, $r) = @_;
5256 sub get_dir_check {
5257 my ($self, $exists, $g, $r) = @_;
5259 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5260 $g->{path}->{depth},
5261 $r);
5263 foreach my $de (@dirs) {
5264 my $p = $g->{path}->full_path($de);
5265 next if $exists->{$p};
5266 next if (length $g->{path}->{right} &&
5267 ($self->check_path($p, $r) !=
5268 $SVN::Node::dir));
5269 next unless $p =~ /$g->{path}->{regex}/;
5270 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5271 $g->{ref}->full_path($de), 1);
5274 foreach my $g (@$globs) {
5275 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5276 if ($path->{action} =~ /^[AR]$/) {
5277 get_dir_check($self, $exists, $g, $r);
5280 foreach (keys %$paths) {
5281 if (/$g->{path}->{left_regex}/ &&
5282 !/$g->{path}->{regex}/) {
5283 next if $paths->{$_}->{action} !~ /^[AR]$/;
5284 get_dir_check($self, $exists, $g, $r);
5286 next unless /$g->{path}->{regex}/;
5287 my $p = $1;
5288 my $pathname = $g->{path}->full_path($p);
5289 next if $exists->{$pathname};
5290 next if ($self->check_path($pathname, $r) !=
5291 $SVN::Node::dir);
5292 $exists->{$pathname} = Git::SVN->init(
5293 $self->{url}, $pathname, undef,
5294 $g->{ref}->full_path($p), 1);
5296 my $c = '';
5297 foreach (split m#/#, $g->{path}->{left}) {
5298 $c .= "/$_";
5299 next unless ($paths->{$c} &&
5300 ($paths->{$c}->{action} =~ /^[AR]$/));
5301 get_dir_check($self, $exists, $g, $r);
5304 values %$exists;
5307 sub minimize_url {
5308 my ($self) = @_;
5309 return $self->{url} if ($self->{url} eq $self->{repos_root});
5310 my $url = $self->{repos_root};
5311 my @components = split(m!/!, $self->{svn_path});
5312 my $c = '';
5313 do {
5314 $url .= "/$c" if length $c;
5315 eval {
5316 my $ra = (ref $self)->new($url);
5317 my $latest = $ra->get_latest_revnum;
5318 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5320 } while ($@ && ($c = shift @components));
5321 $url;
5324 sub can_do_switch {
5325 my $self = shift;
5326 unless (defined $can_do_switch) {
5327 my $pool = SVN::Pool->new;
5328 my $rep = eval {
5329 $self->do_switch(1, '', 0, $self->{url},
5330 SVN::Delta::Editor->new, $pool);
5332 if ($@) {
5333 $can_do_switch = 0;
5334 } else {
5335 $rep->abort_report($pool);
5336 $can_do_switch = 1;
5338 $pool->clear;
5340 $can_do_switch;
5343 sub skip_unknown_revs {
5344 my ($err) = @_;
5345 my $errno = $err->apr_err();
5346 # Maybe the branch we're tracking didn't
5347 # exist when the repo started, so it's
5348 # not an error if it doesn't, just continue
5350 # Wonderfully consistent library, eh?
5351 # 160013 - svn:// and file://
5352 # 175002 - http(s)://
5353 # 175007 - http(s):// (this repo required authorization, too...)
5354 # More codes may be discovered later...
5355 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5356 my $err_key = $err->expanded_message;
5357 # revision numbers change every time, filter them out
5358 $err_key =~ s/\d+/\0/g;
5359 $err_key = "$errno\0$err_key";
5360 unless ($ignored_err{$err_key}) {
5361 warn "W: Ignoring error from SVN, path probably ",
5362 "does not exist: ($errno): ",
5363 $err->expanded_message,"\n";
5364 warn "W: Do not be alarmed at the above message ",
5365 "git-svn is just searching aggressively for ",
5366 "old history.\n",
5367 "This may take a while on large repositories\n";
5368 $ignored_err{$err_key} = 1;
5370 return;
5372 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5375 package Git::SVN::Log;
5376 use strict;
5377 use warnings;
5378 use POSIX qw/strftime/;
5379 use Time::Local;
5380 use constant commit_log_separator => ('-' x 72) . "\n";
5381 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5382 %rusers $show_commit $incremental/;
5383 my $l_fmt;
5385 sub cmt_showable {
5386 my ($c) = @_;
5387 return 1 if defined $c->{r};
5389 # big commit message got truncated by the 16k pretty buffer in rev-list
5390 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5391 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5392 @{$c->{l}} = ();
5393 my @log = command(qw/cat-file commit/, $c->{c});
5395 # shift off the headers
5396 shift @log while ($log[0] ne '');
5397 shift @log;
5399 # TODO: make $c->{l} not have a trailing newline in the future
5400 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5402 (undef, $c->{r}, undef) = ::extract_metadata(
5403 (grep(/^git-svn-id: /, @log))[-1]);
5405 return defined $c->{r};
5408 sub log_use_color {
5409 return $color || Git->repository->get_colorbool('color.diff');
5412 sub git_svn_log_cmd {
5413 my ($r_min, $r_max, @args) = @_;
5414 my $head = 'HEAD';
5415 my (@files, @log_opts);
5416 foreach my $x (@args) {
5417 if ($x eq '--' || @files) {
5418 push @files, $x;
5419 } else {
5420 if (::verify_ref("$x^0")) {
5421 $head = $x;
5422 } else {
5423 push @log_opts, $x;
5428 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5429 $gs ||= Git::SVN->_new;
5430 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5431 $gs->refname);
5432 push @cmd, '-r' unless $non_recursive;
5433 push @cmd, qw/--raw --name-status/ if $verbose;
5434 push @cmd, '--color' if log_use_color();
5435 push @cmd, @log_opts;
5436 if (defined $r_max && $r_max == $r_min) {
5437 push @cmd, '--max-count=1';
5438 if (my $c = $gs->rev_map_get($r_max)) {
5439 push @cmd, $c;
5441 } elsif (defined $r_max) {
5442 if ($r_max < $r_min) {
5443 ($r_min, $r_max) = ($r_max, $r_min);
5445 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5446 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5447 # If there are no commits in the range, both $c_max and $c_min
5448 # will be undefined. If there is at least 1 commit in the
5449 # range, both will be defined.
5450 return () if !defined $c_min || !defined $c_max;
5451 if ($c_min eq $c_max) {
5452 push @cmd, '--max-count=1', $c_min;
5453 } else {
5454 push @cmd, '--boundary', "$c_min..$c_max";
5457 return (@cmd, @files);
5460 # adapted from pager.c
5461 sub config_pager {
5462 chomp(my $pager = command_oneline(qw(var GIT_PAGER)));
5463 if ($pager eq 'cat') {
5464 $pager = undef;
5466 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5469 sub run_pager {
5470 return unless -t *STDOUT && defined $pager;
5471 pipe my ($rfd, $wfd) or return;
5472 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5473 if (!$pid) {
5474 open STDOUT, '>&', $wfd or
5475 ::fatal "Can't redirect to stdout: $!";
5476 return;
5478 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5479 $ENV{LESS} ||= 'FRSX';
5480 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5483 sub format_svn_date {
5484 # some systmes don't handle or mishandle %z, so be creative.
5485 my $t = shift || time;
5486 my $gm = timelocal(gmtime($t));
5487 my $sign = qw( + + - )[ $t <=> $gm ];
5488 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5489 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5492 sub parse_git_date {
5493 my ($t, $tz) = @_;
5494 # Date::Parse isn't in the standard Perl distro :(
5495 if ($tz =~ s/^\+//) {
5496 $t += tz_to_s_offset($tz);
5497 } elsif ($tz =~ s/^\-//) {
5498 $t -= tz_to_s_offset($tz);
5500 return $t;
5503 sub set_local_timezone {
5504 if (defined $TZ) {
5505 $ENV{TZ} = $TZ;
5506 } else {
5507 delete $ENV{TZ};
5511 sub tz_to_s_offset {
5512 my ($tz) = @_;
5513 $tz =~ s/(\d\d)$//;
5514 return ($1 * 60) + ($tz * 3600);
5517 sub get_author_info {
5518 my ($dest, $author, $t, $tz) = @_;
5519 $author =~ s/(?:^\s*|\s*$)//g;
5520 $dest->{a_raw} = $author;
5521 my $au;
5522 if ($::_authors) {
5523 $au = $rusers{$author} || undef;
5525 if (!$au) {
5526 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5528 $dest->{t} = $t;
5529 $dest->{tz} = $tz;
5530 $dest->{a} = $au;
5531 $dest->{t_utc} = parse_git_date($t, $tz);
5534 sub process_commit {
5535 my ($c, $r_min, $r_max, $defer) = @_;
5536 if (defined $r_min && defined $r_max) {
5537 if ($r_min == $c->{r} && $r_min == $r_max) {
5538 show_commit($c);
5539 return 0;
5541 return 1 if $r_min == $r_max;
5542 if ($r_min < $r_max) {
5543 # we need to reverse the print order
5544 return 0 if (defined $limit && --$limit < 0);
5545 push @$defer, $c;
5546 return 1;
5548 if ($r_min != $r_max) {
5549 return 1 if ($r_min < $c->{r});
5550 return 1 if ($r_max > $c->{r});
5553 return 0 if (defined $limit && --$limit < 0);
5554 show_commit($c);
5555 return 1;
5558 sub show_commit {
5559 my $c = shift;
5560 if ($oneline) {
5561 my $x = "\n";
5562 if (my $l = $c->{l}) {
5563 while ($l->[0] =~ /^\s*$/) { shift @$l }
5564 $x = $l->[0];
5566 $l_fmt ||= 'A' . length($c->{r});
5567 print 'r',pack($l_fmt, $c->{r}),' | ';
5568 print "$c->{c} | " if $show_commit;
5569 print $x;
5570 } else {
5571 show_commit_normal($c);
5575 sub show_commit_changed_paths {
5576 my ($c) = @_;
5577 return unless $c->{changed};
5578 print "Changed paths:\n", @{$c->{changed}};
5581 sub show_commit_normal {
5582 my ($c) = @_;
5583 print commit_log_separator, "r$c->{r} | ";
5584 print "$c->{c} | " if $show_commit;
5585 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5586 my $nr_line = 0;
5588 if (my $l = $c->{l}) {
5589 while ($l->[$#$l] eq "\n" && $#$l > 0
5590 && $l->[($#$l - 1)] eq "\n") {
5591 pop @$l;
5593 $nr_line = scalar @$l;
5594 if (!$nr_line) {
5595 print "1 line\n\n\n";
5596 } else {
5597 if ($nr_line == 1) {
5598 $nr_line = '1 line';
5599 } else {
5600 $nr_line .= ' lines';
5602 print $nr_line, "\n";
5603 show_commit_changed_paths($c);
5604 print "\n";
5605 print $_ foreach @$l;
5607 } else {
5608 print "1 line\n";
5609 show_commit_changed_paths($c);
5610 print "\n";
5613 foreach my $x (qw/raw stat diff/) {
5614 if ($c->{$x}) {
5615 print "\n";
5616 print $_ foreach @{$c->{$x}}
5621 sub cmd_show_log {
5622 my (@args) = @_;
5623 my ($r_min, $r_max);
5624 my $r_last = -1; # prevent dupes
5625 set_local_timezone();
5626 if (defined $::_revision) {
5627 if ($::_revision =~ /^(\d+):(\d+)$/) {
5628 ($r_min, $r_max) = ($1, $2);
5629 } elsif ($::_revision =~ /^\d+$/) {
5630 $r_min = $r_max = $::_revision;
5631 } else {
5632 ::fatal "-r$::_revision is not supported, use ",
5633 "standard 'git log' arguments instead";
5637 config_pager();
5638 @args = git_svn_log_cmd($r_min, $r_max, @args);
5639 if (!@args) {
5640 print commit_log_separator unless $incremental || $oneline;
5641 return;
5643 my $log = command_output_pipe(@args);
5644 run_pager();
5645 my (@k, $c, $d, $stat);
5646 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5647 while (<$log>) {
5648 if (/^${esc_color}commit -?($::sha1_short)/o) {
5649 my $cmt = $1;
5650 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5651 $r_last = $c->{r};
5652 process_commit($c, $r_min, $r_max, \@k) or
5653 goto out;
5655 $d = undef;
5656 $c = { c => $cmt };
5657 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5658 get_author_info($c, $1, $2, $3);
5659 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5660 # ignore
5661 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5662 push @{$c->{raw}}, $_;
5663 } elsif (/^${esc_color}[ACRMDT]\t/) {
5664 # we could add $SVN->{svn_path} here, but that requires
5665 # remote access at the moment (repo_path_split)...
5666 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5667 push @{$c->{changed}}, $_;
5668 } elsif (/^${esc_color}diff /o) {
5669 $d = 1;
5670 push @{$c->{diff}}, $_;
5671 } elsif ($d) {
5672 push @{$c->{diff}}, $_;
5673 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5674 $esc_color*[\+\-]*$esc_color$/x) {
5675 $stat = 1;
5676 push @{$c->{stat}}, $_;
5677 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5678 push @{$c->{stat}}, $_;
5679 $stat = undef;
5680 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5681 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5682 } elsif (s/^${esc_color} //o) {
5683 push @{$c->{l}}, $_;
5686 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5687 $r_last = $c->{r};
5688 process_commit($c, $r_min, $r_max, \@k);
5690 if (@k) {
5691 ($r_min, $r_max) = ($r_max, $r_min);
5692 process_commit($_, $r_min, $r_max) foreach reverse @k;
5694 out:
5695 close $log;
5696 print commit_log_separator unless $incremental || $oneline;
5699 sub cmd_blame {
5700 my $path = pop;
5702 config_pager();
5703 run_pager();
5705 my ($fh, $ctx, $rev);
5707 if ($_git_format) {
5708 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5709 while (my $line = <$fh>) {
5710 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5711 # Uncommitted edits show up as a rev ID of
5712 # all zeros, which we can't look up with
5713 # cmt_metadata
5714 if ($1 !~ /^0+$/) {
5715 (undef, $rev, undef) =
5716 ::cmt_metadata($1);
5717 $rev = '0' if (!$rev);
5718 } else {
5719 $rev = '0';
5721 $rev = sprintf('%-10s', $rev);
5722 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5724 print $line;
5726 } else {
5727 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5728 '--', $path);
5729 my ($sha1);
5730 my %authors;
5731 my @buffer;
5732 my %dsha; #distinct sha keys
5734 while (my $line = <$fh>) {
5735 push @buffer, $line;
5736 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5737 $dsha{$1} = 1;
5741 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5743 foreach my $line (@buffer) {
5744 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5745 $rev = $s2r->{$1};
5746 $rev = '0' if (!$rev)
5748 elsif ($line =~ /^author (.*)/) {
5749 $authors{$rev} = $1;
5750 $authors{$rev} =~ s/\s/_/g;
5752 elsif ($line =~ /^\t(.*)$/) {
5753 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5757 command_close_pipe($fh, $ctx);
5760 package Git::SVN::Migration;
5761 # these version numbers do NOT correspond to actual version numbers
5762 # of git nor git-svn. They are just relative.
5764 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5766 # v1 layout: .git/$id/info/url, refs/remotes/$id
5768 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5770 # v3 layout: .git/svn/$id, refs/remotes/$id
5771 # - info/url may remain for backwards compatibility
5772 # - this is what we migrate up to this layout automatically,
5773 # - this will be used by git svn init on single branches
5774 # v3.1 layout (auto migrated):
5775 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5776 # for backwards compatibility
5778 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5779 # - this is only created for newly multi-init-ed
5780 # repositories. Similar in spirit to the
5781 # --use-separate-remotes option in git-clone (now default)
5782 # - we do not automatically migrate to this (following
5783 # the example set by core git)
5785 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5786 # - newer, more-efficient format that uses 24-bytes per record
5787 # with no filler space.
5788 # - use xxd -c24 < .rev_map.$UUID to view and debug
5789 # - This is a one-way migration, repositories updated to the
5790 # new format will not be able to use old git-svn without
5791 # rebuilding the .rev_db. Rebuilding the rev_db is not
5792 # possible if noMetadata or useSvmProps are set; but should
5793 # be no problem for users that use the (sensible) defaults.
5794 use strict;
5795 use warnings;
5796 use Carp qw/croak/;
5797 use File::Path qw/mkpath/;
5798 use File::Basename qw/dirname basename/;
5799 use vars qw/$_minimize/;
5801 sub migrate_from_v0 {
5802 my $git_dir = $ENV{GIT_DIR};
5803 return undef unless -d $git_dir;
5804 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5805 my $migrated = 0;
5806 while (<$fh>) {
5807 chomp;
5808 my ($id, $orig_ref) = ($_, $_);
5809 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5810 next unless -f "$git_dir/$id/info/url";
5811 my $new_ref = "refs/remotes/$id";
5812 if (::verify_ref("$new_ref^0")) {
5813 print STDERR "W: $orig_ref is probably an old ",
5814 "branch used by an ancient version of ",
5815 "git-svn.\n",
5816 "However, $new_ref also exists.\n",
5817 "We will not be able ",
5818 "to use this branch until this ",
5819 "ambiguity is resolved.\n";
5820 next;
5822 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5823 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5824 command_noisy('update-ref', $new_ref, $orig_ref);
5825 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5826 $migrated++;
5828 command_close_pipe($fh, $ctx);
5829 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5830 $migrated;
5833 sub migrate_from_v1 {
5834 my $git_dir = $ENV{GIT_DIR};
5835 my $migrated = 0;
5836 return $migrated unless -d $git_dir;
5837 my $svn_dir = "$git_dir/svn";
5839 # just in case somebody used 'svn' as their $id at some point...
5840 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5842 print STDERR "Migrating from a git-svn v1 layout...\n";
5843 mkpath([$svn_dir]);
5844 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5845 "$svn_dir\n\t(required for this version ",
5846 "($::VERSION) of git-svn) does not exist.\n";
5847 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5848 while (<$fh>) {
5849 my $x = $_;
5850 next unless $x =~ s#^refs/remotes/##;
5851 chomp $x;
5852 next unless -f "$git_dir/$x/info/url";
5853 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5854 next unless $u;
5855 my $dn = dirname("$git_dir/svn/$x");
5856 mkpath([$dn]) unless -d $dn;
5857 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5858 mkpath(["$git_dir/svn/svn"]);
5859 print STDERR " - $git_dir/$x/info => ",
5860 "$git_dir/svn/$x/info\n";
5861 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5862 croak "$!: $x";
5863 # don't worry too much about these, they probably
5864 # don't exist with repos this old (save for index,
5865 # and we can easily regenerate that)
5866 foreach my $f (qw/unhandled.log index .rev_db/) {
5867 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5869 } else {
5870 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5871 rename "$git_dir/$x", "$git_dir/svn/$x" or
5872 croak "$!: $x";
5874 $migrated++;
5876 command_close_pipe($fh, $ctx);
5877 print STDERR "Done migrating from a git-svn v1 layout\n";
5878 $migrated;
5881 sub read_old_urls {
5882 my ($l_map, $pfx, $path) = @_;
5883 my @dir;
5884 foreach (<$path/*>) {
5885 if (-r "$_/info/url") {
5886 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5887 my $ref_id = $pfx . basename $_;
5888 my $url = ::file_to_s("$_/info/url");
5889 $l_map->{$ref_id} = $url;
5890 } elsif (-d $_) {
5891 push @dir, $_;
5894 foreach (@dir) {
5895 my $x = $_;
5896 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5897 read_old_urls($l_map, $x, $_);
5901 sub migrate_from_v2 {
5902 my @cfg = command(qw/config -l/);
5903 return if grep /^svn-remote\..+\.url=/, @cfg;
5904 my %l_map;
5905 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5906 my $migrated = 0;
5908 foreach my $ref_id (sort keys %l_map) {
5909 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5910 if ($@) {
5911 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5913 $migrated++;
5915 $migrated;
5918 sub minimize_connections {
5919 my $r = Git::SVN::read_all_remotes();
5920 my $new_urls = {};
5921 my $root_repos = {};
5922 foreach my $repo_id (keys %$r) {
5923 my $url = $r->{$repo_id}->{url} or next;
5924 my $fetch = $r->{$repo_id}->{fetch} or next;
5925 my $ra = Git::SVN::Ra->new($url);
5927 # skip existing cases where we already connect to the root
5928 if (($ra->{url} eq $ra->{repos_root}) ||
5929 ($ra->{repos_root} eq $repo_id)) {
5930 $root_repos->{$ra->{url}} = $repo_id;
5931 next;
5934 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5935 my $root_path = $ra->{url};
5936 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5937 foreach my $path (keys %$fetch) {
5938 my $ref_id = $fetch->{$path};
5939 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5941 # make sure we can read when connecting to
5942 # a higher level of a repository
5943 my ($last_rev, undef) = $gs->last_rev_commit;
5944 if (!defined $last_rev) {
5945 $last_rev = eval {
5946 $root_ra->get_latest_revnum;
5948 next if $@;
5950 my $new = $root_path;
5951 $new .= length $path ? "/$path" : '';
5952 eval {
5953 $root_ra->get_log([$new], $last_rev, $last_rev,
5954 0, 0, 1, sub { });
5956 next if $@;
5957 $new_urls->{$ra->{repos_root}}->{$new} =
5958 { ref_id => $ref_id,
5959 old_repo_id => $repo_id,
5960 old_path => $path };
5964 my @emptied;
5965 foreach my $url (keys %$new_urls) {
5966 # see if we can re-use an existing [svn-remote "repo_id"]
5967 # instead of creating a(n ugly) new section:
5968 my $repo_id = $root_repos->{$url} || $url;
5970 my $fetch = $new_urls->{$url};
5971 foreach my $path (keys %$fetch) {
5972 my $x = $fetch->{$path};
5973 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5974 my $pfx = "svn-remote.$x->{old_repo_id}";
5976 my $old_fetch = quotemeta("$x->{old_path}:".
5977 "$x->{ref_id}");
5978 command_noisy(qw/config --unset/,
5979 "$pfx.fetch", '^'. $old_fetch . '$');
5980 delete $r->{$x->{old_repo_id}}->
5981 {fetch}->{$x->{old_path}};
5982 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5983 command_noisy(qw/config --unset/,
5984 "$pfx.url");
5985 push @emptied, $x->{old_repo_id}
5989 if (@emptied) {
5990 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5991 print STDERR <<EOF;
5992 The following [svn-remote] sections in your config file ($file) are empty
5993 and can be safely removed:
5995 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5999 sub migration_check {
6000 migrate_from_v0();
6001 migrate_from_v1();
6002 migrate_from_v2();
6003 minimize_connections() if $_minimize;
6006 package Git::IndexInfo;
6007 use strict;
6008 use warnings;
6009 use Git qw/command_input_pipe command_close_pipe/;
6011 sub new {
6012 my ($class) = @_;
6013 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6014 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6017 sub remove {
6018 my ($self, $path) = @_;
6019 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6020 return ++$self->{nr};
6022 undef;
6025 sub update {
6026 my ($self, $mode, $hash, $path) = @_;
6027 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6028 return ++$self->{nr};
6030 undef;
6033 sub DESTROY {
6034 my ($self) = @_;
6035 command_close_pipe($self->{gui}, $self->{ctx});
6038 package Git::SVN::GlobSpec;
6039 use strict;
6040 use warnings;
6042 sub new {
6043 my ($class, $glob, $pattern_ok) = @_;
6044 my $re = $glob;
6045 $re =~ s!/+$!!g; # no need for trailing slashes
6046 my (@left, @right, @patterns);
6047 my $state = "left";
6048 my $die_msg = "Only one set of wildcard directories " .
6049 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6050 for my $part (split(m|/|, $glob)) {
6051 if ($part =~ /\*/ && $part ne "*") {
6052 die "Invalid pattern in '$glob': $part\n";
6053 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6054 $part !~ /^\{[^{}]+\}/) {
6055 die "Invalid pattern in '$glob': $part\n";
6057 if ($part eq "*") {
6058 die $die_msg if $state eq "right";
6059 $state = "pattern";
6060 push(@patterns, "[^/]*");
6061 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6062 die $die_msg if $state eq "right";
6063 $state = "pattern";
6064 my $p = quotemeta($1);
6065 $p =~ s/\\,/|/g;
6066 push(@patterns, "(?:$p)");
6067 } else {
6068 if ($state eq "left") {
6069 push(@left, $part);
6070 } else {
6071 push(@right, $part);
6072 $state = "right";
6076 my $depth = @patterns;
6077 if ($depth == 0) {
6078 die "One '*' is needed in glob: '$glob'\n";
6080 my $left = join('/', @left);
6081 my $right = join('/', @right);
6082 $re = join('/', @patterns);
6083 $re = join('\/',
6084 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6085 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6086 bless { left => $left, right => $right, left_regex => $left_re,
6087 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6090 sub full_path {
6091 my ($self, $path) = @_;
6092 return (length $self->{left} ? "$self->{left}/" : '') .
6093 $path . (length $self->{right} ? "/$self->{right}" : '');
6096 __END__
6098 Data structures:
6101 $remotes = { # returned by read_all_remotes()
6102 'svn' => {
6103 # svn-remote.svn.url=https://svn.musicpd.org
6104 url => 'https://svn.musicpd.org',
6105 # svn-remote.svn.fetch=mpd/trunk:trunk
6106 fetch => {
6107 'mpd/trunk' => 'trunk',
6109 # svn-remote.svn.tags=mpd/tags/*:tags/*
6110 tags => {
6111 path => {
6112 left => 'mpd/tags',
6113 right => '',
6114 regex => qr!mpd/tags/([^/]+)$!,
6115 glob => 'tags/*',
6117 ref => {
6118 left => 'tags',
6119 right => '',
6120 regex => qr!tags/([^/]+)$!,
6121 glob => 'tags/*',
6127 $log_entry hashref as returned by libsvn_log_entry()
6129 log => 'whitespace-formatted log entry
6130 ', # trailing newline is preserved
6131 revision => '8', # integer
6132 date => '2004-02-24T17:01:44.108345Z', # commit date
6133 author => 'committer name'
6137 # this is generated by generate_diff();
6138 @mods = array of diff-index line hashes, each element represents one line
6139 of diff-index output
6141 diff-index line ($m hash)
6143 mode_a => first column of diff-index output, no leading ':',
6144 mode_b => second column of diff-index output,
6145 sha1_b => sha1sum of the final blob,
6146 chg => change type [MCRADT],
6147 file_a => original file name of a file (iff chg is 'C' or 'R')
6148 file_b => new/current file name of a file (any chg)
6152 # retval of read_url_paths{,_all}();
6153 $l_map = {
6154 # repository root url
6155 'https://svn.musicpd.org' => {
6156 # repository path # GIT_SVN_ID
6157 'mpd/trunk' => 'trunk',
6158 'mpd/tags/0.11.5' => 'tags/0.11.5',
6162 Notes:
6163 I don't trust the each() function on unless I created %hash myself
6164 because the internal iterator may not have started at base.