Make the MSVC projects use PDB/IDB files named after the project
[git/dscho.git] / git-svn.perl
blobeb4b75aff347670b1817fb1c2584cff11a08fad5
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;
33 $Git::SVN::Log::TZ = $ENV{TZ};
34 $ENV{TZ} = 'UTC';
35 $| = 1; # unbuffer STDOUT
37 sub fatal (@) { print STDERR "@_\n"; exit 1 }
38 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
39 require SVN::Ra;
40 require SVN::Delta;
41 if ($SVN::Core::VERSION lt '1.1.0') {
42 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
44 my $can_compress = eval { require Compress::Zlib; 1};
45 push @Git::SVN::Ra::ISA, 'SVN::Ra';
46 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
47 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
48 use Carp qw/croak/;
49 use Digest::MD5;
50 use IO::File qw//;
51 use File::Basename qw/dirname basename/;
52 use File::Path qw/mkpath/;
53 use File::Spec;
54 use File::Find;
55 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
56 use IPC::Open3;
57 use Git;
59 BEGIN {
60 # import functions from Git into our packages, en masse
61 no strict 'refs';
62 foreach (qw/command command_oneline command_noisy command_output_pipe
63 command_input_pipe command_close_pipe
64 command_bidi_pipe command_close_bidi_pipe/) {
65 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
66 Git::SVN::Migration Git::SVN::Log Git::SVN),
67 __PACKAGE__) {
68 *{"${package}::$_"} = \&{"Git::$_"};
73 my ($SVN);
75 $sha1 = qr/[a-f\d]{40}/;
76 $sha1_short = qr/[a-f\d]{4,40}/;
77 my ($_stdin, $_help, $_edit,
78 $_message, $_file, $_branch_dest,
79 $_template, $_shared,
80 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
81 $_merge, $_strategy, $_dry_run, $_local,
82 $_prefix, $_no_checkout, $_url, $_verbose,
83 $_git_format, $_commit_url, $_tag);
84 $Git::SVN::_follow_parent = 1;
85 $_q ||= 0;
86 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
87 'config-dir=s' => \$Git::SVN::Ra::config_dir,
88 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
89 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
90 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
91 'authors-file|A=s' => \$_authors,
92 'authors-prog=s' => \$_authors_prog,
93 'repack:i' => \$Git::SVN::_repack,
94 'noMetadata' => \$Git::SVN::_no_metadata,
95 'useSvmProps' => \$Git::SVN::_use_svm_props,
96 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
97 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
98 'no-checkout' => \$_no_checkout,
99 'quiet|q+' => \$_q,
100 'repack-flags|repack-args|repack-opts=s' =>
101 \$Git::SVN::_repack_flags,
102 'use-log-author' => \$Git::SVN::_use_log_author,
103 'add-author-from' => \$Git::SVN::_add_author_from,
104 'localtime' => \$Git::SVN::_localtime,
105 %remote_opts );
107 my ($_trunk, @_tags, @_branches, $_stdlayout);
108 my %icv;
109 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
110 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
111 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
112 'stdlayout|s' => \$_stdlayout,
113 'minimize-url|m!' => \$Git::SVN::_minimize_url,
114 'no-metadata' => sub { $icv{noMetadata} = 1 },
115 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
116 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
117 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
118 %remote_opts );
119 my %cmt_opts = ( 'edit|e' => \$_edit,
120 'rmdir' => \$SVN::Git::Editor::_rmdir,
121 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
122 'l=i' => \$SVN::Git::Editor::_rename_limit,
123 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
126 my %cmd = (
127 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
128 { 'revision|r=s' => \$_revision,
129 'fetch-all|all' => \$_fetch_all,
130 'parent|p' => \$_fetch_parent,
131 %fc_opts } ],
132 clone => [ \&cmd_clone, "Initialize and fetch revisions",
133 { 'revision|r=s' => \$_revision,
134 %fc_opts, %init_opts } ],
135 init => [ \&cmd_init, "Initialize a repo for tracking" .
136 " (requires URL argument)",
137 \%init_opts ],
138 'multi-init' => [ \&cmd_multi_init,
139 "Deprecated alias for ".
140 "'$0 init -T<trunk> -b<branches> -t<tags>'",
141 \%init_opts ],
142 dcommit => [ \&cmd_dcommit,
143 'Commit several diffs to merge with upstream',
144 { 'merge|m|M' => \$_merge,
145 'strategy|s=s' => \$_strategy,
146 'verbose|v' => \$_verbose,
147 'dry-run|n' => \$_dry_run,
148 'fetch-all|all' => \$_fetch_all,
149 'commit-url=s' => \$_commit_url,
150 'revision|r=i' => \$_revision,
151 'no-rebase' => \$_no_rebase,
152 %cmt_opts, %fc_opts } ],
153 branch => [ \&cmd_branch,
154 'Create a branch in the SVN repository',
155 { 'message|m=s' => \$_message,
156 'destination|d=s' => \$_branch_dest,
157 'dry-run|n' => \$_dry_run,
158 'tag|t' => \$_tag } ],
159 tag => [ sub { $_tag = 1; cmd_branch(@_) },
160 'Create a tag in the SVN repository',
161 { 'message|m=s' => \$_message,
162 'destination|d=s' => \$_branch_dest,
163 'dry-run|n' => \$_dry_run } ],
164 'set-tree' => [ \&cmd_set_tree,
165 "Set an SVN repository to a git tree-ish",
166 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
167 'create-ignore' => [ \&cmd_create_ignore,
168 'Create a .gitignore per svn:ignore',
169 { 'revision|r=i' => \$_revision
170 } ],
171 'propget' => [ \&cmd_propget,
172 'Print the value of a property on a file or directory',
173 { 'revision|r=i' => \$_revision } ],
174 'proplist' => [ \&cmd_proplist,
175 'List all properties of a file or directory',
176 { 'revision|r=i' => \$_revision } ],
177 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
178 { 'revision|r=i' => \$_revision
179 } ],
180 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
181 { 'revision|r=i' => \$_revision
182 } ],
183 'multi-fetch' => [ \&cmd_multi_fetch,
184 "Deprecated alias for $0 fetch --all",
185 { 'revision|r=s' => \$_revision, %fc_opts } ],
186 'migrate' => [ sub { },
187 # no-op, we automatically run this anyways,
188 'Migrate configuration/metadata/layout from
189 previous versions of git-svn',
190 { 'minimize' => \$Git::SVN::Migration::_minimize,
191 %remote_opts } ],
192 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
193 { 'limit=i' => \$Git::SVN::Log::limit,
194 'revision|r=s' => \$_revision,
195 'verbose|v' => \$Git::SVN::Log::verbose,
196 'incremental' => \$Git::SVN::Log::incremental,
197 'oneline' => \$Git::SVN::Log::oneline,
198 'show-commit' => \$Git::SVN::Log::show_commit,
199 'non-recursive' => \$Git::SVN::Log::non_recursive,
200 'authors-file|A=s' => \$_authors,
201 'color' => \$Git::SVN::Log::color,
202 'pager=s' => \$Git::SVN::Log::pager
203 } ],
204 'find-rev' => [ \&cmd_find_rev,
205 "Translate between SVN revision numbers and tree-ish",
206 {} ],
207 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
208 { 'merge|m|M' => \$_merge,
209 'verbose|v' => \$_verbose,
210 'strategy|s=s' => \$_strategy,
211 'local|l' => \$_local,
212 'fetch-all|all' => \$_fetch_all,
213 'dry-run|n' => \$_dry_run,
214 %fc_opts } ],
215 'commit-diff' => [ \&cmd_commit_diff,
216 'Commit a diff between two trees',
217 { 'message|m=s' => \$_message,
218 'file|F=s' => \$_file,
219 'revision|r=s' => \$_revision,
220 %cmt_opts } ],
221 'info' => [ \&cmd_info,
222 "Show info about the latest SVN revision
223 on the current branch",
224 { 'url' => \$_url, } ],
225 'blame' => [ \&Git::SVN::Log::cmd_blame,
226 "Show what revision and author last modified each line of a file",
227 { 'git-format' => \$_git_format } ],
228 'reset' => [ \&cmd_reset,
229 "Undo fetches back to the specified SVN revision",
230 { 'revision|r=s' => \$_revision,
231 'parent|p' => \$_fetch_parent } ],
232 'gc' => [ \&cmd_gc,
233 "Compress unhandled.log files in .git/svn and remove " .
234 "index files in .git/svn",
235 {} ],
238 my $cmd;
239 for (my $i = 0; $i < @ARGV; $i++) {
240 if (defined $cmd{$ARGV[$i]}) {
241 $cmd = $ARGV[$i];
242 splice @ARGV, $i, 1;
243 last;
244 } elsif ($ARGV[$i] eq 'help') {
245 $cmd = $ARGV[$i+1];
246 usage(0);
250 # make sure we're always running at the top-level working directory
251 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
252 unless (-d $ENV{GIT_DIR}) {
253 if ($git_dir_user_set) {
254 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
255 "but it is not a directory\n";
257 my $git_dir = delete $ENV{GIT_DIR};
258 my $cdup = undef;
259 git_cmd_try {
260 $cdup = command_oneline(qw/rev-parse --show-cdup/);
261 $git_dir = '.' unless ($cdup);
262 chomp $cdup if ($cdup);
263 $cdup = "." unless ($cdup && length $cdup);
264 } "Already at toplevel, but $git_dir not found\n";
265 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
266 unless (-d $git_dir) {
267 die "$git_dir still not found after going to ",
268 "'$cdup'\n";
270 $ENV{GIT_DIR} = $git_dir;
272 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
275 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
277 read_repo_config(\%opts);
278 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
279 Getopt::Long::Configure('pass_through');
281 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
282 'minimize-connections' => \$Git::SVN::Migration::_minimize,
283 'id|i=s' => \$Git::SVN::default_ref_id,
284 'svn-remote|remote|R=s' => sub {
285 $Git::SVN::no_reuse_existing = 1;
286 $Git::SVN::default_repo_id = $_[1] });
287 exit 1 if (!$rv && $cmd && $cmd ne 'log');
289 usage(0) if $_help;
290 version() if $_version;
291 usage(1) unless defined $cmd;
292 load_authors() if $_authors;
293 if (defined $_authors_prog) {
294 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
297 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
298 Git::SVN::Migration::migration_check();
300 Git::SVN::init_vars();
301 eval {
302 Git::SVN::verify_remotes_sanity();
303 $cmd{$cmd}->[0]->(@ARGV);
305 fatal $@ if $@;
306 post_fetch_checkout();
307 exit 0;
309 ####################### primary functions ######################
310 sub usage {
311 my $exit = shift || 0;
312 my $fd = $exit ? \*STDERR : \*STDOUT;
313 print $fd <<"";
314 git-svn - bidirectional operations between a single Subversion tree and git
315 Usage: git svn <command> [options] [arguments]\n
317 print $fd "Available commands:\n" unless $cmd;
319 foreach (sort keys %cmd) {
320 next if $cmd && $cmd ne $_;
321 next if /^multi-/; # don't show deprecated commands
322 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
323 foreach (sort keys %{$cmd{$_}->[2]}) {
324 # mixed-case options are for .git/config only
325 next if /[A-Z]/ && /^[a-z]+$/i;
326 # prints out arguments as they should be passed:
327 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
328 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
329 "--$_" : "-$_" }
330 split /\|/,$_)," $x\n";
333 print $fd <<"";
334 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
335 arbitrary identifier if you're tracking multiple SVN branches/repositories in
336 one git repository and want to keep them separate. See git-svn(1) for more
337 information.
339 exit $exit;
342 sub version {
343 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
344 exit 0;
347 sub do_git_init_db {
348 unless (-d $ENV{GIT_DIR}) {
349 my @init_db = ('init');
350 push @init_db, "--template=$_template" if defined $_template;
351 if (defined $_shared) {
352 if ($_shared =~ /[a-z]/) {
353 push @init_db, "--shared=$_shared";
354 } else {
355 push @init_db, "--shared";
358 command_noisy(@init_db);
359 $_repository = Git->repository(Repository => ".git");
361 command_noisy('config', 'core.autocrlf', 'false');
362 my $set;
363 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
364 foreach my $i (keys %icv) {
365 die "'$set' and '$i' cannot both be set\n" if $set;
366 next unless defined $icv{$i};
367 command_noisy('config', "$pfx.$i", $icv{$i});
368 $set = $i;
370 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
371 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
372 if defined $$ignore_regex;
375 sub init_subdir {
376 my $repo_path = shift or return;
377 mkpath([$repo_path]) unless -d $repo_path;
378 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
379 $ENV{GIT_DIR} = '.git';
380 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
383 sub cmd_clone {
384 my ($url, $path) = @_;
385 if (!defined $path &&
386 (defined $_trunk || @_branches || @_tags ||
387 defined $_stdlayout) &&
388 $url !~ m#^[a-z\+]+://#) {
389 $path = $url;
391 $path = basename($url) if !defined $path || !length $path;
392 cmd_init($url, $path);
393 Git::SVN::fetch_all($Git::SVN::default_repo_id);
394 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
397 sub cmd_init {
398 if (defined $_stdlayout) {
399 $_trunk = 'trunk' if (!defined $_trunk);
400 @_tags = 'tags' if (! @_tags);
401 @_branches = 'branches' if (! @_branches);
403 if (defined $_trunk || @_branches || @_tags) {
404 return cmd_multi_init(@_);
406 my $url = shift or die "SVN repository location required ",
407 "as a command-line argument\n";
408 $url = canonicalize_url($url);
409 init_subdir(@_);
410 do_git_init_db();
412 if ($Git::SVN::_minimize_url eq 'unset') {
413 $Git::SVN::_minimize_url = 0;
416 Git::SVN->init($url);
419 sub cmd_fetch {
420 if (grep /^\d+=./, @_) {
421 die "'<rev>=<commit>' fetch arguments are ",
422 "no longer supported.\n";
424 my ($remote) = @_;
425 if (@_ > 1) {
426 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
428 if ($_fetch_parent) {
429 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
430 unless ($gs) {
431 die "Unable to determine upstream SVN information from ",
432 "working tree history\n";
434 # just fetch, don't checkout.
435 $_no_checkout = 'true';
436 $_fetch_all ? $gs->fetch_all : $gs->fetch;
437 } elsif ($_fetch_all) {
438 cmd_multi_fetch();
439 } else {
440 $remote ||= $Git::SVN::default_repo_id;
441 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
445 sub cmd_set_tree {
446 my (@commits) = @_;
447 if ($_stdin || !@commits) {
448 print "Reading from stdin...\n";
449 @commits = ();
450 while (<STDIN>) {
451 if (/\b($sha1_short)\b/o) {
452 unshift @commits, $1;
456 my @revs;
457 foreach my $c (@commits) {
458 my @tmp = command('rev-parse',$c);
459 if (scalar @tmp == 1) {
460 push @revs, $tmp[0];
461 } elsif (scalar @tmp > 1) {
462 push @revs, reverse(command('rev-list',@tmp));
463 } else {
464 fatal "Failed to rev-parse $c";
467 my $gs = Git::SVN->new;
468 my ($r_last, $cmt_last) = $gs->last_rev_commit;
469 $gs->fetch;
470 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
471 fatal "There are new revisions that were fetched ",
472 "and need to be merged (or acknowledged) ",
473 "before committing.\nlast rev: $r_last\n",
474 " current: $gs->{last_rev}";
476 $gs->set_tree($_) foreach @revs;
477 print "Done committing ",scalar @revs," revisions to SVN\n";
478 unlink $gs->{index};
481 sub cmd_dcommit {
482 my $head = shift;
483 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
484 'Cannot dcommit with a dirty index. Commit your changes first, '
485 . "or stash them with `git stash'.\n";
486 $head ||= 'HEAD';
488 my $old_head;
489 if ($head ne 'HEAD') {
490 $old_head = eval {
491 command_oneline([qw/symbolic-ref -q HEAD/])
493 if ($old_head) {
494 $old_head =~ s{^refs/heads/}{};
495 } else {
496 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
498 command(['checkout', $head], STDERR => 0);
501 my @refs;
502 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
503 unless ($gs) {
504 die "Unable to determine upstream SVN information from ",
505 "$head history.\nPerhaps the repository is empty.";
508 if (defined $_commit_url) {
509 $url = $_commit_url;
510 } else {
511 $url = eval { command_oneline('config', '--get',
512 "svn-remote.$gs->{repo_id}.commiturl") };
513 if (!$url) {
514 $url = $gs->full_url
518 my $last_rev = $_revision if defined $_revision;
519 if ($url) {
520 print "Committing to $url ...\n";
522 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
523 if ($_no_rebase && scalar(@$linear_refs) > 1) {
524 warn "Attempting to commit more than one change while ",
525 "--no-rebase is enabled.\n",
526 "If these changes depend on each other, re-running ",
527 "without --no-rebase may be required."
529 my $expect_url = $url;
530 Git::SVN::remove_username($expect_url);
531 while (1) {
532 my $d = shift @$linear_refs or last;
533 unless (defined $last_rev) {
534 (undef, $last_rev, undef) = cmt_metadata("$d~1");
535 unless (defined $last_rev) {
536 fatal "Unable to extract revision information ",
537 "from commit $d~1";
540 if ($_dry_run) {
541 print "diff-tree $d~1 $d\n";
542 } else {
543 my $cmt_rev;
544 my %ed_opts = ( r => $last_rev,
545 log => get_commit_entry($d)->{log},
546 ra => Git::SVN::Ra->new($url),
547 config => SVN::Core::config_get_config(
548 $Git::SVN::Ra::config_dir
550 tree_a => "$d~1",
551 tree_b => $d,
552 editor_cb => sub {
553 print "Committed r$_[0]\n";
554 $cmt_rev = $_[0];
556 svn_path => '');
557 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
558 print "No changes\n$d~1 == $d\n";
559 } elsif ($parents->{$d} && @{$parents->{$d}}) {
560 $gs->{inject_parents_dcommit}->{$cmt_rev} =
561 $parents->{$d};
563 $_fetch_all ? $gs->fetch_all : $gs->fetch;
564 $last_rev = $cmt_rev;
565 next if $_no_rebase;
567 # we always want to rebase against the current HEAD,
568 # not any head that was passed to us
569 my @diff = command('diff-tree', $d,
570 $gs->refname, '--');
571 my @finish;
572 if (@diff) {
573 @finish = rebase_cmd();
574 print STDERR "W: $d and ", $gs->refname,
575 " differ, using @finish:\n",
576 join("\n", @diff), "\n";
577 } else {
578 print "No changes between current HEAD and ",
579 $gs->refname,
580 "\nResetting to the latest ",
581 $gs->refname, "\n";
582 @finish = qw/reset --mixed/;
584 command_noisy(@finish, $gs->refname);
585 if (@diff) {
586 @refs = ();
587 my ($url_, $rev_, $uuid_, $gs_) =
588 working_head_info('HEAD', \@refs);
589 my ($linear_refs_, $parents_) =
590 linearize_history($gs_, \@refs);
591 if (scalar(@$linear_refs) !=
592 scalar(@$linear_refs_)) {
593 fatal "# of revisions changed ",
594 "\nbefore:\n",
595 join("\n", @$linear_refs),
596 "\n\nafter:\n",
597 join("\n", @$linear_refs_), "\n",
598 'If you are attempting to commit ',
599 "merges, try running:\n\t",
600 'git rebase --interactive',
601 '--preserve-merges ',
602 $gs->refname,
603 "\nBefore dcommitting";
605 if ($url_ ne $expect_url) {
606 if ($url_ eq $gs->metadata_url) {
607 print
608 "Accepting rewritten URL:",
609 " $url_\n";
610 } else {
611 fatal
612 "URL mismatch after rebase:",
613 " $url_ != $expect_url";
616 if ($uuid_ ne $uuid) {
617 fatal "uuid mismatch after rebase: ",
618 "$uuid_ != $uuid";
620 # remap parents
621 my (%p, @l, $i);
622 for ($i = 0; $i < scalar @$linear_refs; $i++) {
623 my $new = $linear_refs_->[$i] or next;
624 $p{$new} =
625 $parents->{$linear_refs->[$i]};
626 push @l, $new;
628 $parents = \%p;
629 $linear_refs = \@l;
634 if ($old_head) {
635 my $new_head = command_oneline(qw/rev-parse HEAD/);
636 my $new_is_symbolic = eval {
637 command_oneline(qw/symbolic-ref -q HEAD/);
639 if ($new_is_symbolic) {
640 print "dcommitted the branch ", $head, "\n";
641 } else {
642 print "dcommitted on a detached HEAD because you gave ",
643 "a revision argument.\n",
644 "The rewritten commit is: ", $new_head, "\n";
646 command(['checkout', $old_head], STDERR => 0);
649 unlink $gs->{index};
652 sub cmd_branch {
653 my ($branch_name, $head) = @_;
655 unless (defined $branch_name && length $branch_name) {
656 die(($_tag ? "tag" : "branch") . " name required\n");
658 $head ||= 'HEAD';
660 my ($src, $rev, undef, $gs) = working_head_info($head);
662 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
663 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
664 my $glob;
665 if ($#{$allglobs} == 0) {
666 $glob = $allglobs->[0];
667 } else {
668 unless(defined $_branch_dest) {
669 die "Multiple ",
670 $_tag ? "tag" : "branch",
671 " paths defined for Subversion repository.\n",
672 "You must specify where you want to create the ",
673 $_tag ? "tag" : "branch",
674 " with the --destination argument.\n";
676 foreach my $g (@{$allglobs}) {
677 # SVN::Git::Editor could probably be moved to Git.pm..
678 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
679 if ($_branch_dest =~ /$re/) {
680 $glob = $g;
681 last;
684 unless (defined $glob) {
685 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
686 foreach my $g (@{$allglobs}) {
687 $g->{path}->{left} =~ /$dest_re/ or next;
688 if (defined $glob) {
689 die "Ambiguous destination: ",
690 $_branch_dest, "\nmatches both '",
691 $glob->{path}->{left}, "' and '",
692 $g->{path}->{left}, "'\n";
694 $glob = $g;
696 unless (defined $glob) {
697 die "Unknown ",
698 $_tag ? "tag" : "branch",
699 " destination $_branch_dest\n";
703 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
704 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
706 my $ctx = SVN::Client->new(
707 auth => Git::SVN::Ra::_auth_providers(),
708 log_msg => sub {
709 ${ $_[0] } = defined $_message
710 ? $_message
711 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
712 . $branch_name;
716 eval {
717 $ctx->ls($dst, 'HEAD', 0);
718 } and die "branch ${branch_name} already exists\n";
720 print "Copying ${src} at r${rev} to ${dst}...\n";
721 $ctx->copy($src, $rev, $dst)
722 unless $_dry_run;
724 $gs->fetch_all;
727 sub cmd_find_rev {
728 my $revision_or_hash = shift or die "SVN or git revision required ",
729 "as a command-line argument\n";
730 my $result;
731 if ($revision_or_hash =~ /^r\d+$/) {
732 my $head = shift;
733 $head ||= 'HEAD';
734 my @refs;
735 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
736 unless ($gs) {
737 die "Unable to determine upstream SVN information from ",
738 "$head history\n";
740 my $desired_revision = substr($revision_or_hash, 1);
741 $result = $gs->rev_map_get($desired_revision, $uuid);
742 } else {
743 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
744 $result = $rev;
746 print "$result\n" if $result;
749 sub cmd_rebase {
750 command_noisy(qw/update-index --refresh/);
751 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
752 unless ($gs) {
753 die "Unable to determine upstream SVN information from ",
754 "working tree history\n";
756 if ($_dry_run) {
757 print "Remote Branch: " . $gs->refname . "\n";
758 print "SVN URL: " . $url . "\n";
759 return;
761 if (command(qw/diff-index HEAD --/)) {
762 print STDERR "Cannot rebase with uncommited changes:\n";
763 command_noisy('status');
764 exit 1;
766 unless ($_local) {
767 # rebase will checkout for us, so no need to do it explicitly
768 $_no_checkout = 'true';
769 $_fetch_all ? $gs->fetch_all : $gs->fetch;
771 command_noisy(rebase_cmd(), $gs->refname);
774 sub cmd_show_ignore {
775 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
776 $gs ||= Git::SVN->new;
777 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
778 $gs->prop_walk($gs->{path}, $r, sub {
779 my ($gs, $path, $props) = @_;
780 print STDOUT "\n# $path\n";
781 my $s = $props->{'svn:ignore'} or return;
782 $s =~ s/[\r\n]+/\n/g;
783 $s =~ s/^\n+//;
784 chomp $s;
785 $s =~ s#^#$path#gm;
786 print STDOUT "$s\n";
790 sub cmd_show_externals {
791 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
792 $gs ||= Git::SVN->new;
793 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
794 $gs->prop_walk($gs->{path}, $r, sub {
795 my ($gs, $path, $props) = @_;
796 print STDOUT "\n# $path\n";
797 my $s = $props->{'svn:externals'} or return;
798 $s =~ s/[\r\n]+/\n/g;
799 chomp $s;
800 $s =~ s#^#$path#gm;
801 print STDOUT "$s\n";
805 sub cmd_create_ignore {
806 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
807 $gs ||= Git::SVN->new;
808 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
809 $gs->prop_walk($gs->{path}, $r, sub {
810 my ($gs, $path, $props) = @_;
811 # $path is of the form /path/to/dir/
812 $path = '.' . $path;
813 # SVN can have attributes on empty directories,
814 # which git won't track
815 mkpath([$path]) unless -d $path;
816 my $ignore = $path . '.gitignore';
817 my $s = $props->{'svn:ignore'} or return;
818 open(GITIGNORE, '>', $ignore)
819 or fatal("Failed to open `$ignore' for writing: $!");
820 $s =~ s/[\r\n]+/\n/g;
821 $s =~ s/^\n+//;
822 chomp $s;
823 # Prefix all patterns so that the ignore doesn't apply
824 # to sub-directories.
825 $s =~ s#^#/#gm;
826 print GITIGNORE "$s\n";
827 close(GITIGNORE)
828 or fatal("Failed to close `$ignore': $!");
829 command_noisy('add', '-f', $ignore);
833 sub canonicalize_path {
834 my ($path) = @_;
835 my $dot_slash_added = 0;
836 if (substr($path, 0, 1) ne "/") {
837 $path = "./" . $path;
838 $dot_slash_added = 1;
840 # File::Spec->canonpath doesn't collapse x/../y into y (for a
841 # good reason), so let's do this manually.
842 $path =~ s#/+#/#g;
843 $path =~ s#/\.(?:/|$)#/#g;
844 $path =~ s#/[^/]+/\.\.##g;
845 $path =~ s#/$##g;
846 $path =~ s#^\./## if $dot_slash_added;
847 $path =~ s#^/##;
848 $path =~ s#^\.$##;
849 return $path;
852 sub canonicalize_url {
853 my ($url) = @_;
854 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
855 return $url;
858 # get_svnprops(PATH)
859 # ------------------
860 # Helper for cmd_propget and cmd_proplist below.
861 sub get_svnprops {
862 my $path = shift;
863 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
864 $gs ||= Git::SVN->new;
866 # prefix THE PATH by the sub-directory from which the user
867 # invoked us.
868 $path = $cmd_dir_prefix . $path;
869 fatal("No such file or directory: $path") unless -e $path;
870 my $is_dir = -d $path ? 1 : 0;
871 $path = $gs->{path} . '/' . $path;
873 # canonicalize the path (otherwise libsvn will abort or fail to
874 # find the file)
875 $path = canonicalize_path($path);
877 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
878 my $props;
879 if ($is_dir) {
880 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
882 else {
883 (undef, $props) = $gs->ra->get_file($path, $r, undef);
885 return $props;
888 # cmd_propget (PROP, PATH)
889 # ------------------------
890 # Print the SVN property PROP for PATH.
891 sub cmd_propget {
892 my ($prop, $path) = @_;
893 $path = '.' if not defined $path;
894 usage(1) if not defined $prop;
895 my $props = get_svnprops($path);
896 if (not defined $props->{$prop}) {
897 fatal("`$path' does not have a `$prop' SVN property.");
899 print $props->{$prop} . "\n";
902 # cmd_proplist (PATH)
903 # -------------------
904 # Print the list of SVN properties for PATH.
905 sub cmd_proplist {
906 my $path = shift;
907 $path = '.' if not defined $path;
908 my $props = get_svnprops($path);
909 print "Properties on '$path':\n";
910 foreach (sort keys %{$props}) {
911 print " $_\n";
915 sub cmd_multi_init {
916 my $url = shift;
917 unless (defined $_trunk || @_branches || @_tags) {
918 usage(1);
921 $_prefix = '' unless defined $_prefix;
922 if (defined $url) {
923 $url = canonicalize_url($url);
924 init_subdir(@_);
926 do_git_init_db();
927 if (defined $_trunk) {
928 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
929 # try both old-style and new-style lookups:
930 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
931 unless ($gs_trunk) {
932 my ($trunk_url, $trunk_path) =
933 complete_svn_url($url, $_trunk);
934 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
935 undef, $trunk_ref);
938 return unless @_branches || @_tags;
939 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
940 foreach my $path (@_branches) {
941 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
943 foreach my $path (@_tags) {
944 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
948 sub cmd_multi_fetch {
949 my $remotes = Git::SVN::read_all_remotes();
950 foreach my $repo_id (sort keys %$remotes) {
951 if ($remotes->{$repo_id}->{url}) {
952 Git::SVN::fetch_all($repo_id, $remotes);
957 # this command is special because it requires no metadata
958 sub cmd_commit_diff {
959 my ($ta, $tb, $url) = @_;
960 my $usage = "Usage: $0 commit-diff -r<revision> ".
961 "<tree-ish> <tree-ish> [<URL>]";
962 fatal($usage) if (!defined $ta || !defined $tb);
963 my $svn_path = '';
964 if (!defined $url) {
965 my $gs = eval { Git::SVN->new };
966 if (!$gs) {
967 fatal("Needed URL or usable git-svn --id in ",
968 "the command-line\n", $usage);
970 $url = $gs->{url};
971 $svn_path = $gs->{path};
973 unless (defined $_revision) {
974 fatal("-r|--revision is a required argument\n", $usage);
976 if (defined $_message && defined $_file) {
977 fatal("Both --message/-m and --file/-F specified ",
978 "for the commit message.\n",
979 "I have no idea what you mean");
981 if (defined $_file) {
982 $_message = file_to_s($_file);
983 } else {
984 $_message ||= get_commit_entry($tb)->{log};
986 my $ra ||= Git::SVN::Ra->new($url);
987 my $r = $_revision;
988 if ($r eq 'HEAD') {
989 $r = $ra->get_latest_revnum;
990 } elsif ($r !~ /^\d+$/) {
991 die "revision argument: $r not understood by git-svn\n";
993 my %ed_opts = ( r => $r,
994 log => $_message,
995 ra => $ra,
996 tree_a => $ta,
997 tree_b => $tb,
998 editor_cb => sub { print "Committed r$_[0]\n" },
999 svn_path => $svn_path );
1000 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1001 print "No changes\n$ta == $tb\n";
1005 sub escape_uri_only {
1006 my ($uri) = @_;
1007 my @tmp;
1008 foreach (split m{/}, $uri) {
1009 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1010 push @tmp, $_;
1012 join('/', @tmp);
1015 sub escape_url {
1016 my ($url) = @_;
1017 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1018 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1019 $url = "$scheme://$domain$uri";
1021 $url;
1024 sub cmd_info {
1025 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1026 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1027 if (exists $_[1]) {
1028 die "Too many arguments specified\n";
1031 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1033 if (!$file_type && !$diff_status) {
1034 print STDERR "svn: '$path' is not under version control\n";
1035 exit 1;
1038 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1039 unless ($gs) {
1040 die "Unable to determine upstream SVN information from ",
1041 "working tree history\n";
1044 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1045 $path = "." if $path eq "";
1047 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1049 if ($_url) {
1050 print escape_url($full_url), "\n";
1051 return;
1054 my $result = "Path: $path\n";
1055 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1056 $result .= "URL: " . escape_url($full_url) . "\n";
1058 eval {
1059 my $repos_root = $gs->repos_root;
1060 Git::SVN::remove_username($repos_root);
1061 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1063 if ($@) {
1064 $result .= "Repository Root: (offline)\n";
1066 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1067 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1068 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1070 $result .= "Node Kind: " .
1071 ($file_type eq "dir" ? "directory" : "file") . "\n";
1073 my $schedule = $diff_status eq "A"
1074 ? "add"
1075 : ($diff_status eq "D" ? "delete" : "normal");
1076 $result .= "Schedule: $schedule\n";
1078 if ($diff_status eq "A") {
1079 print $result, "\n";
1080 return;
1083 my ($lc_author, $lc_rev, $lc_date_utc);
1084 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1085 my $log = command_output_pipe(@args);
1086 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1087 while (<$log>) {
1088 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1089 $lc_author = $1;
1090 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1091 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1092 (undef, $lc_rev, undef) = ::extract_metadata($1);
1095 close $log;
1097 Git::SVN::Log::set_local_timezone();
1099 $result .= "Last Changed Author: $lc_author\n";
1100 $result .= "Last Changed Rev: $lc_rev\n";
1101 $result .= "Last Changed Date: " .
1102 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1104 if ($file_type ne "dir") {
1105 my $text_last_updated_date =
1106 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1107 $result .=
1108 "Text Last Updated: " .
1109 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1110 "\n";
1111 my $checksum;
1112 if ($diff_status eq "D") {
1113 my ($fh, $ctx) =
1114 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1115 if ($file_type eq "link") {
1116 my $file_name = <$fh>;
1117 $checksum = md5sum("link $file_name");
1118 } else {
1119 $checksum = md5sum($fh);
1121 command_close_pipe($fh, $ctx);
1122 } elsif ($file_type eq "link") {
1123 my $file_name =
1124 command(qw(cat-file blob), "HEAD:$path");
1125 $checksum =
1126 md5sum("link " . $file_name);
1127 } else {
1128 open FILE, "<", $path or die $!;
1129 $checksum = md5sum(\*FILE);
1130 close FILE or die $!;
1132 $result .= "Checksum: " . $checksum . "\n";
1135 print $result, "\n";
1138 sub cmd_reset {
1139 my $target = shift || $_revision or die "SVN revision required\n";
1140 $target = $1 if $target =~ /^r(\d+)$/;
1141 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1142 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1143 unless ($gs) {
1144 die "Unable to determine upstream SVN information from ".
1145 "history\n";
1147 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1148 $gs->rev_map_set($r, $c, 'reset', $uuid);
1149 print "r$r = $c ($gs->{ref_id})\n";
1152 sub cmd_gc {
1153 if (!$can_compress) {
1154 warn "Compress::Zlib could not be found; unhandled.log " .
1155 "files will not be compressed.\n";
1157 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1160 ########################### utility functions #########################
1162 sub rebase_cmd {
1163 my @cmd = qw/rebase/;
1164 push @cmd, '-v' if $_verbose;
1165 push @cmd, qw/--merge/ if $_merge;
1166 push @cmd, "--strategy=$_strategy" if $_strategy;
1167 @cmd;
1170 sub post_fetch_checkout {
1171 return if $_no_checkout;
1172 my $gs = $Git::SVN::_head or return;
1173 return if verify_ref('refs/heads/master^0');
1175 # look for "trunk" ref if it exists
1176 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1177 my $fetch = $remote->{fetch};
1178 if ($fetch) {
1179 foreach my $p (keys %$fetch) {
1180 basename($fetch->{$p}) eq 'trunk' or next;
1181 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1182 last;
1186 my $valid_head = verify_ref('HEAD^0');
1187 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1188 return if ($valid_head || !verify_ref('HEAD^0'));
1190 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1191 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1192 return if -f $index;
1194 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1195 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1196 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1197 print STDERR "Checked out HEAD:\n ",
1198 $gs->full_url, " r", $gs->last_rev, "\n";
1201 sub complete_svn_url {
1202 my ($url, $path) = @_;
1203 $path =~ s#/+$##;
1204 if ($path !~ m#^[a-z\+]+://#) {
1205 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1206 fatal("E: '$path' is not a complete URL ",
1207 "and a separate URL is not specified");
1209 return ($url, $path);
1211 return ($path, '');
1214 sub complete_url_ls_init {
1215 my ($ra, $repo_path, $switch, $pfx) = @_;
1216 unless ($repo_path) {
1217 print STDERR "W: $switch not specified\n";
1218 return;
1220 $repo_path =~ s#/+$##;
1221 if ($repo_path =~ m#^[a-z\+]+://#) {
1222 $ra = Git::SVN::Ra->new($repo_path);
1223 $repo_path = '';
1224 } else {
1225 $repo_path =~ s#^/+##;
1226 unless ($ra) {
1227 fatal("E: '$repo_path' is not a complete URL ",
1228 "and a separate URL is not specified");
1231 my $url = $ra->{url};
1232 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1233 my $k = "svn-remote.$gs->{repo_id}.url";
1234 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1235 if ($orig_url && ($orig_url ne $gs->{url})) {
1236 die "$k already set: $orig_url\n",
1237 "wanted to set to: $gs->{url}\n";
1239 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1240 my $remote_path = "$gs->{path}/$repo_path";
1241 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1242 $remote_path =~ s#/+#/#g;
1243 $remote_path =~ s#^/##g;
1244 $remote_path .= "/*" if $remote_path !~ /\*/;
1245 my ($n) = ($switch =~ /^--(\w+)/);
1246 if (length $pfx && $pfx !~ m#/$#) {
1247 die "--prefix='$pfx' must have a trailing slash '/'\n";
1249 command_noisy('config',
1250 '--add',
1251 "svn-remote.$gs->{repo_id}.$n",
1252 "$remote_path:refs/remotes/$pfx*" .
1253 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1256 sub verify_ref {
1257 my ($ref) = @_;
1258 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1259 { STDERR => 0 }); };
1262 sub get_tree_from_treeish {
1263 my ($treeish) = @_;
1264 # $treeish can be a symbolic ref, too:
1265 my $type = command_oneline(qw/cat-file -t/, $treeish);
1266 my $expected;
1267 while ($type eq 'tag') {
1268 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1270 if ($type eq 'commit') {
1271 $expected = (grep /^tree /, command(qw/cat-file commit/,
1272 $treeish))[0];
1273 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1274 die "Unable to get tree from $treeish\n" unless $expected;
1275 } elsif ($type eq 'tree') {
1276 $expected = $treeish;
1277 } else {
1278 die "$treeish is a $type, expected tree, tag or commit\n";
1280 return $expected;
1283 sub get_commit_entry {
1284 my ($treeish) = shift;
1285 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1286 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1287 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1288 open my $log_fh, '>', $commit_editmsg or croak $!;
1290 my $type = command_oneline(qw/cat-file -t/, $treeish);
1291 if ($type eq 'commit' || $type eq 'tag') {
1292 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1293 $type, $treeish);
1294 my $in_msg = 0;
1295 my $author;
1296 my $saw_from = 0;
1297 my $msgbuf = "";
1298 while (<$msg_fh>) {
1299 if (!$in_msg) {
1300 $in_msg = 1 if (/^\s*$/);
1301 $author = $1 if (/^author (.*>)/);
1302 } elsif (/^git-svn-id: /) {
1303 # skip this for now, we regenerate the
1304 # correct one on re-fetch anyways
1305 # TODO: set *:merge properties or like...
1306 } else {
1307 if (/^From:/ || /^Signed-off-by:/) {
1308 $saw_from = 1;
1310 $msgbuf .= $_;
1313 $msgbuf =~ s/\s+$//s;
1314 if ($Git::SVN::_add_author_from && defined($author)
1315 && !$saw_from) {
1316 $msgbuf .= "\n\nFrom: $author";
1318 print $log_fh $msgbuf or croak $!;
1319 command_close_pipe($msg_fh, $ctx);
1321 close $log_fh or croak $!;
1323 if ($_edit || ($type eq 'tree')) {
1324 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1325 # TODO: strip out spaces, comments, like git-commit.sh
1326 system($editor, $commit_editmsg);
1328 rename $commit_editmsg, $commit_msg or croak $!;
1330 require Encode;
1331 # SVN requires messages to be UTF-8 when entering the repo
1332 local $/;
1333 open $log_fh, '<', $commit_msg or croak $!;
1334 binmode $log_fh;
1335 chomp($log_entry{log} = <$log_fh>);
1337 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1338 my $msg = $log_entry{log};
1340 eval { $msg = Encode::decode($enc, $msg, 1) };
1341 if ($@) {
1342 die "Could not decode as $enc:\n", $msg,
1343 "\nPerhaps you need to set i18n.commitencoding\n";
1346 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1347 die "Could not encode as UTF-8:\n$msg\n" if $@;
1349 $log_entry{log} = $msg;
1351 close $log_fh or croak $!;
1353 unlink $commit_msg;
1354 \%log_entry;
1357 sub s_to_file {
1358 my ($str, $file, $mode) = @_;
1359 open my $fd,'>',$file or croak $!;
1360 print $fd $str,"\n" or croak $!;
1361 close $fd or croak $!;
1362 chmod ($mode &~ umask, $file) if (defined $mode);
1365 sub file_to_s {
1366 my $file = shift;
1367 open my $fd,'<',$file or croak "$!: file: $file\n";
1368 local $/;
1369 my $ret = <$fd>;
1370 close $fd or croak $!;
1371 $ret =~ s/\s*$//s;
1372 return $ret;
1375 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1376 sub load_authors {
1377 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1378 my $log = $cmd eq 'log';
1379 while (<$authors>) {
1380 chomp;
1381 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1382 my ($user, $name, $email) = ($1, $2, $3);
1383 if ($log) {
1384 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1385 } else {
1386 $users{$user} = [$name, $email];
1389 close $authors or croak $!;
1392 # convert GetOpt::Long specs for use by git-config
1393 sub read_repo_config {
1394 return unless -d $ENV{GIT_DIR};
1395 my $opts = shift;
1396 my @config_only;
1397 foreach my $o (keys %$opts) {
1398 # if we have mixedCase and a long option-only, then
1399 # it's a config-only variable that we don't need for
1400 # the command-line.
1401 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1402 my $v = $opts->{$o};
1403 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1404 $key =~ s/-//g;
1405 my $arg = 'git config';
1406 $arg .= ' --int' if ($o =~ /[:=]i$/);
1407 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1408 if (ref $v eq 'ARRAY') {
1409 chomp(my @tmp = `$arg --get-all svn.$key`);
1410 @$v = @tmp if @tmp;
1411 } else {
1412 chomp(my $tmp = `$arg --get svn.$key`);
1413 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1414 $$v = $tmp;
1418 delete @$opts{@config_only} if @config_only;
1421 sub extract_metadata {
1422 my $id = shift or return (undef, undef, undef);
1423 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1424 \s([a-f\d\-]+)$/ix);
1425 if (!defined $rev || !$uuid || !$url) {
1426 # some of the original repositories I made had
1427 # identifiers like this:
1428 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1430 return ($url, $rev, $uuid);
1433 sub cmt_metadata {
1434 return extract_metadata((grep(/^git-svn-id: /,
1435 command(qw/cat-file commit/, shift)))[-1]);
1438 sub cmt_sha2rev_batch {
1439 my %s2r;
1440 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1441 my $list = shift;
1443 foreach my $sha (@{$list}) {
1444 my $first = 1;
1445 my $size = 0;
1446 print $out $sha, "\n";
1448 while (my $line = <$in>) {
1449 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1450 last;
1451 } elsif ($first &&
1452 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1453 $first = 0;
1454 $size = $1;
1455 next;
1456 } elsif ($line =~ /^(git-svn-id: )/) {
1457 my (undef, $rev, undef) =
1458 extract_metadata($line);
1459 $s2r{$sha} = $rev;
1462 $size -= length($line);
1463 last if ($size == 0);
1467 command_close_bidi_pipe($pid, $in, $out, $ctx);
1469 return \%s2r;
1472 sub working_head_info {
1473 my ($head, $refs) = @_;
1474 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1475 my ($fh, $ctx) = command_output_pipe(@args, $head);
1476 my $hash;
1477 my %max;
1478 while (<$fh>) {
1479 if ( m{^commit ($::sha1)$} ) {
1480 unshift @$refs, $hash if $hash and $refs;
1481 $hash = $1;
1482 next;
1484 next unless s{^\s*(git-svn-id:)}{$1};
1485 my ($url, $rev, $uuid) = extract_metadata($_);
1486 if (defined $url && defined $rev) {
1487 next if $max{$url} and $max{$url} < $rev;
1488 if (my $gs = Git::SVN->find_by_url($url)) {
1489 my $c = $gs->rev_map_get($rev, $uuid);
1490 if ($c && $c eq $hash) {
1491 close $fh; # break the pipe
1492 return ($url, $rev, $uuid, $gs);
1493 } else {
1494 $max{$url} ||= $gs->rev_map_max;
1499 command_close_pipe($fh, $ctx);
1500 (undef, undef, undef, undef);
1503 sub read_commit_parents {
1504 my ($parents, $c) = @_;
1505 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1506 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1507 @{$parents->{$c}} = split(/ /, $p);
1510 sub linearize_history {
1511 my ($gs, $refs) = @_;
1512 my %parents;
1513 foreach my $c (@$refs) {
1514 read_commit_parents(\%parents, $c);
1517 my @linear_refs;
1518 my %skip = ();
1519 my $last_svn_commit = $gs->last_commit;
1520 foreach my $c (reverse @$refs) {
1521 next if $c eq $last_svn_commit;
1522 last if $skip{$c};
1524 unshift @linear_refs, $c;
1525 $skip{$c} = 1;
1527 # we only want the first parent to diff against for linear
1528 # history, we save the rest to inject when we finalize the
1529 # svn commit
1530 my $fp_a = verify_ref("$c~1");
1531 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1532 if (!$fp_a || !$fp_b) {
1533 die "Commit $c\n",
1534 "has no parent commit, and therefore ",
1535 "nothing to diff against.\n",
1536 "You should be working from a repository ",
1537 "originally created by git-svn\n";
1539 if ($fp_a ne $fp_b) {
1540 die "$c~1 = $fp_a, however parsing commit $c ",
1541 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1544 foreach my $p (@{$parents{$c}}) {
1545 $skip{$p} = 1;
1548 (\@linear_refs, \%parents);
1551 sub find_file_type_and_diff_status {
1552 my ($path) = @_;
1553 return ('dir', '') if $path eq '';
1555 my $diff_output =
1556 command_oneline(qw(diff --cached --name-status --), $path) || "";
1557 my $diff_status = (split(' ', $diff_output))[0] || "";
1559 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1561 return (undef, undef) if !$diff_status && !$ls_tree;
1563 if ($diff_status eq "A") {
1564 return ("link", $diff_status) if -l $path;
1565 return ("dir", $diff_status) if -d $path;
1566 return ("file", $diff_status);
1569 my $mode = (split(' ', $ls_tree))[0] || "";
1571 return ("link", $diff_status) if $mode eq "120000";
1572 return ("dir", $diff_status) if $mode eq "040000";
1573 return ("file", $diff_status);
1576 sub md5sum {
1577 my $arg = shift;
1578 my $ref = ref $arg;
1579 my $md5 = Digest::MD5->new();
1580 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1581 $md5->addfile($arg) or croak $!;
1582 } elsif ($ref eq 'SCALAR') {
1583 $md5->add($$arg) or croak $!;
1584 } elsif (!$ref) {
1585 $md5->add($arg) or croak $!;
1586 } else {
1587 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1589 return $md5->hexdigest();
1592 sub gc_directory {
1593 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1594 my $out_filename = $_ . ".gz";
1595 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1596 binmode $in_fh;
1597 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1598 die "Unable to open $out_filename: $!\n";
1600 my $res;
1601 while ($res = sysread($in_fh, my $str, 1024)) {
1602 $gz->gzwrite($str) or
1603 die "Unable to write: ".$gz->gzerror()."!\n";
1605 unlink $_ or die "unlink $File::Find::name: $!\n";
1606 } elsif (-f $_ && basename($_) eq "index") {
1607 unlink $_ or die "unlink $_: $!\n";
1611 package Git::SVN;
1612 use strict;
1613 use warnings;
1614 use Fcntl qw/:DEFAULT :seek/;
1615 use constant rev_map_fmt => 'NH40';
1616 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1617 $_repack $_repack_flags $_use_svm_props $_head
1618 $_use_svnsync_props $no_reuse_existing $_minimize_url
1619 $_use_log_author $_add_author_from $_localtime/;
1620 use Carp qw/croak/;
1621 use File::Path qw/mkpath/;
1622 use File::Copy qw/copy/;
1623 use IPC::Open3;
1625 my ($_gc_nr, $_gc_period);
1627 # properties that we do not log:
1628 my %SKIP_PROP;
1629 BEGIN {
1630 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1631 svn:special svn:executable
1632 svn:entry:committed-rev
1633 svn:entry:last-author
1634 svn:entry:uuid
1635 svn:entry:committed-date/;
1637 # some options are read globally, but can be overridden locally
1638 # per [svn-remote "..."] section. Command-line options will *NOT*
1639 # override options set in an [svn-remote "..."] section
1640 no strict 'refs';
1641 for my $option (qw/follow_parent no_metadata use_svm_props
1642 use_svnsync_props/) {
1643 my $key = $option;
1644 $key =~ tr/_//d;
1645 my $prop = "-$option";
1646 *$option = sub {
1647 my ($self) = @_;
1648 return $self->{$prop} if exists $self->{$prop};
1649 my $k = "svn-remote.$self->{repo_id}.$key";
1650 eval { command_oneline(qw/config --get/, $k) };
1651 if ($@) {
1652 $self->{$prop} = ${"Git::SVN::_$option"};
1653 } else {
1654 my $v = command_oneline(qw/config --bool/,$k);
1655 $self->{$prop} = $v eq 'false' ? 0 : 1;
1657 return $self->{$prop};
1663 my (%LOCKFILES, %INDEX_FILES);
1664 END {
1665 unlink keys %LOCKFILES if %LOCKFILES;
1666 unlink keys %INDEX_FILES if %INDEX_FILES;
1669 sub resolve_local_globs {
1670 my ($url, $fetch, $glob_spec) = @_;
1671 return unless defined $glob_spec;
1672 my $ref = $glob_spec->{ref};
1673 my $path = $glob_spec->{path};
1674 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1675 next unless m#^$ref->{regex}$#;
1676 my $p = $1;
1677 my $pathname = desanitize_refname($path->full_path($p));
1678 my $refname = desanitize_refname($ref->full_path($p));
1679 if (my $existing = $fetch->{$pathname}) {
1680 if ($existing ne $refname) {
1681 die "Refspec conflict:\n",
1682 "existing: $existing\n",
1683 " globbed: $refname\n";
1685 my $u = (::cmt_metadata("$refname"))[0];
1686 $u =~ s!^\Q$url\E(/|$)!! or die
1687 "$refname: '$url' not found in '$u'\n";
1688 if ($pathname ne $u) {
1689 warn "W: Refspec glob conflict ",
1690 "(ref: $refname):\n",
1691 "expected path: $pathname\n",
1692 " real path: $u\n",
1693 "Continuing ahead with $u\n";
1694 next;
1696 } else {
1697 $fetch->{$pathname} = $refname;
1702 sub parse_revision_argument {
1703 my ($base, $head) = @_;
1704 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1705 return ($base, $head);
1707 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1708 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1709 return ($head, $head) if ($::_revision eq 'HEAD');
1710 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1711 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1712 die "revision argument: $::_revision not understood by git-svn\n";
1715 sub fetch_all {
1716 my ($repo_id, $remotes) = @_;
1717 if (ref $repo_id) {
1718 my $gs = $repo_id;
1719 $repo_id = undef;
1720 $repo_id = $gs->{repo_id};
1722 $remotes ||= read_all_remotes();
1723 my $remote = $remotes->{$repo_id} or
1724 die "[svn-remote \"$repo_id\"] unknown\n";
1725 my $fetch = $remote->{fetch};
1726 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1727 my (@gs, @globs);
1728 my $ra = Git::SVN::Ra->new($url);
1729 my $uuid = $ra->get_uuid;
1730 my $head = $ra->get_latest_revnum;
1731 $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] });
1732 my $base = defined $fetch ? $head : 0;
1734 # read the max revs for wildcard expansion (branches/*, tags/*)
1735 foreach my $t (qw/branches tags/) {
1736 defined $remote->{$t} or next;
1737 push @globs, @{$remote->{$t}};
1739 my $max_rev = eval { tmp_config(qw/--int --get/,
1740 "svn-remote.$repo_id.${t}-maxRev") };
1741 if (defined $max_rev && ($max_rev < $base)) {
1742 $base = $max_rev;
1743 } elsif (!defined $max_rev) {
1744 $base = 0;
1748 if ($fetch) {
1749 foreach my $p (sort keys %$fetch) {
1750 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1751 my $lr = $gs->rev_map_max;
1752 if (defined $lr) {
1753 $base = $lr if ($lr < $base);
1755 push @gs, $gs;
1759 ($base, $head) = parse_revision_argument($base, $head);
1760 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1763 sub read_all_remotes {
1764 my $r = {};
1765 my $use_svm_props = eval { command_oneline(qw/config --bool
1766 svn.useSvmProps/) };
1767 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1768 my $svn_refspec = qr{\s*/?(.*?)\s*:\s*(.+?)\s*};
1769 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1770 if (m!^(.+)\.fetch=$svn_refspec$!) {
1771 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1772 die("svn-remote.$remote: remote ref '$remote_ref' "
1773 . "must start with 'refs/'\n")
1774 unless $remote_ref =~ m{^refs/};
1775 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1776 $r->{$remote}->{svm} = {} if $use_svm_props;
1777 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1778 $r->{$1}->{svm} = {};
1779 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1780 $r->{$1}->{url} = $2;
1781 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1782 my ($remote, $t, $local_ref, $remote_ref) =
1783 ($1, $2, $3, $4);
1784 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1785 . "must start with 'refs/'\n")
1786 unless $remote_ref =~ m{^refs/};
1787 my $rs = {
1788 t => $t,
1789 remote => $remote,
1790 path => Git::SVN::GlobSpec->new($local_ref),
1791 ref => Git::SVN::GlobSpec->new($remote_ref) };
1792 if (length($rs->{ref}->{right}) != 0) {
1793 die "The '*' glob character must be the last ",
1794 "character of '$remote_ref'\n";
1796 push @{ $r->{$remote}->{$t} }, $rs;
1800 map {
1801 if (defined $r->{$_}->{svm}) {
1802 my $svm;
1803 eval {
1804 my $section = "svn-remote.$_";
1805 $svm = {
1806 source => tmp_config('--get',
1807 "$section.svm-source"),
1808 replace => tmp_config('--get',
1809 "$section.svm-replace"),
1812 $r->{$_}->{svm} = $svm;
1814 } keys %$r;
1819 sub init_vars {
1820 $_gc_nr = $_gc_period = 1000;
1821 if (defined $_repack || defined $_repack_flags) {
1822 warn "Repack options are obsolete; they have no effect.\n";
1826 sub verify_remotes_sanity {
1827 return unless -d $ENV{GIT_DIR};
1828 my %seen;
1829 foreach (command(qw/config -l/)) {
1830 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1831 if ($seen{$1}) {
1832 die "Remote ref refs/remote/$1 is tracked by",
1833 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1834 "Please resolve this ambiguity in ",
1835 "your git configuration file before ",
1836 "continuing\n";
1838 $seen{$1} = $_;
1843 sub find_existing_remote {
1844 my ($url, $remotes) = @_;
1845 return undef if $no_reuse_existing;
1846 my $existing;
1847 foreach my $repo_id (keys %$remotes) {
1848 my $u = $remotes->{$repo_id}->{url} or next;
1849 next if $u ne $url;
1850 $existing = $repo_id;
1851 last;
1853 $existing;
1856 sub init_remote_config {
1857 my ($self, $url, $no_write) = @_;
1858 $url =~ s!/+$!!; # strip trailing slash
1859 my $r = read_all_remotes();
1860 my $existing = find_existing_remote($url, $r);
1861 if ($existing) {
1862 unless ($no_write) {
1863 print STDERR "Using existing ",
1864 "[svn-remote \"$existing\"]\n";
1866 $self->{repo_id} = $existing;
1867 } elsif ($_minimize_url) {
1868 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1869 $existing = find_existing_remote($min_url, $r);
1870 if ($existing) {
1871 unless ($no_write) {
1872 print STDERR "Using existing ",
1873 "[svn-remote \"$existing\"]\n";
1875 $self->{repo_id} = $existing;
1877 if ($min_url ne $url) {
1878 unless ($no_write) {
1879 print STDERR "Using higher level of URL: ",
1880 "$url => $min_url\n";
1882 my $old_path = $self->{path};
1883 $self->{path} = $url;
1884 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1885 if (length $old_path) {
1886 $self->{path} .= "/$old_path";
1888 $url = $min_url;
1891 my $orig_url;
1892 if (!$existing) {
1893 # verify that we aren't overwriting anything:
1894 $orig_url = eval {
1895 command_oneline('config', '--get',
1896 "svn-remote.$self->{repo_id}.url")
1898 if ($orig_url && ($orig_url ne $url)) {
1899 die "svn-remote.$self->{repo_id}.url already set: ",
1900 "$orig_url\nwanted to set to: $url\n";
1903 my ($xrepo_id, $xpath) = find_ref($self->refname);
1904 if (!$no_write && defined $xpath) {
1905 die "svn-remote.$xrepo_id.fetch already set to track ",
1906 "$xpath:", $self->refname, "\n";
1908 unless ($no_write) {
1909 command_noisy('config',
1910 "svn-remote.$self->{repo_id}.url", $url);
1911 $self->{path} =~ s{^/}{};
1912 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1913 command_noisy('config', '--add',
1914 "svn-remote.$self->{repo_id}.fetch",
1915 "$self->{path}:".$self->refname);
1917 $self->{url} = $url;
1920 sub find_by_url { # repos_root and, path are optional
1921 my ($class, $full_url, $repos_root, $path) = @_;
1923 return undef unless defined $full_url;
1924 remove_username($full_url);
1925 remove_username($repos_root) if defined $repos_root;
1926 my $remotes = read_all_remotes();
1927 if (defined $full_url && defined $repos_root && !defined $path) {
1928 $path = $full_url;
1929 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1931 foreach my $repo_id (keys %$remotes) {
1932 my $u = $remotes->{$repo_id}->{url} or next;
1933 remove_username($u);
1934 next if defined $repos_root && $repos_root ne $u;
1936 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1937 foreach my $t (qw/branches tags/) {
1938 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1939 resolve_local_globs($u, $fetch, $globspec);
1942 my $p = $path;
1943 my $rwr = rewrite_root({repo_id => $repo_id});
1944 my $svm = $remotes->{$repo_id}->{svm}
1945 if defined $remotes->{$repo_id}->{svm};
1946 unless (defined $p) {
1947 $p = $full_url;
1948 my $z = $u;
1949 my $prefix = '';
1950 if ($rwr) {
1951 $z = $rwr;
1952 remove_username($z);
1953 } elsif (defined $svm) {
1954 $z = $svm->{source};
1955 $prefix = $svm->{replace};
1956 $prefix =~ s#^\Q$u\E(?:/|$)##;
1957 $prefix =~ s#/$##;
1959 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1961 foreach my $f (keys %$fetch) {
1962 next if $f ne $p;
1963 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1966 undef;
1969 sub init {
1970 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1971 my $self = _new($class, $repo_id, $ref_id, $path);
1972 if (defined $url) {
1973 $self->init_remote_config($url, $no_write);
1975 $self;
1978 sub find_ref {
1979 my ($ref_id) = @_;
1980 foreach (command(qw/config -l/)) {
1981 next unless m!^svn-remote\.(.+)\.fetch=
1982 \s*/?(.*?)\s*:\s*(.+?)\s*$!x;
1983 my ($repo_id, $path, $ref) = ($1, $2, $3);
1984 if ($ref eq $ref_id) {
1985 $path = '' if ($path =~ m#^\./?#);
1986 return ($repo_id, $path);
1989 (undef, undef, undef);
1992 sub new {
1993 my ($class, $ref_id, $repo_id, $path) = @_;
1994 if (defined $ref_id && !defined $repo_id && !defined $path) {
1995 ($repo_id, $path) = find_ref($ref_id);
1996 if (!defined $repo_id) {
1997 die "Could not find a \"svn-remote.*.fetch\" key ",
1998 "in the repository configuration matching: ",
1999 "$ref_id\n";
2002 my $self = _new($class, $repo_id, $ref_id, $path);
2003 if (!defined $self->{path} || !length $self->{path}) {
2004 my $fetch = command_oneline('config', '--get',
2005 "svn-remote.$repo_id.fetch",
2006 ":$ref_id\$") or
2007 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2008 "\":$ref_id\$\" in config\n";
2009 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2011 $self->{url} = command_oneline('config', '--get',
2012 "svn-remote.$repo_id.url") or
2013 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2014 $self->rebuild;
2015 $self;
2018 sub refname {
2019 my ($refname) = $_[0]->{ref_id} ;
2021 # It cannot end with a slash /, we'll throw up on this because
2022 # SVN can't have directories with a slash in their name, either:
2023 if ($refname =~ m{/$}) {
2024 die "ref: '$refname' ends with a trailing slash, this is ",
2025 "not permitted by git nor Subversion\n";
2028 # It cannot have ASCII control character space, tilde ~, caret ^,
2029 # colon :, question-mark ?, asterisk *, space, or open bracket [
2030 # anywhere.
2032 # Additionally, % must be escaped because it is used for escaping
2033 # and we want our escaped refname to be reversible
2034 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2036 # no slash-separated component can begin with a dot .
2037 # /.* becomes /%2E*
2038 $refname =~ s{/\.}{/%2E}g;
2040 # It cannot have two consecutive dots .. anywhere
2041 # .. becomes %2E%2E
2042 $refname =~ s{\.\.}{%2E%2E}g;
2044 return $refname;
2047 sub desanitize_refname {
2048 my ($refname) = @_;
2049 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2050 return $refname;
2053 sub svm_uuid {
2054 my ($self) = @_;
2055 return $self->{svm}->{uuid} if $self->svm;
2056 $self->ra;
2057 unless ($self->{svm}) {
2058 die "SVM UUID not cached, and reading remotely failed\n";
2060 $self->{svm}->{uuid};
2063 sub svm {
2064 my ($self) = @_;
2065 return $self->{svm} if $self->{svm};
2066 my $svm;
2067 # see if we have it in our config, first:
2068 eval {
2069 my $section = "svn-remote.$self->{repo_id}";
2070 $svm = {
2071 source => tmp_config('--get', "$section.svm-source"),
2072 uuid => tmp_config('--get', "$section.svm-uuid"),
2073 replace => tmp_config('--get', "$section.svm-replace"),
2076 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2077 $self->{svm} = $svm;
2079 $self->{svm};
2082 sub _set_svm_vars {
2083 my ($self, $ra) = @_;
2084 return $ra if $self->svm;
2086 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2087 "(svm:source, svm:uuid) ",
2088 "from the following URLs:\n" );
2089 sub read_svm_props {
2090 my ($self, $ra, $path, $r) = @_;
2091 my $props = ($ra->get_dir($path, $r))[2];
2092 my $src = $props->{'svm:source'};
2093 my $uuid = $props->{'svm:uuid'};
2094 return undef if (!$src || !$uuid);
2096 chomp($src, $uuid);
2098 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2099 or die "doesn't look right - svm:uuid is '$uuid'\n";
2101 # the '!' is used to mark the repos_root!/relative/path
2102 $src =~ s{/?!/?}{/};
2103 $src =~ s{/+$}{}; # no trailing slashes please
2104 # username is of no interest
2105 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2107 my $replace = $ra->{url};
2108 $replace .= "/$path" if length $path;
2110 my $section = "svn-remote.$self->{repo_id}";
2111 tmp_config("$section.svm-source", $src);
2112 tmp_config("$section.svm-replace", $replace);
2113 tmp_config("$section.svm-uuid", $uuid);
2114 $self->{svm} = {
2115 source => $src,
2116 uuid => $uuid,
2117 replace => $replace
2121 my $r = $ra->get_latest_revnum;
2122 my $path = $self->{path};
2123 my %tried;
2124 while (length $path) {
2125 unless ($tried{"$self->{url}/$path"}) {
2126 return $ra if $self->read_svm_props($ra, $path, $r);
2127 $tried{"$self->{url}/$path"} = 1;
2129 $path =~ s#/?[^/]+$##;
2131 die "Path: '$path' should be ''\n" if $path ne '';
2132 return $ra if $self->read_svm_props($ra, $path, $r);
2133 $tried{"$self->{url}/$path"} = 1;
2135 if ($ra->{repos_root} eq $self->{url}) {
2136 die @err, (map { " $_\n" } keys %tried), "\n";
2139 # nope, make sure we're connected to the repository root:
2140 my $ok;
2141 my @tried_b;
2142 $path = $ra->{svn_path};
2143 $ra = Git::SVN::Ra->new($ra->{repos_root});
2144 while (length $path) {
2145 unless ($tried{"$ra->{url}/$path"}) {
2146 $ok = $self->read_svm_props($ra, $path, $r);
2147 last if $ok;
2148 $tried{"$ra->{url}/$path"} = 1;
2150 $path =~ s#/?[^/]+$##;
2152 die "Path: '$path' should be ''\n" if $path ne '';
2153 $ok ||= $self->read_svm_props($ra, $path, $r);
2154 $tried{"$ra->{url}/$path"} = 1;
2155 if (!$ok) {
2156 die @err, (map { " $_\n" } keys %tried), "\n";
2158 Git::SVN::Ra->new($self->{url});
2161 sub svnsync {
2162 my ($self) = @_;
2163 return $self->{svnsync} if $self->{svnsync};
2165 if ($self->no_metadata) {
2166 die "Can't have both 'noMetadata' and ",
2167 "'useSvnsyncProps' options set!\n";
2169 if ($self->rewrite_root) {
2170 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2171 "options set!\n";
2174 my $svnsync;
2175 # see if we have it in our config, first:
2176 eval {
2177 my $section = "svn-remote.$self->{repo_id}";
2179 my $url = tmp_config('--get', "$section.svnsync-url");
2180 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2181 die "doesn't look right - svn:sync-from-url is '$url'\n";
2183 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2184 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2185 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2187 $svnsync = { url => $url, uuid => $uuid }
2189 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2190 return $self->{svnsync} = $svnsync;
2193 my $err = "useSvnsyncProps set, but failed to read " .
2194 "svnsync property: svn:sync-from-";
2195 my $rp = $self->ra->rev_proplist(0);
2197 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2198 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2199 die "doesn't look right - svn:sync-from-url is '$url'\n";
2201 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2202 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2203 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2205 my $section = "svn-remote.$self->{repo_id}";
2206 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2207 tmp_config('--add', "$section.svnsync-url", $url);
2208 return $self->{svnsync} = { url => $url, uuid => $uuid };
2211 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2212 # remote lookup (useful for 'git svn log').
2213 sub ra_uuid {
2214 my ($self) = @_;
2215 unless ($self->{ra_uuid}) {
2216 my $key = "svn-remote.$self->{repo_id}.uuid";
2217 my $uuid = eval { tmp_config('--get', $key) };
2218 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2219 $self->{ra_uuid} = $uuid;
2220 } else {
2221 die "ra_uuid called without URL\n" unless $self->{url};
2222 $self->{ra_uuid} = $self->ra->get_uuid;
2223 tmp_config('--add', $key, $self->{ra_uuid});
2226 $self->{ra_uuid};
2229 sub _set_repos_root {
2230 my ($self, $repos_root) = @_;
2231 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2232 $repos_root ||= $self->ra->{repos_root};
2233 tmp_config($k, $repos_root);
2234 $repos_root;
2237 sub repos_root {
2238 my ($self) = @_;
2239 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2240 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2243 sub ra {
2244 my ($self) = shift;
2245 my $ra = Git::SVN::Ra->new($self->{url});
2246 $self->_set_repos_root($ra->{repos_root});
2247 if ($self->use_svm_props && !$self->{svm}) {
2248 if ($self->no_metadata) {
2249 die "Can't have both 'noMetadata' and ",
2250 "'useSvmProps' options set!\n";
2251 } elsif ($self->use_svnsync_props) {
2252 die "Can't have both 'useSvnsyncProps' and ",
2253 "'useSvmProps' options set!\n";
2255 $ra = $self->_set_svm_vars($ra);
2256 $self->{-want_revprops} = 1;
2258 $ra;
2261 # prop_walk(PATH, REV, SUB)
2262 # -------------------------
2263 # Recursively traverse PATH at revision REV and invoke SUB for each
2264 # directory that contains a SVN property. SUB will be invoked as
2265 # follows: &SUB(gs, path, props); where `gs' is this instance of
2266 # Git::SVN, `path' the path to the directory where the properties
2267 # `props' were found. The `path' will be relative to point of checkout,
2268 # that is, if url://repo/trunk is the current Git branch, and that
2269 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2270 # as `path' (note the trailing `/').
2271 sub prop_walk {
2272 my ($self, $path, $rev, $sub) = @_;
2274 $path =~ s#^/##;
2275 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2276 $path =~ s#^/*#/#g;
2277 my $p = $path;
2278 # Strip the irrelevant part of the path.
2279 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2280 # Ensure the path is terminated by a `/'.
2281 $p =~ s#/*$#/#;
2283 # The properties contain all the internal SVN stuff nobody
2284 # (usually) cares about.
2285 my $interesting_props = 0;
2286 foreach (keys %{$props}) {
2287 # If it doesn't start with `svn:', it must be a
2288 # user-defined property.
2289 ++$interesting_props and next if $_ !~ /^svn:/;
2290 # FIXME: Fragile, if SVN adds new public properties,
2291 # this needs to be updated.
2292 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2293 |eol-style|mime-type
2294 |externals|needs-lock)$/x;
2296 &$sub($self, $p, $props) if $interesting_props;
2298 foreach (sort keys %$dirent) {
2299 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2300 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2304 sub last_rev { ($_[0]->last_rev_commit)[0] }
2305 sub last_commit { ($_[0]->last_rev_commit)[1] }
2307 # returns the newest SVN revision number and newest commit SHA1
2308 sub last_rev_commit {
2309 my ($self) = @_;
2310 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2311 return ($self->{last_rev}, $self->{last_commit});
2313 my $c = ::verify_ref($self->refname.'^0');
2314 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2315 my $rev = (::cmt_metadata($c))[1];
2316 if (defined $rev) {
2317 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2318 return ($rev, $c);
2321 my $map_path = $self->map_path;
2322 unless (-e $map_path) {
2323 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2324 return (undef, undef);
2326 my ($rev, $commit) = $self->rev_map_max(1);
2327 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2328 return ($rev, $commit);
2331 sub get_fetch_range {
2332 my ($self, $min, $max) = @_;
2333 $max ||= $self->ra->get_latest_revnum;
2334 $min ||= $self->rev_map_max;
2335 (++$min, $max);
2338 sub tmp_config {
2339 my (@args) = @_;
2340 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2341 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2342 if (! -f $config && -f $old_def_config) {
2343 rename $old_def_config, $config or
2344 die "Failed rename $old_def_config => $config: $!\n";
2346 my $old_config = $ENV{GIT_CONFIG};
2347 $ENV{GIT_CONFIG} = $config;
2348 $@ = undef;
2349 my @ret = eval {
2350 unless (-f $config) {
2351 mkfile($config);
2352 open my $fh, '>', $config or
2353 die "Can't open $config: $!\n";
2354 print $fh "; This file is used internally by ",
2355 "git-svn\n" or die
2356 "Couldn't write to $config: $!\n";
2357 print $fh "; You should not have to edit it\n" or
2358 die "Couldn't write to $config: $!\n";
2359 close $fh or die "Couldn't close $config: $!\n";
2361 command('config', @args);
2363 my $err = $@;
2364 if (defined $old_config) {
2365 $ENV{GIT_CONFIG} = $old_config;
2366 } else {
2367 delete $ENV{GIT_CONFIG};
2369 die $err if $err;
2370 wantarray ? @ret : $ret[0];
2373 sub tmp_index_do {
2374 my ($self, $sub) = @_;
2375 my $old_index = $ENV{GIT_INDEX_FILE};
2376 $ENV{GIT_INDEX_FILE} = $self->{index};
2377 $@ = undef;
2378 my @ret = eval {
2379 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2380 mkpath([$dir]) unless -d $dir;
2381 &$sub;
2383 my $err = $@;
2384 if (defined $old_index) {
2385 $ENV{GIT_INDEX_FILE} = $old_index;
2386 } else {
2387 delete $ENV{GIT_INDEX_FILE};
2389 die $err if $err;
2390 wantarray ? @ret : $ret[0];
2393 sub assert_index_clean {
2394 my ($self, $treeish) = @_;
2396 $self->tmp_index_do(sub {
2397 command_noisy('read-tree', $treeish) unless -e $self->{index};
2398 my $x = command_oneline('write-tree');
2399 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2400 /^tree ($::sha1)/mo);
2401 return if $y eq $x;
2403 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2404 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2405 command_noisy('read-tree', $treeish);
2406 $x = command_oneline('write-tree');
2407 if ($y ne $x) {
2408 ::fatal "trees ($treeish) $y != $x\n",
2409 "Something is seriously wrong...";
2414 sub get_commit_parents {
2415 my ($self, $log_entry) = @_;
2416 my (%seen, @ret, @tmp);
2417 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2418 if (my $ip = $self->{inject_parents}) {
2419 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2420 push @tmp, $commit;
2423 if (my $cur = ::verify_ref($self->refname.'^0')) {
2424 push @tmp, $cur;
2426 if (my $ipd = $self->{inject_parents_dcommit}) {
2427 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2428 push @tmp, @$commit;
2431 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2432 while (my $p = shift @tmp) {
2433 next if $seen{$p};
2434 $seen{$p} = 1;
2435 push @ret, $p;
2436 # MAXPARENT is defined to 16 in commit-tree.c:
2437 last if @ret >= 16;
2439 if (@tmp) {
2440 die "r$log_entry->{revision}: No room for parents:\n\t",
2441 join("\n\t", @tmp), "\n";
2443 @ret;
2446 sub rewrite_root {
2447 my ($self) = @_;
2448 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2449 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2450 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2451 if ($rwr) {
2452 $rwr =~ s#/+$##;
2453 if ($rwr !~ m#^[a-z\+]+://#) {
2454 die "$rwr is not a valid URL (key: $k)\n";
2457 $self->{-rewrite_root} = $rwr;
2460 sub metadata_url {
2461 my ($self) = @_;
2462 ($self->rewrite_root || $self->{url}) .
2463 (length $self->{path} ? '/' . $self->{path} : '');
2466 sub full_url {
2467 my ($self) = @_;
2468 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2472 sub set_commit_header_env {
2473 my ($log_entry) = @_;
2474 my %env;
2475 foreach my $ned (qw/NAME EMAIL DATE/) {
2476 foreach my $ac (qw/AUTHOR COMMITTER/) {
2477 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2481 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2482 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2483 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2485 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2486 ? $log_entry->{commit_name}
2487 : $log_entry->{name};
2488 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2489 ? $log_entry->{commit_email}
2490 : $log_entry->{email};
2491 \%env;
2494 sub restore_commit_header_env {
2495 my ($env) = @_;
2496 foreach my $ned (qw/NAME EMAIL DATE/) {
2497 foreach my $ac (qw/AUTHOR COMMITTER/) {
2498 my $k = "GIT_${ac}_${ned}";
2499 if (defined $env->{$k}) {
2500 $ENV{$k} = $env->{$k};
2501 } else {
2502 delete $ENV{$k};
2508 sub gc {
2509 command_noisy('gc', '--auto');
2512 sub do_git_commit {
2513 my ($self, $log_entry) = @_;
2514 my $lr = $self->last_rev;
2515 if (defined $lr && $lr >= $log_entry->{revision}) {
2516 die "Last fetched revision of ", $self->refname,
2517 " was r$lr, but we are about to fetch: ",
2518 "r$log_entry->{revision}!\n";
2520 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2521 croak "$log_entry->{revision} = $c already exists! ",
2522 "Why are we refetching it?\n";
2524 my $old_env = set_commit_header_env($log_entry);
2525 my $tree = $log_entry->{tree};
2526 if (!defined $tree) {
2527 $tree = $self->tmp_index_do(sub {
2528 command_oneline('write-tree') });
2530 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2532 my @exec = ('git', 'commit-tree', $tree);
2533 foreach ($self->get_commit_parents($log_entry)) {
2534 push @exec, '-p', $_;
2536 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2537 or croak $!;
2538 binmode $msg_fh;
2540 # we always get UTF-8 from SVN, but we may want our commits in
2541 # a different encoding.
2542 if (my $enc = Git::config('i18n.commitencoding')) {
2543 require Encode;
2544 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2546 print $msg_fh $log_entry->{log} or croak $!;
2547 restore_commit_header_env($old_env);
2548 unless ($self->no_metadata) {
2549 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2550 or croak $!;
2552 $msg_fh->flush == 0 or croak $!;
2553 close $msg_fh or croak $!;
2554 chomp(my $commit = do { local $/; <$out_fh> });
2555 close $out_fh or croak $!;
2556 waitpid $pid, 0;
2557 croak $? if $?;
2558 if ($commit !~ /^$::sha1$/o) {
2559 die "Failed to commit, invalid sha1: $commit\n";
2562 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2564 $self->{last_rev} = $log_entry->{revision};
2565 $self->{last_commit} = $commit;
2566 print "r$log_entry->{revision}" unless $::_q > 1;
2567 if (defined $log_entry->{svm_revision}) {
2568 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2569 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2570 0, $self->svm_uuid);
2572 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2573 if (--$_gc_nr == 0) {
2574 $_gc_nr = $_gc_period;
2575 gc();
2577 return $commit;
2580 sub match_paths {
2581 my ($self, $paths, $r) = @_;
2582 return 1 if $self->{path} eq '';
2583 if (my $path = $paths->{"/$self->{path}"}) {
2584 return ($path->{action} eq 'D') ? 0 : 1;
2586 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2587 if (grep /$self->{path_regex}/, keys %$paths) {
2588 return 1;
2590 my $c = '';
2591 foreach (split m#/#, $self->{path}) {
2592 $c .= "/$_";
2593 next unless ($paths->{$c} &&
2594 ($paths->{$c}->{action} =~ /^[AR]$/));
2595 if ($self->ra->check_path($self->{path}, $r) ==
2596 $SVN::Node::dir) {
2597 return 1;
2600 return 0;
2603 sub find_parent_branch {
2604 my ($self, $paths, $rev) = @_;
2605 return undef unless $self->follow_parent;
2606 unless (defined $paths) {
2607 my $err_handler = $SVN::Error::handler;
2608 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2609 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2610 sub { $paths = $_[0] });
2611 $SVN::Error::handler = $err_handler;
2613 return undef unless defined $paths;
2615 # look for a parent from another branch:
2616 my @b_path_components = split m#/#, $self->{path};
2617 my @a_path_components;
2618 my $i;
2619 while (@b_path_components) {
2620 $i = $paths->{'/'.join('/', @b_path_components)};
2621 last if $i && defined $i->{copyfrom_path};
2622 unshift(@a_path_components, pop(@b_path_components));
2624 return undef unless defined $i && defined $i->{copyfrom_path};
2625 my $branch_from = $i->{copyfrom_path};
2626 if (@a_path_components) {
2627 print STDERR "branch_from: $branch_from => ";
2628 $branch_from .= '/'.join('/', @a_path_components);
2629 print STDERR $branch_from, "\n";
2631 my $r = $i->{copyfrom_rev};
2632 my $repos_root = $self->ra->{repos_root};
2633 my $url = $self->ra->{url};
2634 my $new_url = $url . $branch_from;
2635 print STDERR "Found possible branch point: ",
2636 "$new_url => ", $self->full_url, ", $r\n"
2637 unless $::_q > 1;
2638 $branch_from =~ s#^/##;
2639 my $gs = $self->other_gs($new_url, $url,
2640 $branch_from, $r, $self->{ref_id});
2641 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2643 my ($base, $head);
2644 if (!defined $r0 || !defined $parent) {
2645 ($base, $head) = parse_revision_argument(0, $r);
2646 } else {
2647 if ($r0 < $r) {
2648 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2649 0, 1, sub { $base = $_[1] - 1 });
2652 if (defined $base && $base <= $r) {
2653 $gs->fetch($base, $r);
2655 ($r0, $parent) = $gs->find_rev_before($r, 1);
2657 if (defined $r0 && defined $parent) {
2658 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2659 unless $::_q > 1;
2660 my $ed;
2661 if ($self->ra->can_do_switch) {
2662 $self->assert_index_clean($parent);
2663 print STDERR "Following parent with do_switch\n"
2664 unless $::_q > 1;
2665 # do_switch works with svn/trunk >= r22312, but that
2666 # is not included with SVN 1.4.3 (the latest version
2667 # at the moment), so we can't rely on it
2668 $self->{last_rev} = $r0;
2669 $self->{last_commit} = $parent;
2670 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2671 $gs->ra->gs_do_switch($r0, $rev, $gs,
2672 $self->full_url, $ed)
2673 or die "SVN connection failed somewhere...\n";
2674 } elsif ($self->ra->trees_match($new_url, $r0,
2675 $self->full_url, $rev)) {
2676 print STDERR "Trees match:\n",
2677 " $new_url\@$r0\n",
2678 " ${\$self->full_url}\@$rev\n",
2679 "Following parent with no changes\n"
2680 unless $::_q > 1;
2681 $self->tmp_index_do(sub {
2682 command_noisy('read-tree', $parent);
2684 $self->{last_commit} = $parent;
2685 } else {
2686 print STDERR "Following parent with do_update\n"
2687 unless $::_q > 1;
2688 $ed = SVN::Git::Fetcher->new($self);
2689 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2690 or die "SVN connection failed somewhere...\n";
2692 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2693 return $self->make_log_entry($rev, [$parent], $ed);
2695 return undef;
2698 sub do_fetch {
2699 my ($self, $paths, $rev) = @_;
2700 my $ed;
2701 my ($last_rev, @parents);
2702 if (my $lc = $self->last_commit) {
2703 # we can have a branch that was deleted, then re-added
2704 # under the same name but copied from another path, in
2705 # which case we'll have multiple parents (we don't
2706 # want to break the original ref, nor lose copypath info):
2707 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2708 push @{$log_entry->{parents}}, $lc;
2709 return $log_entry;
2711 $ed = SVN::Git::Fetcher->new($self);
2712 $last_rev = $self->{last_rev};
2713 $ed->{c} = $lc;
2714 @parents = ($lc);
2715 } else {
2716 $last_rev = $rev;
2717 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2718 return $log_entry;
2720 $ed = SVN::Git::Fetcher->new($self);
2722 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2723 die "SVN connection failed somewhere...\n";
2725 $self->make_log_entry($rev, \@parents, $ed);
2728 sub get_untracked {
2729 my ($self, $ed) = @_;
2730 my @out;
2731 my $h = $ed->{empty};
2732 foreach (sort keys %$h) {
2733 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2734 push @out, " $act: " . uri_encode($_);
2735 warn "W: $act: $_\n";
2737 foreach my $t (qw/dir_prop file_prop/) {
2738 $h = $ed->{$t} or next;
2739 foreach my $path (sort keys %$h) {
2740 my $ppath = $path eq '' ? '.' : $path;
2741 foreach my $prop (sort keys %{$h->{$path}}) {
2742 next if $SKIP_PROP{$prop};
2743 my $v = $h->{$path}->{$prop};
2744 my $t_ppath_prop = "$t: " .
2745 uri_encode($ppath) . ' ' .
2746 uri_encode($prop);
2747 if (defined $v) {
2748 push @out, " +$t_ppath_prop " .
2749 uri_encode($v);
2750 } else {
2751 push @out, " -$t_ppath_prop";
2756 foreach my $t (qw/absent_file absent_directory/) {
2757 $h = $ed->{$t} or next;
2758 foreach my $parent (sort keys %$h) {
2759 foreach my $path (sort @{$h->{$parent}}) {
2760 push @out, " $t: " .
2761 uri_encode("$parent/$path");
2762 warn "W: $t: $parent/$path ",
2763 "Insufficient permissions?\n";
2767 \@out;
2770 # parse_svn_date(DATE)
2771 # --------------------
2772 # Given a date (in UTC) from Subversion, return a string in the format
2773 # "<TZ Offset> <local date/time>" that Git will use.
2775 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2776 # is true we'll convert it to the local timezone instead.
2777 sub parse_svn_date {
2778 my $date = shift || return '+0000 1970-01-01 00:00:00';
2779 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2780 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2781 croak "Unable to parse date: $date\n";
2782 my $parsed_date; # Set next.
2784 if ($Git::SVN::_localtime) {
2785 # Translate the Subversion datetime to an epoch time.
2786 # Begin by switching ourselves to $date's timezone, UTC.
2787 my $old_env_TZ = $ENV{TZ};
2788 $ENV{TZ} = 'UTC';
2790 my $epoch_in_UTC =
2791 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2793 # Determine our local timezone (including DST) at the
2794 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2795 # value of TZ, if any, at the time we were run.
2796 if (defined $Git::SVN::Log::TZ) {
2797 $ENV{TZ} = $Git::SVN::Log::TZ;
2798 } else {
2799 delete $ENV{TZ};
2802 my $our_TZ =
2803 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2805 # This converts $epoch_in_UTC into our local timezone.
2806 my ($sec, $min, $hour, $mday, $mon, $year,
2807 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2809 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2810 $our_TZ, $year + 1900, $mon + 1,
2811 $mday, $hour, $min, $sec);
2813 # Reset us to the timezone in effect when we entered
2814 # this routine.
2815 if (defined $old_env_TZ) {
2816 $ENV{TZ} = $old_env_TZ;
2817 } else {
2818 delete $ENV{TZ};
2820 } else {
2821 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2824 return $parsed_date;
2827 sub other_gs {
2828 my ($self, $new_url, $url,
2829 $branch_from, $r, $old_ref_id) = @_;
2830 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2831 unless ($gs) {
2832 my $ref_id = $old_ref_id;
2833 $ref_id =~ s/\@\d+$//;
2834 $ref_id .= "\@$r";
2835 # just grow a tail if we're not unique enough :x
2836 $ref_id .= '-' while find_ref($ref_id);
2837 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2838 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2839 if ($u =~ s#^\Q$url\E(/|$)##) {
2840 $p = $u;
2841 $u = $url;
2842 $repo_id = $self->{repo_id};
2844 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2849 sub call_authors_prog {
2850 my ($orig_author) = @_;
2851 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2852 my $author = `$::_authors_prog $orig_author`;
2853 if ($? != 0) {
2854 die "$::_authors_prog failed with exit code $?\n"
2856 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2857 my ($name, $email) = ($1, $2);
2858 $email = undef if length $2 == 0;
2859 return [$name, $email];
2860 } else {
2861 die "Author: $orig_author: $::_authors_prog returned "
2862 . "invalid author format: $author\n";
2866 sub check_author {
2867 my ($author) = @_;
2868 if (!defined $author || length $author == 0) {
2869 $author = '(no author)';
2871 if (!defined $::users{$author}) {
2872 if (defined $::_authors_prog) {
2873 $::users{$author} = call_authors_prog($author);
2874 } elsif (defined $::_authors) {
2875 die "Author: $author not defined in $::_authors file\n";
2878 $author;
2881 sub make_log_entry {
2882 my ($self, $rev, $parents, $ed) = @_;
2883 my $untracked = $self->get_untracked($ed);
2885 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2886 print $un "r$rev\n" or croak $!;
2887 print $un $_, "\n" foreach @$untracked;
2888 my %log_entry = ( parents => $parents || [], revision => $rev,
2889 log => '');
2891 my $headrev;
2892 my $logged = delete $self->{logged_rev_props};
2893 if (!$logged || $self->{-want_revprops}) {
2894 my $rp = $self->ra->rev_proplist($rev);
2895 foreach (sort keys %$rp) {
2896 my $v = $rp->{$_};
2897 if (/^svn:(author|date|log)$/) {
2898 $log_entry{$1} = $v;
2899 } elsif ($_ eq 'svm:headrev') {
2900 $headrev = $v;
2901 } else {
2902 print $un " rev_prop: ", uri_encode($_), ' ',
2903 uri_encode($v), "\n";
2906 } else {
2907 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2909 close $un or croak $!;
2911 $log_entry{date} = parse_svn_date($log_entry{date});
2912 $log_entry{log} .= "\n";
2913 my $author = $log_entry{author} = check_author($log_entry{author});
2914 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2915 : ($author, undef);
2917 my ($commit_name, $commit_email) = ($name, $email);
2918 if ($_use_log_author) {
2919 my $name_field;
2920 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2921 $name_field = $1;
2922 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2923 $name_field = $1;
2925 if (!defined $name_field) {
2926 if (!defined $email) {
2927 $email = $name;
2929 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2930 ($name, $email) = ($1, $2);
2931 } elsif ($name_field =~ /(.*)@/) {
2932 ($name, $email) = ($1, $name_field);
2933 } else {
2934 ($name, $email) = ($name_field, $name_field);
2937 if (defined $headrev && $self->use_svm_props) {
2938 if ($self->rewrite_root) {
2939 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2940 "options set!\n";
2942 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
2943 # we don't want "SVM: initializing mirror for junk" ...
2944 return undef if $r == 0;
2945 my $svm = $self->svm;
2946 if ($uuid ne $svm->{uuid}) {
2947 die "UUID mismatch on SVM path:\n",
2948 "expected: $svm->{uuid}\n",
2949 " got: $uuid\n";
2951 my $full_url = $self->full_url;
2952 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2953 die "Failed to replace '$svm->{replace}' with ",
2954 "'$svm->{source}' in $full_url\n";
2955 # throw away username for storing in records
2956 remove_username($full_url);
2957 $log_entry{metadata} = "$full_url\@$r $uuid";
2958 $log_entry{svm_revision} = $r;
2959 $email ||= "$author\@$uuid";
2960 $commit_email ||= "$author\@$uuid";
2961 } elsif ($self->use_svnsync_props) {
2962 my $full_url = $self->svnsync->{url};
2963 $full_url .= "/$self->{path}" if length $self->{path};
2964 remove_username($full_url);
2965 my $uuid = $self->svnsync->{uuid};
2966 $log_entry{metadata} = "$full_url\@$rev $uuid";
2967 $email ||= "$author\@$uuid";
2968 $commit_email ||= "$author\@$uuid";
2969 } else {
2970 my $url = $self->metadata_url;
2971 remove_username($url);
2972 $log_entry{metadata} = "$url\@$rev " .
2973 $self->ra->get_uuid;
2974 $email ||= "$author\@" . $self->ra->get_uuid;
2975 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2977 $log_entry{name} = $name;
2978 $log_entry{email} = $email;
2979 $log_entry{commit_name} = $commit_name;
2980 $log_entry{commit_email} = $commit_email;
2981 \%log_entry;
2984 sub fetch {
2985 my ($self, $min_rev, $max_rev, @parents) = @_;
2986 my ($last_rev, $last_commit) = $self->last_rev_commit;
2987 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2988 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2991 sub set_tree_cb {
2992 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2993 $self->{inject_parents} = { $rev => $tree };
2994 $self->fetch(undef, undef);
2997 sub set_tree {
2998 my ($self, $tree) = (shift, shift);
2999 my $log_entry = ::get_commit_entry($tree);
3000 unless ($self->{last_rev}) {
3001 ::fatal("Must have an existing revision to commit");
3003 my %ed_opts = ( r => $self->{last_rev},
3004 log => $log_entry->{log},
3005 ra => $self->ra,
3006 tree_a => $self->{last_commit},
3007 tree_b => $tree,
3008 editor_cb => sub {
3009 $self->set_tree_cb($log_entry, $tree, @_) },
3010 svn_path => $self->{path} );
3011 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3012 print "No changes\nr$self->{last_rev} = $tree\n";
3016 sub rebuild_from_rev_db {
3017 my ($self, $path) = @_;
3018 my $r = -1;
3019 open my $fh, '<', $path or croak "open: $!";
3020 binmode $fh or croak "binmode: $!";
3021 while (<$fh>) {
3022 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3023 chomp($_);
3024 ++$r;
3025 next if $_ eq ('0' x 40);
3026 $self->rev_map_set($r, $_);
3027 print "r$r = $_\n";
3029 close $fh or croak "close: $!";
3030 unlink $path or croak "unlink: $!";
3033 sub rebuild {
3034 my ($self) = @_;
3035 my $map_path = $self->map_path;
3036 my $partial = (-e $map_path && ! -z $map_path);
3037 return unless ::verify_ref($self->refname.'^0');
3038 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3039 my $rev_db = $self->rev_db_path;
3040 $self->rebuild_from_rev_db($rev_db);
3041 if ($self->use_svm_props) {
3042 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3043 $self->rebuild_from_rev_db($svm_rev_db);
3045 $self->unlink_rev_db_symlink;
3046 return;
3048 print "Rebuilding $map_path ...\n" if (!$partial);
3049 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3050 (undef, undef));
3051 my ($log, $ctx) =
3052 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3053 ($head ? "$head.." : "") . $self->refname,
3054 '--');
3055 my $metadata_url = $self->metadata_url;
3056 remove_username($metadata_url);
3057 my $svn_uuid = $self->ra_uuid;
3058 my $c;
3059 while (<$log>) {
3060 if ( m{^commit ($::sha1)$} ) {
3061 $c = $1;
3062 next;
3064 next unless s{^\s*(git-svn-id:)}{$1};
3065 my ($url, $rev, $uuid) = ::extract_metadata($_);
3066 remove_username($url);
3068 # ignore merges (from set-tree)
3069 next if (!defined $rev || !$uuid);
3071 # if we merged or otherwise started elsewhere, this is
3072 # how we break out of it
3073 if (($uuid ne $svn_uuid) ||
3074 ($metadata_url && $url && ($url ne $metadata_url))) {
3075 next;
3077 if ($partial && $head) {
3078 print "Partial-rebuilding $map_path ...\n";
3079 print "Currently at $base_rev = $head\n";
3080 $head = undef;
3083 $self->rev_map_set($rev, $c);
3084 print "r$rev = $c\n";
3086 command_close_pipe($log, $ctx);
3087 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3088 my $rev_db_path = $self->rev_db_path;
3089 if (-f $self->rev_db_path) {
3090 unlink $self->rev_db_path or croak "unlink: $!";
3092 $self->unlink_rev_db_symlink;
3095 # rev_map:
3096 # Tie::File seems to be prone to offset errors if revisions get sparse,
3097 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3098 # one of my favorite modules is out :< Next up would be one of the DBM
3099 # modules, but I'm not sure which is most portable...
3101 # This is the replacement for the rev_db format, which was too big
3102 # and inefficient for large repositories with a lot of sparse history
3103 # (mainly tags)
3105 # The format is this:
3106 # - 24 bytes for every record,
3107 # * 4 bytes for the integer representing an SVN revision number
3108 # * 20 bytes representing the sha1 of a git commit
3109 # - No empty padding records like the old format
3110 # (except the last record, which can be overwritten)
3111 # - new records are written append-only since SVN revision numbers
3112 # increase monotonically
3113 # - lookups on SVN revision number are done via a binary search
3114 # - Piping the file to xxd -c24 is a good way of dumping it for
3115 # viewing or editing (piped back through xxd -r), should the need
3116 # ever arise.
3117 # - The last record can be padding revision with an all-zero sha1
3118 # This is used to optimize fetch performance when using multiple
3119 # "fetch" directives in .git/config
3121 # These files are disposable unless noMetadata or useSvmProps is set
3123 sub _rev_map_set {
3124 my ($fh, $rev, $commit) = @_;
3126 binmode $fh or croak "binmode: $!";
3127 my $size = (stat($fh))[7];
3128 ($size % 24) == 0 or croak "inconsistent size: $size";
3130 my $wr_offset = 0;
3131 if ($size > 0) {
3132 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3133 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3134 $read == 24 or croak "read only $read bytes (!= 24)";
3135 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3136 if ($last_commit eq ('0' x40)) {
3137 if ($size >= 48) {
3138 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3139 $read = sysread($fh, $buf, 24) or
3140 croak "read: $!";
3141 $read == 24 or
3142 croak "read only $read bytes (!= 24)";
3143 ($last_rev, $last_commit) =
3144 unpack(rev_map_fmt, $buf);
3145 if ($last_commit eq ('0' x40)) {
3146 croak "inconsistent .rev_map\n";
3149 if ($last_rev >= $rev) {
3150 croak "last_rev is higher!: $last_rev >= $rev";
3152 $wr_offset = -24;
3155 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3156 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3157 croak "write: $!";
3160 sub _rev_map_reset {
3161 my ($fh, $rev, $commit) = @_;
3162 my $c = _rev_map_get($fh, $rev);
3163 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3164 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3165 truncate $fh, $offset or croak "truncate: $!";
3168 sub mkfile {
3169 my ($path) = @_;
3170 unless (-e $path) {
3171 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3172 mkpath([$dir]) unless -d $dir;
3173 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3174 close $fh or die "Couldn't close (create) $path: $!\n";
3178 sub rev_map_set {
3179 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3180 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3181 my $db = $self->map_path($uuid);
3182 my $db_lock = "$db.lock";
3183 my $sig;
3184 $update_ref ||= 0;
3185 if ($update_ref) {
3186 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3187 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3189 mkfile($db);
3191 $LOCKFILES{$db_lock} = 1;
3192 my $sync;
3193 # both of these options make our .rev_db file very, very important
3194 # and we can't afford to lose it because rebuild() won't work
3195 if ($self->use_svm_props || $self->no_metadata) {
3196 $sync = 1;
3197 copy($db, $db_lock) or die "rev_map_set(@_): ",
3198 "Failed to copy: ",
3199 "$db => $db_lock ($!)\n";
3200 } else {
3201 rename $db, $db_lock or die "rev_map_set(@_): ",
3202 "Failed to rename: ",
3203 "$db => $db_lock ($!)\n";
3206 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3207 or croak "Couldn't open $db_lock: $!\n";
3208 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3209 _rev_map_set($fh, $rev, $commit);
3210 if ($sync) {
3211 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3212 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3214 close $fh or croak $!;
3215 if ($update_ref) {
3216 $_head = $self;
3217 my $note = "";
3218 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3219 command_noisy('update-ref', '-m', "r$rev$note",
3220 $self->refname, $commit);
3222 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3223 "$db_lock => $db ($!)\n";
3224 delete $LOCKFILES{$db_lock};
3225 if ($update_ref) {
3226 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3227 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3228 kill $sig, $$ if defined $sig;
3232 # If want_commit, this will return an array of (rev, commit) where
3233 # commit _must_ be a valid commit in the archive.
3234 # Otherwise, it'll return the max revision (whether or not the
3235 # commit is valid or just a 0x40 placeholder).
3236 sub rev_map_max {
3237 my ($self, $want_commit) = @_;
3238 $self->rebuild;
3239 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3240 $want_commit ? ($r, $c) : $r;
3243 sub rev_map_max_norebuild {
3244 my ($self, $want_commit) = @_;
3245 my $map_path = $self->map_path;
3246 stat $map_path or return $want_commit ? (0, undef) : 0;
3247 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3248 binmode $fh or croak "binmode: $!";
3249 my $size = (stat($fh))[7];
3250 ($size % 24) == 0 or croak "inconsistent size: $size";
3252 if ($size == 0) {
3253 close $fh or croak "close: $!";
3254 return $want_commit ? (0, undef) : 0;
3257 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3258 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3259 my ($r, $c) = unpack(rev_map_fmt, $buf);
3260 if ($want_commit && $c eq ('0' x40)) {
3261 if ($size < 48) {
3262 return $want_commit ? (0, undef) : 0;
3264 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3265 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3266 ($r, $c) = unpack(rev_map_fmt, $buf);
3267 if ($c eq ('0'x40)) {
3268 croak "Penultimate record is all-zeroes in $map_path";
3271 close $fh or croak "close: $!";
3272 $want_commit ? ($r, $c) : $r;
3275 sub rev_map_get {
3276 my ($self, $rev, $uuid) = @_;
3277 my $map_path = $self->map_path($uuid);
3278 return undef unless -e $map_path;
3280 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3281 my $c = _rev_map_get($fh, $rev);
3282 close($fh) or croak "close: $!";
3286 sub _rev_map_get {
3287 my ($fh, $rev) = @_;
3289 binmode $fh or croak "binmode: $!";
3290 my $size = (stat($fh))[7];
3291 ($size % 24) == 0 or croak "inconsistent size: $size";
3293 if ($size == 0) {
3294 return undef;
3297 my ($l, $u) = (0, $size - 24);
3298 my ($r, $c, $buf);
3300 while ($l <= $u) {
3301 my $i = int(($l/24 + $u/24) / 2) * 24;
3302 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3303 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3304 my ($r, $c) = unpack(rev_map_fmt, $buf);
3306 if ($r < $rev) {
3307 $l = $i + 24;
3308 } elsif ($r > $rev) {
3309 $u = $i - 24;
3310 } else { # $r == $rev
3311 return $c eq ('0' x 40) ? undef : $c;
3314 undef;
3317 # Finds the first svn revision that exists on (if $eq_ok is true) or
3318 # before $rev for the current branch. It will not search any lower
3319 # than $min_rev. Returns the git commit hash and svn revision number
3320 # if found, else (undef, undef).
3321 sub find_rev_before {
3322 my ($self, $rev, $eq_ok, $min_rev) = @_;
3323 --$rev unless $eq_ok;
3324 $min_rev ||= 1;
3325 my $max_rev = $self->rev_map_max;
3326 $rev = $max_rev if ($rev > $max_rev);
3327 while ($rev >= $min_rev) {
3328 if (my $c = $self->rev_map_get($rev)) {
3329 return ($rev, $c);
3331 --$rev;
3333 return (undef, undef);
3336 # Finds the first svn revision that exists on (if $eq_ok is true) or
3337 # after $rev for the current branch. It will not search any higher
3338 # than $max_rev. Returns the git commit hash and svn revision number
3339 # if found, else (undef, undef).
3340 sub find_rev_after {
3341 my ($self, $rev, $eq_ok, $max_rev) = @_;
3342 ++$rev unless $eq_ok;
3343 $max_rev ||= $self->rev_map_max;
3344 while ($rev <= $max_rev) {
3345 if (my $c = $self->rev_map_get($rev)) {
3346 return ($rev, $c);
3348 ++$rev;
3350 return (undef, undef);
3353 sub _new {
3354 my ($class, $repo_id, $ref_id, $path) = @_;
3355 unless (defined $repo_id && length $repo_id) {
3356 $repo_id = $Git::SVN::default_repo_id;
3358 unless (defined $ref_id && length $ref_id) {
3359 $_prefix = '' unless defined($_prefix);
3360 $_[2] = $ref_id =
3361 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3363 $_[1] = $repo_id;
3364 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3366 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3367 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3368 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3369 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3370 if (-d $old_dir && ! -d $dir) {
3371 $dir = $old_dir;
3375 $_[3] = $path = '' unless (defined $path);
3376 mkpath([$dir]);
3377 bless {
3378 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3379 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3380 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3383 # for read-only access of old .rev_db formats
3384 sub unlink_rev_db_symlink {
3385 my ($self) = @_;
3386 my $link = $self->rev_db_path;
3387 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3388 if (-l $link) {
3389 unlink $link or croak "unlink: $link failed!";
3393 sub rev_db_path {
3394 my ($self, $uuid) = @_;
3395 my $db_path = $self->map_path($uuid);
3396 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3397 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3398 $db_path;
3401 # the new replacement for .rev_db
3402 sub map_path {
3403 my ($self, $uuid) = @_;
3404 $uuid ||= $self->ra_uuid;
3405 "$self->{map_root}.$uuid";
3408 sub uri_encode {
3409 my ($f) = @_;
3410 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3414 sub remove_username {
3415 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3418 package Git::SVN::Prompt;
3419 use strict;
3420 use warnings;
3421 require SVN::Core;
3422 use vars qw/$_no_auth_cache $_username/;
3424 sub simple {
3425 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3426 $may_save = undef if $_no_auth_cache;
3427 $default_username = $_username if defined $_username;
3428 if (defined $default_username && length $default_username) {
3429 if (defined $realm && length $realm) {
3430 print STDERR "Authentication realm: $realm\n";
3431 STDERR->flush;
3433 $cred->username($default_username);
3434 } else {
3435 username($cred, $realm, $may_save, $pool);
3437 $cred->password(_read_password("Password for '" .
3438 $cred->username . "': ", $realm));
3439 $cred->may_save($may_save);
3440 $SVN::_Core::SVN_NO_ERROR;
3443 sub ssl_server_trust {
3444 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3445 $may_save = undef if $_no_auth_cache;
3446 print STDERR "Error validating server certificate for '$realm':\n";
3448 no warnings 'once';
3449 # All variables SVN::Auth::SSL::* are used only once,
3450 # so we're shutting up Perl warnings about this.
3451 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3452 print STDERR " - The certificate is not issued ",
3453 "by a trusted authority. Use the\n",
3454 " fingerprint to validate ",
3455 "the certificate manually!\n";
3457 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3458 print STDERR " - The certificate hostname ",
3459 "does not match.\n";
3461 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3462 print STDERR " - The certificate is not yet valid.\n";
3464 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3465 print STDERR " - The certificate has expired.\n";
3467 if ($failures & $SVN::Auth::SSL::OTHER) {
3468 print STDERR " - The certificate has ",
3469 "an unknown error.\n";
3471 } # no warnings 'once'
3472 printf STDERR
3473 "Certificate information:\n".
3474 " - Hostname: %s\n".
3475 " - Valid: from %s until %s\n".
3476 " - Issuer: %s\n".
3477 " - Fingerprint: %s\n",
3478 map $cert_info->$_, qw(hostname valid_from valid_until
3479 issuer_dname fingerprint);
3480 my $choice;
3481 prompt:
3482 print STDERR $may_save ?
3483 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3484 "(R)eject or accept (t)emporarily? ";
3485 STDERR->flush;
3486 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3487 if ($choice =~ /^t$/i) {
3488 $cred->may_save(undef);
3489 } elsif ($choice =~ /^r$/i) {
3490 return -1;
3491 } elsif ($may_save && $choice =~ /^p$/i) {
3492 $cred->may_save($may_save);
3493 } else {
3494 goto prompt;
3496 $cred->accepted_failures($failures);
3497 $SVN::_Core::SVN_NO_ERROR;
3500 sub ssl_client_cert {
3501 my ($cred, $realm, $may_save, $pool) = @_;
3502 $may_save = undef if $_no_auth_cache;
3503 print STDERR "Client certificate filename: ";
3504 STDERR->flush;
3505 chomp(my $filename = <STDIN>);
3506 $cred->cert_file($filename);
3507 $cred->may_save($may_save);
3508 $SVN::_Core::SVN_NO_ERROR;
3511 sub ssl_client_cert_pw {
3512 my ($cred, $realm, $may_save, $pool) = @_;
3513 $may_save = undef if $_no_auth_cache;
3514 $cred->password(_read_password("Password: ", $realm));
3515 $cred->may_save($may_save);
3516 $SVN::_Core::SVN_NO_ERROR;
3519 sub username {
3520 my ($cred, $realm, $may_save, $pool) = @_;
3521 $may_save = undef if $_no_auth_cache;
3522 if (defined $realm && length $realm) {
3523 print STDERR "Authentication realm: $realm\n";
3525 my $username;
3526 if (defined $_username) {
3527 $username = $_username;
3528 } else {
3529 print STDERR "Username: ";
3530 STDERR->flush;
3531 chomp($username = <STDIN>);
3533 $cred->username($username);
3534 $cred->may_save($may_save);
3535 $SVN::_Core::SVN_NO_ERROR;
3538 sub _read_password {
3539 my ($prompt, $realm) = @_;
3540 print STDERR $prompt;
3541 STDERR->flush;
3542 require Term::ReadKey;
3543 Term::ReadKey::ReadMode('noecho');
3544 my $password = '';
3545 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3546 last if $key =~ /[\012\015]/; # \n\r
3547 $password .= $key;
3549 Term::ReadKey::ReadMode('restore');
3550 print STDERR "\n";
3551 STDERR->flush;
3552 $password;
3555 package SVN::Git::Fetcher;
3556 use vars qw/@ISA/;
3557 use strict;
3558 use warnings;
3559 use Carp qw/croak/;
3560 use File::Temp qw/tempfile/;
3561 use IO::File qw//;
3562 use vars qw/$_ignore_regex/;
3564 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3565 sub new {
3566 my ($class, $git_svn, $switch_path) = @_;
3567 my $self = SVN::Delta::Editor->new;
3568 bless $self, $class;
3569 if (exists $git_svn->{last_commit}) {
3570 $self->{c} = $git_svn->{last_commit};
3571 $self->{empty_symlinks} =
3572 _mark_empty_symlinks($git_svn, $switch_path);
3574 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3575 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3576 $self->{empty} = {};
3577 $self->{dir_prop} = {};
3578 $self->{file_prop} = {};
3579 $self->{absent_dir} = {};
3580 $self->{absent_file} = {};
3581 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3582 $self;
3585 # this uses the Ra object, so it must be called before do_{switch,update},
3586 # not inside them (when the Git::SVN::Fetcher object is passed) to
3587 # do_{switch,update}
3588 sub _mark_empty_symlinks {
3589 my ($git_svn, $switch_path) = @_;
3590 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3591 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3593 my %ret;
3594 my ($rev, $cmt) = $git_svn->last_rev_commit;
3595 return {} unless ($rev && $cmt);
3597 # allow the warning to be printed for each revision we fetch to
3598 # ensure the user sees it. The user can also disable the workaround
3599 # on the repository even while git svn is running and the next
3600 # revision fetched will skip this expensive function.
3601 my $printed_warning;
3602 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3603 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3604 local $/ = "\0";
3605 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3606 $pfx .= '/' if length($pfx);
3607 while (<$ls>) {
3608 chomp;
3609 s/\A100644 blob $empty_blob\t//o or next;
3610 unless ($printed_warning) {
3611 print STDERR "Scanning for empty symlinks, ",
3612 "this may take a while if you have ",
3613 "many empty files\n",
3614 "You may disable this with `",
3615 "git config svn.brokenSymlinkWorkaround ",
3616 "false'.\n",
3617 "This may be done in a different ",
3618 "terminal without restarting ",
3619 "git svn\n";
3620 $printed_warning = 1;
3622 my $path = $_;
3623 my (undef, $props) =
3624 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3625 if ($props->{'svn:special'}) {
3626 $ret{$path} = 1;
3629 command_close_pipe($ls, $ctx);
3630 \%ret;
3633 # returns true if a given path is inside a ".git" directory
3634 sub in_dot_git {
3635 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3638 # return value: 0 -- don't ignore, 1 -- ignore
3639 sub is_path_ignored {
3640 my ($self, $path) = @_;
3641 return 1 if in_dot_git($path);
3642 return 1 if defined($self->{ignore_regex}) &&
3643 $path =~ m!$self->{ignore_regex}!;
3644 return 0 unless defined($_ignore_regex);
3645 return 1 if $path =~ m!$_ignore_regex!o;
3646 return 0;
3649 sub set_path_strip {
3650 my ($self, $path) = @_;
3651 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;