run_command: report failure to execute the program, but optionally don't
[git/dscho.git] / git-svn.perl
blobd1af1a3d2f1e24c068e227f847ccceb7e156ad0d
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file, $_branch_dest,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, @_tags, @_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
99 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'destination|d=s' => \$_branch_dest,
145 'dry-run|n' => \$_dry_run,
146 'tag|t' => \$_tag } ],
147 tag => [ sub { $_tag = 1; cmd_branch(@_) },
148 'Create a tag in the SVN repository',
149 { 'message|m=s' => \$_message,
150 'destination|d=s' => \$_branch_dest,
151 'dry-run|n' => \$_dry_run } ],
152 'set-tree' => [ \&cmd_set_tree,
153 "Set an SVN repository to a git tree-ish",
154 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
155 'create-ignore' => [ \&cmd_create_ignore,
156 'Create a .gitignore per svn:ignore',
157 { 'revision|r=i' => \$_revision
158 } ],
159 'propget' => [ \&cmd_propget,
160 'Print the value of a property on a file or directory',
161 { 'revision|r=i' => \$_revision } ],
162 'proplist' => [ \&cmd_proplist,
163 'List all properties of a file or directory',
164 { 'revision|r=i' => \$_revision } ],
165 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
166 { 'revision|r=i' => \$_revision
167 } ],
168 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
169 { 'revision|r=i' => \$_revision
170 } ],
171 'multi-fetch' => [ \&cmd_multi_fetch,
172 "Deprecated alias for $0 fetch --all",
173 { 'revision|r=s' => \$_revision, %fc_opts } ],
174 'migrate' => [ sub { },
175 # no-op, we automatically run this anyways,
176 'Migrate configuration/metadata/layout from
177 previous versions of git-svn',
178 { 'minimize' => \$Git::SVN::Migration::_minimize,
179 %remote_opts } ],
180 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
181 { 'limit=i' => \$Git::SVN::Log::limit,
182 'revision|r=s' => \$_revision,
183 'verbose|v' => \$Git::SVN::Log::verbose,
184 'incremental' => \$Git::SVN::Log::incremental,
185 'oneline' => \$Git::SVN::Log::oneline,
186 'show-commit' => \$Git::SVN::Log::show_commit,
187 'non-recursive' => \$Git::SVN::Log::non_recursive,
188 'authors-file|A=s' => \$_authors,
189 'color' => \$Git::SVN::Log::color,
190 'pager=s' => \$Git::SVN::Log::pager
191 } ],
192 'find-rev' => [ \&cmd_find_rev,
193 "Translate between SVN revision numbers and tree-ish",
194 {} ],
195 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
196 { 'merge|m|M' => \$_merge,
197 'verbose|v' => \$_verbose,
198 'strategy|s=s' => \$_strategy,
199 'local|l' => \$_local,
200 'fetch-all|all' => \$_fetch_all,
201 'dry-run|n' => \$_dry_run,
202 %fc_opts } ],
203 'commit-diff' => [ \&cmd_commit_diff,
204 'Commit a diff between two trees',
205 { 'message|m=s' => \$_message,
206 'file|F=s' => \$_file,
207 'revision|r=s' => \$_revision,
208 %cmt_opts } ],
209 'info' => [ \&cmd_info,
210 "Show info about the latest SVN revision
211 on the current branch",
212 { 'url' => \$_url, } ],
213 'blame' => [ \&Git::SVN::Log::cmd_blame,
214 "Show what revision and author last modified each line of a file",
215 { 'git-format' => \$_git_format } ],
216 'reset' => [ \&cmd_reset,
217 "Undo fetches back to the specified SVN revision",
218 { 'revision|r=s' => \$_revision,
219 'parent|p' => \$_fetch_parent } ],
222 my $cmd;
223 for (my $i = 0; $i < @ARGV; $i++) {
224 if (defined $cmd{$ARGV[$i]}) {
225 $cmd = $ARGV[$i];
226 splice @ARGV, $i, 1;
227 last;
228 } elsif ($ARGV[$i] eq 'help') {
229 $cmd = $ARGV[$i+1];
230 usage(0);
234 # make sure we're always running at the top-level working directory
235 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
236 unless (-d $ENV{GIT_DIR}) {
237 if ($git_dir_user_set) {
238 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
239 "but it is not a directory\n";
241 my $git_dir = delete $ENV{GIT_DIR};
242 my $cdup = undef;
243 git_cmd_try {
244 $cdup = command_oneline(qw/rev-parse --show-cdup/);
245 $git_dir = '.' unless ($cdup);
246 chomp $cdup if ($cdup);
247 $cdup = "." unless ($cdup && length $cdup);
248 } "Already at toplevel, but $git_dir not found\n";
249 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
250 unless (-d $git_dir) {
251 die "$git_dir still not found after going to ",
252 "'$cdup'\n";
254 $ENV{GIT_DIR} = $git_dir;
256 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
259 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
261 read_repo_config(\%opts);
262 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
263 Getopt::Long::Configure('pass_through');
265 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
266 'minimize-connections' => \$Git::SVN::Migration::_minimize,
267 'id|i=s' => \$Git::SVN::default_ref_id,
268 'svn-remote|remote|R=s' => sub {
269 $Git::SVN::no_reuse_existing = 1;
270 $Git::SVN::default_repo_id = $_[1] });
271 exit 1 if (!$rv && $cmd && $cmd ne 'log');
273 usage(0) if $_help;
274 version() if $_version;
275 usage(1) unless defined $cmd;
276 load_authors() if $_authors;
277 if (defined $_authors_prog) {
278 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
281 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
282 Git::SVN::Migration::migration_check();
284 Git::SVN::init_vars();
285 eval {
286 Git::SVN::verify_remotes_sanity();
287 $cmd{$cmd}->[0]->(@ARGV);
289 fatal $@ if $@;
290 post_fetch_checkout();
291 exit 0;
293 ####################### primary functions ######################
294 sub usage {
295 my $exit = shift || 0;
296 my $fd = $exit ? \*STDERR : \*STDOUT;
297 print $fd <<"";
298 git-svn - bidirectional operations between a single Subversion tree and git
299 Usage: git svn <command> [options] [arguments]\n
301 print $fd "Available commands:\n" unless $cmd;
303 foreach (sort keys %cmd) {
304 next if $cmd && $cmd ne $_;
305 next if /^multi-/; # don't show deprecated commands
306 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
307 foreach (sort keys %{$cmd{$_}->[2]}) {
308 # mixed-case options are for .git/config only
309 next if /[A-Z]/ && /^[a-z]+$/i;
310 # prints out arguments as they should be passed:
311 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
312 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
313 "--$_" : "-$_" }
314 split /\|/,$_)," $x\n";
317 print $fd <<"";
318 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
319 arbitrary identifier if you're tracking multiple SVN branches/repositories in
320 one git repository and want to keep them separate. See git-svn(1) for more
321 information.
323 exit $exit;
326 sub version {
327 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
328 exit 0;
331 sub do_git_init_db {
332 unless (-d $ENV{GIT_DIR}) {
333 my @init_db = ('init');
334 push @init_db, "--template=$_template" if defined $_template;
335 if (defined $_shared) {
336 if ($_shared =~ /[a-z]/) {
337 push @init_db, "--shared=$_shared";
338 } else {
339 push @init_db, "--shared";
342 command_noisy(@init_db);
343 $_repository = Git->repository(Repository => ".git");
345 command_noisy('config', 'core.autocrlf', 'false');
346 my $set;
347 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
348 foreach my $i (keys %icv) {
349 die "'$set' and '$i' cannot both be set\n" if $set;
350 next unless defined $icv{$i};
351 command_noisy('config', "$pfx.$i", $icv{$i});
352 $set = $i;
354 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
355 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
356 if defined $$ignore_regex;
359 sub init_subdir {
360 my $repo_path = shift or return;
361 mkpath([$repo_path]) unless -d $repo_path;
362 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
363 $ENV{GIT_DIR} = '.git';
364 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
367 sub cmd_clone {
368 my ($url, $path) = @_;
369 if (!defined $path &&
370 (defined $_trunk || @_branches || @_tags ||
371 defined $_stdlayout) &&
372 $url !~ m#^[a-z\+]+://#) {
373 $path = $url;
375 $path = basename($url) if !defined $path || !length $path;
376 cmd_init($url, $path);
377 Git::SVN::fetch_all($Git::SVN::default_repo_id);
378 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
381 sub cmd_init {
382 if (defined $_stdlayout) {
383 $_trunk = 'trunk' if (!defined $_trunk);
384 @_tags = 'tags' if (! @_tags);
385 @_branches = 'branches' if (! @_branches);
387 if (defined $_trunk || @_branches || @_tags) {
388 return cmd_multi_init(@_);
390 my $url = shift or die "SVN repository location required ",
391 "as a command-line argument\n";
392 $url = canonicalize_url($url);
393 init_subdir(@_);
394 do_git_init_db();
396 Git::SVN->init($url);
399 sub cmd_fetch {
400 if (grep /^\d+=./, @_) {
401 die "'<rev>=<commit>' fetch arguments are ",
402 "no longer supported.\n";
404 my ($remote) = @_;
405 if (@_ > 1) {
406 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
408 if ($_fetch_parent) {
409 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
410 unless ($gs) {
411 die "Unable to determine upstream SVN information from ",
412 "working tree history\n";
414 # just fetch, don't checkout.
415 $_no_checkout = 'true';
416 $_fetch_all ? $gs->fetch_all : $gs->fetch;
417 } elsif ($_fetch_all) {
418 cmd_multi_fetch();
419 } else {
420 $remote ||= $Git::SVN::default_repo_id;
421 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
425 sub cmd_set_tree {
426 my (@commits) = @_;
427 if ($_stdin || !@commits) {
428 print "Reading from stdin...\n";
429 @commits = ();
430 while (<STDIN>) {
431 if (/\b($sha1_short)\b/o) {
432 unshift @commits, $1;
436 my @revs;
437 foreach my $c (@commits) {
438 my @tmp = command('rev-parse',$c);
439 if (scalar @tmp == 1) {
440 push @revs, $tmp[0];
441 } elsif (scalar @tmp > 1) {
442 push @revs, reverse(command('rev-list',@tmp));
443 } else {
444 fatal "Failed to rev-parse $c";
447 my $gs = Git::SVN->new;
448 my ($r_last, $cmt_last) = $gs->last_rev_commit;
449 $gs->fetch;
450 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
451 fatal "There are new revisions that were fetched ",
452 "and need to be merged (or acknowledged) ",
453 "before committing.\nlast rev: $r_last\n",
454 " current: $gs->{last_rev}";
456 $gs->set_tree($_) foreach @revs;
457 print "Done committing ",scalar @revs," revisions to SVN\n";
458 unlink $gs->{index};
461 sub cmd_dcommit {
462 my $head = shift;
463 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
464 'Cannot dcommit with a dirty index. Commit your changes first, '
465 . "or stash them with `git stash'.\n";
466 $head ||= 'HEAD';
468 my $old_head;
469 if ($head ne 'HEAD') {
470 $old_head = eval {
471 command_oneline([qw/symbolic-ref -q HEAD/])
473 if ($old_head) {
474 $old_head =~ s{^refs/heads/}{};
475 } else {
476 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
478 command(['checkout', $head], STDERR => 0);
481 my @refs;
482 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
483 unless ($gs) {
484 die "Unable to determine upstream SVN information from ",
485 "$head history.\nPerhaps the repository is empty.";
488 if (defined $_commit_url) {
489 $url = $_commit_url;
490 } else {
491 $url = eval { command_oneline('config', '--get',
492 "svn-remote.$gs->{repo_id}.commiturl") };
493 if (!$url) {
494 $url = $gs->full_url
498 my $last_rev = $_revision if defined $_revision;
499 if ($url) {
500 print "Committing to $url ...\n";
502 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
503 if ($_no_rebase && scalar(@$linear_refs) > 1) {
504 warn "Attempting to commit more than one change while ",
505 "--no-rebase is enabled.\n",
506 "If these changes depend on each other, re-running ",
507 "without --no-rebase may be required."
509 my $expect_url = $url;
510 Git::SVN::remove_username($expect_url);
511 while (1) {
512 my $d = shift @$linear_refs or last;
513 unless (defined $last_rev) {
514 (undef, $last_rev, undef) = cmt_metadata("$d~1");
515 unless (defined $last_rev) {
516 fatal "Unable to extract revision information ",
517 "from commit $d~1";
520 if ($_dry_run) {
521 print "diff-tree $d~1 $d\n";
522 } else {
523 my $cmt_rev;
524 my %ed_opts = ( r => $last_rev,
525 log => get_commit_entry($d)->{log},
526 ra => Git::SVN::Ra->new($url),
527 config => SVN::Core::config_get_config(
528 $Git::SVN::Ra::config_dir
530 tree_a => "$d~1",
531 tree_b => $d,
532 editor_cb => sub {
533 print "Committed r$_[0]\n";
534 $cmt_rev = $_[0];
536 svn_path => '');
537 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
538 print "No changes\n$d~1 == $d\n";
539 } elsif ($parents->{$d} && @{$parents->{$d}}) {
540 $gs->{inject_parents_dcommit}->{$cmt_rev} =
541 $parents->{$d};
543 $_fetch_all ? $gs->fetch_all : $gs->fetch;
544 $last_rev = $cmt_rev;
545 next if $_no_rebase;
547 # we always want to rebase against the current HEAD,
548 # not any head that was passed to us
549 my @diff = command('diff-tree', $d,
550 $gs->refname, '--');
551 my @finish;
552 if (@diff) {
553 @finish = rebase_cmd();
554 print STDERR "W: $d and ", $gs->refname,
555 " differ, using @finish:\n",
556 join("\n", @diff), "\n";
557 } else {
558 print "No changes between current HEAD and ",
559 $gs->refname,
560 "\nResetting to the latest ",
561 $gs->refname, "\n";
562 @finish = qw/reset --mixed/;
564 command_noisy(@finish, $gs->refname);
565 if (@diff) {
566 @refs = ();
567 my ($url_, $rev_, $uuid_, $gs_) =
568 working_head_info('HEAD', \@refs);
569 my ($linear_refs_, $parents_) =
570 linearize_history($gs_, \@refs);
571 if (scalar(@$linear_refs) !=
572 scalar(@$linear_refs_)) {
573 fatal "# of revisions changed ",
574 "\nbefore:\n",
575 join("\n", @$linear_refs),
576 "\n\nafter:\n",
577 join("\n", @$linear_refs_), "\n",
578 'If you are attempting to commit ',
579 "merges, try running:\n\t",
580 'git rebase --interactive',
581 '--preserve-merges ',
582 $gs->refname,
583 "\nBefore dcommitting";
585 if ($url_ ne $expect_url) {
586 fatal "URL mismatch after rebase: ",
587 "$url_ != $expect_url";
589 if ($uuid_ ne $uuid) {
590 fatal "uuid mismatch after rebase: ",
591 "$uuid_ != $uuid";
593 # remap parents
594 my (%p, @l, $i);
595 for ($i = 0; $i < scalar @$linear_refs; $i++) {
596 my $new = $linear_refs_->[$i] or next;
597 $p{$new} =
598 $parents->{$linear_refs->[$i]};
599 push @l, $new;
601 $parents = \%p;
602 $linear_refs = \@l;
607 if ($old_head) {
608 my $new_head = command_oneline(qw/rev-parse HEAD/);
609 my $new_is_symbolic = eval {
610 command_oneline(qw/symbolic-ref -q HEAD/);
612 if ($new_is_symbolic) {
613 print "dcommitted the branch ", $head, "\n";
614 } else {
615 print "dcommitted on a detached HEAD because you gave ",
616 "a revision argument.\n",
617 "The rewritten commit is: ", $new_head, "\n";
619 command(['checkout', $old_head], STDERR => 0);
622 unlink $gs->{index};
625 sub cmd_branch {
626 my ($branch_name, $head) = @_;
628 unless (defined $branch_name && length $branch_name) {
629 die(($_tag ? "tag" : "branch") . " name required\n");
631 $head ||= 'HEAD';
633 my ($src, $rev, undef, $gs) = working_head_info($head);
635 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
636 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
637 my $glob;
638 if ($#{$allglobs} == 0) {
639 $glob = $allglobs->[0];
640 } else {
641 unless(defined $_branch_dest) {
642 die "Multiple ",
643 $_tag ? "tag" : "branch",
644 " paths defined for Subversion repository.\n",
645 "You must specify where you want to create the ",
646 $_tag ? "tag" : "branch",
647 " with the --destination argument.\n";
649 foreach my $g (@{$allglobs}) {
650 # SVN::Git::Editor could probably be moved to Git.pm..
651 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
652 if ($_branch_dest =~ /$re/) {
653 $glob = $g;
654 last;
657 unless (defined $glob) {
658 die "Unknown ",
659 $_tag ? "tag" : "branch",
660 " destination $_branch_dest\n";
663 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
664 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
666 my $ctx = SVN::Client->new(
667 auth => Git::SVN::Ra::_auth_providers(),
668 log_msg => sub {
669 ${ $_[0] } = defined $_message
670 ? $_message
671 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
672 . $branch_name;
676 eval {
677 $ctx->ls($dst, 'HEAD', 0);
678 } and die "branch ${branch_name} already exists\n";
680 print "Copying ${src} at r${rev} to ${dst}...\n";
681 $ctx->copy($src, $rev, $dst)
682 unless $_dry_run;
684 $gs->fetch_all;
687 sub cmd_find_rev {
688 my $revision_or_hash = shift or die "SVN or git revision required ",
689 "as a command-line argument\n";
690 my $result;
691 if ($revision_or_hash =~ /^r\d+$/) {
692 my $head = shift;
693 $head ||= 'HEAD';
694 my @refs;
695 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
696 unless ($gs) {
697 die "Unable to determine upstream SVN information from ",
698 "$head history\n";
700 my $desired_revision = substr($revision_or_hash, 1);
701 $result = $gs->rev_map_get($desired_revision, $uuid);
702 } else {
703 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
704 $result = $rev;
706 print "$result\n" if $result;
709 sub cmd_rebase {
710 command_noisy(qw/update-index --refresh/);
711 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
712 unless ($gs) {
713 die "Unable to determine upstream SVN information from ",
714 "working tree history\n";
716 if ($_dry_run) {
717 print "Remote Branch: " . $gs->refname . "\n";
718 print "SVN URL: " . $url . "\n";
719 return;
721 if (command(qw/diff-index HEAD --/)) {
722 print STDERR "Cannot rebase with uncommited changes:\n";
723 command_noisy('status');
724 exit 1;
726 unless ($_local) {
727 # rebase will checkout for us, so no need to do it explicitly
728 $_no_checkout = 'true';
729 $_fetch_all ? $gs->fetch_all : $gs->fetch;
731 command_noisy(rebase_cmd(), $gs->refname);
734 sub cmd_show_ignore {
735 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
736 $gs ||= Git::SVN->new;
737 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
738 $gs->prop_walk($gs->{path}, $r, sub {
739 my ($gs, $path, $props) = @_;
740 print STDOUT "\n# $path\n";
741 my $s = $props->{'svn:ignore'} or return;
742 $s =~ s/[\r\n]+/\n/g;
743 chomp $s;
744 $s =~ s#^#$path#gm;
745 print STDOUT "$s\n";
749 sub cmd_show_externals {
750 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
751 $gs ||= Git::SVN->new;
752 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
753 $gs->prop_walk($gs->{path}, $r, sub {
754 my ($gs, $path, $props) = @_;
755 print STDOUT "\n# $path\n";
756 my $s = $props->{'svn:externals'} or return;
757 $s =~ s/[\r\n]+/\n/g;
758 chomp $s;
759 $s =~ s#^#$path#gm;
760 print STDOUT "$s\n";
764 sub cmd_create_ignore {
765 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
766 $gs ||= Git::SVN->new;
767 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
768 $gs->prop_walk($gs->{path}, $r, sub {
769 my ($gs, $path, $props) = @_;
770 # $path is of the form /path/to/dir/
771 $path = '.' . $path;
772 # SVN can have attributes on empty directories,
773 # which git won't track
774 mkpath([$path]) unless -d $path;
775 my $ignore = $path . '.gitignore';
776 my $s = $props->{'svn:ignore'} or return;
777 open(GITIGNORE, '>', $ignore)
778 or fatal("Failed to open `$ignore' for writing: $!");
779 $s =~ s/[\r\n]+/\n/g;
780 chomp $s;
781 # Prefix all patterns so that the ignore doesn't apply
782 # to sub-directories.
783 $s =~ s#^#/#gm;
784 print GITIGNORE "$s\n";
785 close(GITIGNORE)
786 or fatal("Failed to close `$ignore': $!");
787 command_noisy('add', '-f', $ignore);
791 sub canonicalize_path {
792 my ($path) = @_;
793 my $dot_slash_added = 0;
794 if (substr($path, 0, 1) ne "/") {
795 $path = "./" . $path;
796 $dot_slash_added = 1;
798 # File::Spec->canonpath doesn't collapse x/../y into y (for a
799 # good reason), so let's do this manually.
800 $path =~ s#/+#/#g;
801 $path =~ s#/\.(?:/|$)#/#g;
802 $path =~ s#/[^/]+/\.\.##g;
803 $path =~ s#/$##g;
804 $path =~ s#^\./## if $dot_slash_added;
805 $path =~ s#^/##;
806 $path =~ s#^\.$##;
807 return $path;
810 sub canonicalize_url {
811 my ($url) = @_;
812 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
813 return $url;
816 # get_svnprops(PATH)
817 # ------------------
818 # Helper for cmd_propget and cmd_proplist below.
819 sub get_svnprops {
820 my $path = shift;
821 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
822 $gs ||= Git::SVN->new;
824 # prefix THE PATH by the sub-directory from which the user
825 # invoked us.
826 $path = $cmd_dir_prefix . $path;
827 fatal("No such file or directory: $path") unless -e $path;
828 my $is_dir = -d $path ? 1 : 0;
829 $path = $gs->{path} . '/' . $path;
831 # canonicalize the path (otherwise libsvn will abort or fail to
832 # find the file)
833 $path = canonicalize_path($path);
835 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
836 my $props;
837 if ($is_dir) {
838 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
840 else {
841 (undef, $props) = $gs->ra->get_file($path, $r, undef);
843 return $props;
846 # cmd_propget (PROP, PATH)
847 # ------------------------
848 # Print the SVN property PROP for PATH.
849 sub cmd_propget {
850 my ($prop, $path) = @_;
851 $path = '.' if not defined $path;
852 usage(1) if not defined $prop;
853 my $props = get_svnprops($path);
854 if (not defined $props->{$prop}) {
855 fatal("`$path' does not have a `$prop' SVN property.");
857 print $props->{$prop} . "\n";
860 # cmd_proplist (PATH)
861 # -------------------
862 # Print the list of SVN properties for PATH.
863 sub cmd_proplist {
864 my $path = shift;
865 $path = '.' if not defined $path;
866 my $props = get_svnprops($path);
867 print "Properties on '$path':\n";
868 foreach (sort keys %{$props}) {
869 print " $_\n";
873 sub cmd_multi_init {
874 my $url = shift;
875 unless (defined $_trunk || @_branches || @_tags) {
876 usage(1);
879 # there are currently some bugs that prevent multi-init/multi-fetch
880 # setups from working well without this.
881 $Git::SVN::_minimize_url = 1;
883 $_prefix = '' unless defined $_prefix;
884 if (defined $url) {
885 $url = canonicalize_url($url);
886 init_subdir(@_);
888 do_git_init_db();
889 if (defined $_trunk) {
890 my $trunk_ref = $_prefix . 'trunk';
891 # try both old-style and new-style lookups:
892 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
893 unless ($gs_trunk) {
894 my ($trunk_url, $trunk_path) =
895 complete_svn_url($url, $_trunk);
896 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
897 undef, $trunk_ref);
900 return unless @_branches || @_tags;
901 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
902 foreach my $path (@_branches) {
903 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
905 foreach my $path (@_tags) {
906 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
910 sub cmd_multi_fetch {
911 my $remotes = Git::SVN::read_all_remotes();
912 foreach my $repo_id (sort keys %$remotes) {
913 if ($remotes->{$repo_id}->{url}) {
914 Git::SVN::fetch_all($repo_id, $remotes);
919 # this command is special because it requires no metadata
920 sub cmd_commit_diff {
921 my ($ta, $tb, $url) = @_;
922 my $usage = "Usage: $0 commit-diff -r<revision> ".
923 "<tree-ish> <tree-ish> [<URL>]";
924 fatal($usage) if (!defined $ta || !defined $tb);
925 my $svn_path = '';
926 if (!defined $url) {
927 my $gs = eval { Git::SVN->new };
928 if (!$gs) {
929 fatal("Needed URL or usable git-svn --id in ",
930 "the command-line\n", $usage);
932 $url = $gs->{url};
933 $svn_path = $gs->{path};
935 unless (defined $_revision) {
936 fatal("-r|--revision is a required argument\n", $usage);
938 if (defined $_message && defined $_file) {
939 fatal("Both --message/-m and --file/-F specified ",
940 "for the commit message.\n",
941 "I have no idea what you mean");
943 if (defined $_file) {
944 $_message = file_to_s($_file);
945 } else {
946 $_message ||= get_commit_entry($tb)->{log};
948 my $ra ||= Git::SVN::Ra->new($url);
949 my $r = $_revision;
950 if ($r eq 'HEAD') {
951 $r = $ra->get_latest_revnum;
952 } elsif ($r !~ /^\d+$/) {
953 die "revision argument: $r not understood by git-svn\n";
955 my %ed_opts = ( r => $r,
956 log => $_message,
957 ra => $ra,
958 tree_a => $ta,
959 tree_b => $tb,
960 editor_cb => sub { print "Committed r$_[0]\n" },
961 svn_path => $svn_path );
962 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
963 print "No changes\n$ta == $tb\n";
967 sub escape_uri_only {
968 my ($uri) = @_;
969 my @tmp;
970 foreach (split m{/}, $uri) {
971 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
972 push @tmp, $_;
974 join('/', @tmp);
977 sub escape_url {
978 my ($url) = @_;
979 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
980 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
981 $url = "$scheme://$domain$uri";
983 $url;
986 sub cmd_info {
987 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
988 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
989 if (exists $_[1]) {
990 die "Too many arguments specified\n";
993 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
995 if (!$file_type && !$diff_status) {
996 print STDERR "svn: '$path' is not under version control\n";
997 exit 1;
1000 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1001 unless ($gs) {
1002 die "Unable to determine upstream SVN information from ",
1003 "working tree history\n";
1006 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1007 $path = "." if $path eq "";
1009 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1011 if ($_url) {
1012 print escape_url($full_url), "\n";
1013 return;
1016 my $result = "Path: $path\n";
1017 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1018 $result .= "URL: " . escape_url($full_url) . "\n";
1020 eval {
1021 my $repos_root = $gs->repos_root;
1022 Git::SVN::remove_username($repos_root);
1023 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1025 if ($@) {
1026 $result .= "Repository Root: (offline)\n";
1028 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1029 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1030 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1032 $result .= "Node Kind: " .
1033 ($file_type eq "dir" ? "directory" : "file") . "\n";
1035 my $schedule = $diff_status eq "A"
1036 ? "add"
1037 : ($diff_status eq "D" ? "delete" : "normal");
1038 $result .= "Schedule: $schedule\n";
1040 if ($diff_status eq "A") {
1041 print $result, "\n";
1042 return;
1045 my ($lc_author, $lc_rev, $lc_date_utc);
1046 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1047 my $log = command_output_pipe(@args);
1048 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1049 while (<$log>) {
1050 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1051 $lc_author = $1;
1052 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1053 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1054 (undef, $lc_rev, undef) = ::extract_metadata($1);
1057 close $log;
1059 Git::SVN::Log::set_local_timezone();
1061 $result .= "Last Changed Author: $lc_author\n";
1062 $result .= "Last Changed Rev: $lc_rev\n";
1063 $result .= "Last Changed Date: " .
1064 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1066 if ($file_type ne "dir") {
1067 my $text_last_updated_date =
1068 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1069 $result .=
1070 "Text Last Updated: " .
1071 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1072 "\n";
1073 my $checksum;
1074 if ($diff_status eq "D") {
1075 my ($fh, $ctx) =
1076 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1077 if ($file_type eq "link") {
1078 my $file_name = <$fh>;
1079 $checksum = md5sum("link $file_name");
1080 } else {
1081 $checksum = md5sum($fh);
1083 command_close_pipe($fh, $ctx);
1084 } elsif ($file_type eq "link") {
1085 my $file_name =
1086 command(qw(cat-file blob), "HEAD:$path");
1087 $checksum =
1088 md5sum("link " . $file_name);
1089 } else {
1090 open FILE, "<", $path or die $!;
1091 $checksum = md5sum(\*FILE);
1092 close FILE or die $!;
1094 $result .= "Checksum: " . $checksum . "\n";
1097 print $result, "\n";
1100 sub cmd_reset {
1101 my $target = shift || $_revision or die "SVN revision required\n";
1102 $target = $1 if $target =~ /^r(\d+)$/;
1103 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1104 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1105 unless ($gs) {
1106 die "Unable to determine upstream SVN information from ".
1107 "history\n";
1109 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1110 $gs->rev_map_set($r, $c, 'reset', $uuid);
1111 print "r$r = $c ($gs->{ref_id})\n";
1114 ########################### utility functions #########################
1116 sub rebase_cmd {
1117 my @cmd = qw/rebase/;
1118 push @cmd, '-v' if $_verbose;
1119 push @cmd, qw/--merge/ if $_merge;
1120 push @cmd, "--strategy=$_strategy" if $_strategy;
1121 @cmd;
1124 sub post_fetch_checkout {
1125 return if $_no_checkout;
1126 my $gs = $Git::SVN::_head or return;
1127 return if verify_ref('refs/heads/master^0');
1129 my $valid_head = verify_ref('HEAD^0');
1130 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1131 return if ($valid_head || !verify_ref('HEAD^0'));
1133 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1134 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1135 return if -f $index;
1137 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1138 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1139 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1140 print STDERR "Checked out HEAD:\n ",
1141 $gs->full_url, " r", $gs->last_rev, "\n";
1144 sub complete_svn_url {
1145 my ($url, $path) = @_;
1146 $path =~ s#/+$##;
1147 if ($path !~ m#^[a-z\+]+://#) {
1148 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1149 fatal("E: '$path' is not a complete URL ",
1150 "and a separate URL is not specified");
1152 return ($url, $path);
1154 return ($path, '');
1157 sub complete_url_ls_init {
1158 my ($ra, $repo_path, $switch, $pfx) = @_;
1159 unless ($repo_path) {
1160 print STDERR "W: $switch not specified\n";
1161 return;
1163 $repo_path =~ s#/+$##;
1164 if ($repo_path =~ m#^[a-z\+]+://#) {
1165 $ra = Git::SVN::Ra->new($repo_path);
1166 $repo_path = '';
1167 } else {
1168 $repo_path =~ s#^/+##;
1169 unless ($ra) {
1170 fatal("E: '$repo_path' is not a complete URL ",
1171 "and a separate URL is not specified");
1174 my $url = $ra->{url};
1175 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1176 my $k = "svn-remote.$gs->{repo_id}.url";
1177 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1178 if ($orig_url && ($orig_url ne $gs->{url})) {
1179 die "$k already set: $orig_url\n",
1180 "wanted to set to: $gs->{url}\n";
1182 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1183 my $remote_path = "$ra->{svn_path}/$repo_path";
1184 $remote_path =~ s#/+#/#g;
1185 $remote_path =~ s#^/##g;
1186 $remote_path .= "/*" if $remote_path !~ /\*/;
1187 my ($n) = ($switch =~ /^--(\w+)/);
1188 if (length $pfx && $pfx !~ m#/$#) {
1189 die "--prefix='$pfx' must have a trailing slash '/'\n";
1191 command_noisy('config',
1192 '--add',
1193 "svn-remote.$gs->{repo_id}.$n",
1194 "$remote_path:refs/remotes/$pfx*" .
1195 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1198 sub verify_ref {
1199 my ($ref) = @_;
1200 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1201 { STDERR => 0 }); };
1204 sub get_tree_from_treeish {
1205 my ($treeish) = @_;
1206 # $treeish can be a symbolic ref, too:
1207 my $type = command_oneline(qw/cat-file -t/, $treeish);
1208 my $expected;
1209 while ($type eq 'tag') {
1210 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1212 if ($type eq 'commit') {
1213 $expected = (grep /^tree /, command(qw/cat-file commit/,
1214 $treeish))[0];
1215 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1216 die "Unable to get tree from $treeish\n" unless $expected;
1217 } elsif ($type eq 'tree') {
1218 $expected = $treeish;
1219 } else {
1220 die "$treeish is a $type, expected tree, tag or commit\n";
1222 return $expected;
1225 sub get_commit_entry {
1226 my ($treeish) = shift;
1227 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1228 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1229 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1230 open my $log_fh, '>', $commit_editmsg or croak $!;
1232 my $type = command_oneline(qw/cat-file -t/, $treeish);
1233 if ($type eq 'commit' || $type eq 'tag') {
1234 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1235 $type, $treeish);
1236 my $in_msg = 0;
1237 my $author;
1238 my $saw_from = 0;
1239 my $msgbuf = "";
1240 while (<$msg_fh>) {
1241 if (!$in_msg) {
1242 $in_msg = 1 if (/^\s*$/);
1243 $author = $1 if (/^author (.*>)/);
1244 } elsif (/^git-svn-id: /) {
1245 # skip this for now, we regenerate the
1246 # correct one on re-fetch anyways
1247 # TODO: set *:merge properties or like...
1248 } else {
1249 if (/^From:/ || /^Signed-off-by:/) {
1250 $saw_from = 1;
1252 $msgbuf .= $_;
1255 $msgbuf =~ s/\s+$//s;
1256 if ($Git::SVN::_add_author_from && defined($author)
1257 && !$saw_from) {
1258 $msgbuf .= "\n\nFrom: $author";
1260 print $log_fh $msgbuf or croak $!;
1261 command_close_pipe($msg_fh, $ctx);
1263 close $log_fh or croak $!;
1265 if ($_edit || ($type eq 'tree')) {
1266 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1267 # TODO: strip out spaces, comments, like git-commit.sh
1268 system($editor, $commit_editmsg);
1270 rename $commit_editmsg, $commit_msg or croak $!;
1272 require Encode;
1273 # SVN requires messages to be UTF-8 when entering the repo
1274 local $/;
1275 open $log_fh, '<', $commit_msg or croak $!;
1276 binmode $log_fh;
1277 chomp($log_entry{log} = <$log_fh>);
1279 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1280 my $msg = $log_entry{log};
1282 eval { $msg = Encode::decode($enc, $msg, 1) };
1283 if ($@) {
1284 die "Could not decode as $enc:\n", $msg,
1285 "\nPerhaps you need to set i18n.commitencoding\n";
1288 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1289 die "Could not encode as UTF-8:\n$msg\n" if $@;
1291 $log_entry{log} = $msg;
1293 close $log_fh or croak $!;
1295 unlink $commit_msg;
1296 \%log_entry;
1299 sub s_to_file {
1300 my ($str, $file, $mode) = @_;
1301 open my $fd,'>',$file or croak $!;
1302 print $fd $str,"\n" or croak $!;
1303 close $fd or croak $!;
1304 chmod ($mode &~ umask, $file) if (defined $mode);
1307 sub file_to_s {
1308 my $file = shift;
1309 open my $fd,'<',$file or croak "$!: file: $file\n";
1310 local $/;
1311 my $ret = <$fd>;
1312 close $fd or croak $!;
1313 $ret =~ s/\s*$//s;
1314 return $ret;
1317 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1318 sub load_authors {
1319 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1320 my $log = $cmd eq 'log';
1321 while (<$authors>) {
1322 chomp;
1323 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1324 my ($user, $name, $email) = ($1, $2, $3);
1325 if ($log) {
1326 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1327 } else {
1328 $users{$user} = [$name, $email];
1331 close $authors or croak $!;
1334 # convert GetOpt::Long specs for use by git-config
1335 sub read_repo_config {
1336 return unless -d $ENV{GIT_DIR};
1337 my $opts = shift;
1338 my @config_only;
1339 foreach my $o (keys %$opts) {
1340 # if we have mixedCase and a long option-only, then
1341 # it's a config-only variable that we don't need for
1342 # the command-line.
1343 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1344 my $v = $opts->{$o};
1345 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1346 $key =~ s/-//g;
1347 my $arg = 'git config';
1348 $arg .= ' --int' if ($o =~ /[:=]i$/);
1349 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1350 if (ref $v eq 'ARRAY') {
1351 chomp(my @tmp = `$arg --get-all svn.$key`);
1352 @$v = @tmp if @tmp;
1353 } else {
1354 chomp(my $tmp = `$arg --get svn.$key`);
1355 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1356 $$v = $tmp;
1360 delete @$opts{@config_only} if @config_only;
1363 sub extract_metadata {
1364 my $id = shift or return (undef, undef, undef);
1365 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1366 \s([a-f\d\-]+)$/x);
1367 if (!defined $rev || !$uuid || !$url) {
1368 # some of the original repositories I made had
1369 # identifiers like this:
1370 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1372 return ($url, $rev, $uuid);
1375 sub cmt_metadata {
1376 return extract_metadata((grep(/^git-svn-id: /,
1377 command(qw/cat-file commit/, shift)))[-1]);
1380 sub cmt_sha2rev_batch {
1381 my %s2r;
1382 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1383 my $list = shift;
1385 foreach my $sha (@{$list}) {
1386 my $first = 1;
1387 my $size = 0;
1388 print $out $sha, "\n";
1390 while (my $line = <$in>) {
1391 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1392 last;
1393 } elsif ($first &&
1394 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1395 $first = 0;
1396 $size = $1;
1397 next;
1398 } elsif ($line =~ /^(git-svn-id: )/) {
1399 my (undef, $rev, undef) =
1400 extract_metadata($line);
1401 $s2r{$sha} = $rev;
1404 $size -= length($line);
1405 last if ($size == 0);
1409 command_close_bidi_pipe($pid, $in, $out, $ctx);
1411 return \%s2r;
1414 sub working_head_info {
1415 my ($head, $refs) = @_;
1416 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1417 my ($fh, $ctx) = command_output_pipe(@args, $head);
1418 my $hash;
1419 my %max;
1420 while (<$fh>) {
1421 if ( m{^commit ($::sha1)$} ) {
1422 unshift @$refs, $hash if $hash and $refs;
1423 $hash = $1;
1424 next;
1426 next unless s{^\s*(git-svn-id:)}{$1};
1427 my ($url, $rev, $uuid) = extract_metadata($_);
1428 if (defined $url && defined $rev) {
1429 next if $max{$url} and $max{$url} < $rev;
1430 if (my $gs = Git::SVN->find_by_url($url)) {
1431 my $c = $gs->rev_map_get($rev, $uuid);
1432 if ($c && $c eq $hash) {
1433 close $fh; # break the pipe
1434 return ($url, $rev, $uuid, $gs);
1435 } else {
1436 $max{$url} ||= $gs->rev_map_max;
1441 command_close_pipe($fh, $ctx);
1442 (undef, undef, undef, undef);
1445 sub read_commit_parents {
1446 my ($parents, $c) = @_;
1447 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1448 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1449 @{$parents->{$c}} = split(/ /, $p);
1452 sub linearize_history {
1453 my ($gs, $refs) = @_;
1454 my %parents;
1455 foreach my $c (@$refs) {
1456 read_commit_parents(\%parents, $c);
1459 my @linear_refs;
1460 my %skip = ();
1461 my $last_svn_commit = $gs->last_commit;
1462 foreach my $c (reverse @$refs) {
1463 next if $c eq $last_svn_commit;
1464 last if $skip{$c};
1466 unshift @linear_refs, $c;
1467 $skip{$c} = 1;
1469 # we only want the first parent to diff against for linear
1470 # history, we save the rest to inject when we finalize the
1471 # svn commit
1472 my $fp_a = verify_ref("$c~1");
1473 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1474 if (!$fp_a || !$fp_b) {
1475 die "Commit $c\n",
1476 "has no parent commit, and therefore ",
1477 "nothing to diff against.\n",
1478 "You should be working from a repository ",
1479 "originally created by git-svn\n";
1481 if ($fp_a ne $fp_b) {
1482 die "$c~1 = $fp_a, however parsing commit $c ",
1483 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1486 foreach my $p (@{$parents{$c}}) {
1487 $skip{$p} = 1;
1490 (\@linear_refs, \%parents);
1493 sub find_file_type_and_diff_status {
1494 my ($path) = @_;
1495 return ('dir', '') if $path eq '';
1497 my $diff_output =
1498 command_oneline(qw(diff --cached --name-status --), $path) || "";
1499 my $diff_status = (split(' ', $diff_output))[0] || "";
1501 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1503 return (undef, undef) if !$diff_status && !$ls_tree;
1505 if ($diff_status eq "A") {
1506 return ("link", $diff_status) if -l $path;
1507 return ("dir", $diff_status) if -d $path;
1508 return ("file", $diff_status);
1511 my $mode = (split(' ', $ls_tree))[0] || "";
1513 return ("link", $diff_status) if $mode eq "120000";
1514 return ("dir", $diff_status) if $mode eq "040000";
1515 return ("file", $diff_status);
1518 sub md5sum {
1519 my $arg = shift;
1520 my $ref = ref $arg;
1521 my $md5 = Digest::MD5->new();
1522 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1523 $md5->addfile($arg) or croak $!;
1524 } elsif ($ref eq 'SCALAR') {
1525 $md5->add($$arg) or croak $!;
1526 } elsif (!$ref) {
1527 $md5->add($arg) or croak $!;
1528 } else {
1529 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1531 return $md5->hexdigest();
1534 package Git::SVN;
1535 use strict;
1536 use warnings;
1537 use Fcntl qw/:DEFAULT :seek/;
1538 use constant rev_map_fmt => 'NH40';
1539 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1540 $_repack $_repack_flags $_use_svm_props $_head
1541 $_use_svnsync_props $no_reuse_existing $_minimize_url
1542 $_use_log_author $_add_author_from $_localtime/;
1543 use Carp qw/croak/;
1544 use File::Path qw/mkpath/;
1545 use File::Copy qw/copy/;
1546 use IPC::Open3;
1548 my ($_gc_nr, $_gc_period);
1550 # properties that we do not log:
1551 my %SKIP_PROP;
1552 BEGIN {
1553 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1554 svn:special svn:executable
1555 svn:entry:committed-rev
1556 svn:entry:last-author
1557 svn:entry:uuid
1558 svn:entry:committed-date/;
1560 # some options are read globally, but can be overridden locally
1561 # per [svn-remote "..."] section. Command-line options will *NOT*
1562 # override options set in an [svn-remote "..."] section
1563 no strict 'refs';
1564 for my $option (qw/follow_parent no_metadata use_svm_props
1565 use_svnsync_props/) {
1566 my $key = $option;
1567 $key =~ tr/_//d;
1568 my $prop = "-$option";
1569 *$option = sub {
1570 my ($self) = @_;
1571 return $self->{$prop} if exists $self->{$prop};
1572 my $k = "svn-remote.$self->{repo_id}.$key";
1573 eval { command_oneline(qw/config --get/, $k) };
1574 if ($@) {
1575 $self->{$prop} = ${"Git::SVN::_$option"};
1576 } else {
1577 my $v = command_oneline(qw/config --bool/,$k);
1578 $self->{$prop} = $v eq 'false' ? 0 : 1;
1580 return $self->{$prop};
1586 my (%LOCKFILES, %INDEX_FILES);
1587 END {
1588 unlink keys %LOCKFILES if %LOCKFILES;
1589 unlink keys %INDEX_FILES if %INDEX_FILES;
1592 sub resolve_local_globs {
1593 my ($url, $fetch, $glob_spec) = @_;
1594 return unless defined $glob_spec;
1595 my $ref = $glob_spec->{ref};
1596 my $path = $glob_spec->{path};
1597 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1598 next unless m#^refs/remotes/$ref->{regex}$#;
1599 my $p = $1;
1600 my $pathname = desanitize_refname($path->full_path($p));
1601 my $refname = desanitize_refname($ref->full_path($p));
1602 if (my $existing = $fetch->{$pathname}) {
1603 if ($existing ne $refname) {
1604 die "Refspec conflict:\n",
1605 "existing: refs/remotes/$existing\n",
1606 " globbed: refs/remotes/$refname\n";
1608 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1609 $u =~ s!^\Q$url\E(/|$)!! or die
1610 "refs/remotes/$refname: '$url' not found in '$u'\n";
1611 if ($pathname ne $u) {
1612 warn "W: Refspec glob conflict ",
1613 "(ref: refs/remotes/$refname):\n",
1614 "expected path: $pathname\n",
1615 " real path: $u\n",
1616 "Continuing ahead with $u\n";
1617 next;
1619 } else {
1620 $fetch->{$pathname} = $refname;
1625 sub parse_revision_argument {
1626 my ($base, $head) = @_;
1627 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1628 return ($base, $head);
1630 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1631 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1632 return ($head, $head) if ($::_revision eq 'HEAD');
1633 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1634 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1635 die "revision argument: $::_revision not understood by git-svn\n";
1638 sub fetch_all {
1639 my ($repo_id, $remotes) = @_;
1640 if (ref $repo_id) {
1641 my $gs = $repo_id;
1642 $repo_id = undef;
1643 $repo_id = $gs->{repo_id};
1645 $remotes ||= read_all_remotes();
1646 my $remote = $remotes->{$repo_id} or
1647 die "[svn-remote \"$repo_id\"] unknown\n";
1648 my $fetch = $remote->{fetch};
1649 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1650 my (@gs, @globs);
1651 my $ra = Git::SVN::Ra->new($url);
1652 my $uuid = $ra->get_uuid;
1653 my $head = $ra->get_latest_revnum;
1654 my $base = defined $fetch ? $head : 0;
1656 # read the max revs for wildcard expansion (branches/*, tags/*)
1657 foreach my $t (qw/branches tags/) {
1658 defined $remote->{$t} or next;
1659 push @globs, @{$remote->{$t}};
1661 my $max_rev = eval { tmp_config(qw/--int --get/,
1662 "svn-remote.$repo_id.${t}-maxRev") };
1663 if (defined $max_rev && ($max_rev < $base)) {
1664 $base = $max_rev;
1665 } elsif (!defined $max_rev) {
1666 $base = 0;
1670 if ($fetch) {
1671 foreach my $p (sort keys %$fetch) {
1672 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1673 my $lr = $gs->rev_map_max;
1674 if (defined $lr) {
1675 $base = $lr if ($lr < $base);
1677 push @gs, $gs;
1681 ($base, $head) = parse_revision_argument($base, $head);
1682 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1685 sub read_all_remotes {
1686 my $r = {};
1687 my $use_svm_props = eval { command_oneline(qw/config --bool
1688 svn.useSvmProps/) };
1689 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1690 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1691 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1692 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1693 die("svn-remote.$remote: remote ref '$_remote_ref' "
1694 . "must start with 'refs/remotes/'\n")
1695 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1696 my $remote_ref = $1;
1697 $local_ref =~ s{^/}{};
1698 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1699 $r->{$remote}->{svm} = {} if $use_svm_props;
1700 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1701 $r->{$1}->{svm} = {};
1702 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1703 $r->{$1}->{url} = $2;
1704 } elsif (m!^(.+)\.(branches|tags)=
1705 (.*):refs/remotes/(.+)\s*$/!x) {
1706 my ($p, $g) = ($3, $4);
1707 my $rs = {
1708 t => $2,
1709 remote => $1,
1710 path => Git::SVN::GlobSpec->new($p),
1711 ref => Git::SVN::GlobSpec->new($g) };
1712 if (length($rs->{ref}->{right}) != 0) {
1713 die "The '*' glob character must be the last ",
1714 "character of '$g'\n";
1716 push @{ $r->{$1}->{$2} }, $rs;
1720 map {
1721 if (defined $r->{$_}->{svm}) {
1722 my $svm;
1723 eval {
1724 my $section = "svn-remote.$_";
1725 $svm = {
1726 source => tmp_config('--get',
1727 "$section.svm-source"),
1728 replace => tmp_config('--get',
1729 "$section.svm-replace"),
1732 $r->{$_}->{svm} = $svm;
1734 } keys %$r;
1739 sub init_vars {
1740 $_gc_nr = $_gc_period = 1000;
1741 if (defined $_repack || defined $_repack_flags) {
1742 warn "Repack options are obsolete; they have no effect.\n";
1746 sub verify_remotes_sanity {
1747 return unless -d $ENV{GIT_DIR};
1748 my %seen;
1749 foreach (command(qw/config -l/)) {
1750 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1751 if ($seen{$1}) {
1752 die "Remote ref refs/remote/$1 is tracked by",
1753 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1754 "Please resolve this ambiguity in ",
1755 "your git configuration file before ",
1756 "continuing\n";
1758 $seen{$1} = $_;
1763 sub find_existing_remote {
1764 my ($url, $remotes) = @_;
1765 return undef if $no_reuse_existing;
1766 my $existing;
1767 foreach my $repo_id (keys %$remotes) {
1768 my $u = $remotes->{$repo_id}->{url} or next;
1769 next if $u ne $url;
1770 $existing = $repo_id;
1771 last;
1773 $existing;
1776 sub init_remote_config {
1777 my ($self, $url, $no_write) = @_;
1778 $url =~ s!/+$!!; # strip trailing slash
1779 my $r = read_all_remotes();
1780 my $existing = find_existing_remote($url, $r);
1781 if ($existing) {
1782 unless ($no_write) {
1783 print STDERR "Using existing ",
1784 "[svn-remote \"$existing\"]\n";
1786 $self->{repo_id} = $existing;
1787 } elsif ($_minimize_url) {
1788 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1789 $existing = find_existing_remote($min_url, $r);
1790 if ($existing) {
1791 unless ($no_write) {
1792 print STDERR "Using existing ",
1793 "[svn-remote \"$existing\"]\n";
1795 $self->{repo_id} = $existing;
1797 if ($min_url ne $url) {
1798 unless ($no_write) {
1799 print STDERR "Using higher level of URL: ",
1800 "$url => $min_url\n";
1802 my $old_path = $self->{path};
1803 $self->{path} = $url;
1804 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1805 if (length $old_path) {
1806 $self->{path} .= "/$old_path";
1808 $url = $min_url;
1811 my $orig_url;
1812 if (!$existing) {
1813 # verify that we aren't overwriting anything:
1814 $orig_url = eval {
1815 command_oneline('config', '--get',
1816 "svn-remote.$self->{repo_id}.url")
1818 if ($orig_url && ($orig_url ne $url)) {
1819 die "svn-remote.$self->{repo_id}.url already set: ",
1820 "$orig_url\nwanted to set to: $url\n";
1823 my ($xrepo_id, $xpath) = find_ref($self->refname);
1824 if (defined $xpath) {
1825 die "svn-remote.$xrepo_id.fetch already set to track ",
1826 "$xpath:refs/remotes/", $self->refname, "\n";
1828 unless ($no_write) {
1829 command_noisy('config',
1830 "svn-remote.$self->{repo_id}.url", $url);
1831 $self->{path} =~ s{^/}{};
1832 command_noisy('config', '--add',
1833 "svn-remote.$self->{repo_id}.fetch",
1834 "$self->{path}:".$self->refname);
1836 $self->{url} = $url;
1839 sub find_by_url { # repos_root and, path are optional
1840 my ($class, $full_url, $repos_root, $path) = @_;
1842 return undef unless defined $full_url;
1843 remove_username($full_url);
1844 remove_username($repos_root) if defined $repos_root;
1845 my $remotes = read_all_remotes();
1846 if (defined $full_url && defined $repos_root && !defined $path) {
1847 $path = $full_url;
1848 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1850 foreach my $repo_id (keys %$remotes) {
1851 my $u = $remotes->{$repo_id}->{url} or next;
1852 remove_username($u);
1853 next if defined $repos_root && $repos_root ne $u;
1855 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1856 foreach my $t (qw/branches tags/) {
1857 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1858 resolve_local_globs($u, $fetch, $globspec);
1861 my $p = $path;
1862 my $rwr = rewrite_root({repo_id => $repo_id});
1863 my $svm = $remotes->{$repo_id}->{svm}
1864 if defined $remotes->{$repo_id}->{svm};
1865 unless (defined $p) {
1866 $p = $full_url;
1867 my $z = $u;
1868 my $prefix = '';
1869 if ($rwr) {
1870 $z = $rwr;
1871 remove_username($z);
1872 } elsif (defined $svm) {
1873 $z = $svm->{source};
1874 $prefix = $svm->{replace};
1875 $prefix =~ s#^\Q$u\E(?:/|$)##;
1876 $prefix =~ s#/$##;
1878 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1880 foreach my $f (keys %$fetch) {
1881 next if $f ne $p;
1882 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1885 undef;
1888 sub init {
1889 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1890 my $self = _new($class, $repo_id, $ref_id, $path);
1891 if (defined $url) {
1892 $self->init_remote_config($url, $no_write);
1894 $self;
1897 sub find_ref {
1898 my ($ref_id) = @_;
1899 foreach (command(qw/config -l/)) {
1900 next unless m!^svn-remote\.(.+)\.fetch=
1901 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1902 my ($repo_id, $path, $ref) = ($1, $2, $3);
1903 if ($ref eq $ref_id) {
1904 $path = '' if ($path =~ m#^\./?#);
1905 return ($repo_id, $path);
1908 (undef, undef, undef);
1911 sub new {
1912 my ($class, $ref_id, $repo_id, $path) = @_;
1913 if (defined $ref_id && !defined $repo_id && !defined $path) {
1914 ($repo_id, $path) = find_ref($ref_id);
1915 if (!defined $repo_id) {
1916 die "Could not find a \"svn-remote.*.fetch\" key ",
1917 "in the repository configuration matching: ",
1918 "refs/remotes/$ref_id\n";
1921 my $self = _new($class, $repo_id, $ref_id, $path);
1922 if (!defined $self->{path} || !length $self->{path}) {
1923 my $fetch = command_oneline('config', '--get',
1924 "svn-remote.$repo_id.fetch",
1925 ":refs/remotes/$ref_id\$") or
1926 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1927 "\":refs/remotes/$ref_id\$\" in config\n";
1928 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1930 $self->{url} = command_oneline('config', '--get',
1931 "svn-remote.$repo_id.url") or
1932 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1933 $self->rebuild;
1934 $self;
1937 sub refname {
1938 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1940 # It cannot end with a slash /, we'll throw up on this because
1941 # SVN can't have directories with a slash in their name, either:
1942 if ($refname =~ m{/$}) {
1943 die "ref: '$refname' ends with a trailing slash, this is ",
1944 "not permitted by git nor Subversion\n";
1947 # It cannot have ASCII control character space, tilde ~, caret ^,
1948 # colon :, question-mark ?, asterisk *, space, or open bracket [
1949 # anywhere.
1951 # Additionally, % must be escaped because it is used for escaping
1952 # and we want our escaped refname to be reversible
1953 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1955 # no slash-separated component can begin with a dot .
1956 # /.* becomes /%2E*
1957 $refname =~ s{/\.}{/%2E}g;
1959 # It cannot have two consecutive dots .. anywhere
1960 # .. becomes %2E%2E
1961 $refname =~ s{\.\.}{%2E%2E}g;
1963 return $refname;
1966 sub desanitize_refname {
1967 my ($refname) = @_;
1968 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1969 return $refname;
1972 sub svm_uuid {
1973 my ($self) = @_;
1974 return $self->{svm}->{uuid} if $self->svm;
1975 $self->ra;
1976 unless ($self->{svm}) {
1977 die "SVM UUID not cached, and reading remotely failed\n";
1979 $self->{svm}->{uuid};
1982 sub svm {
1983 my ($self) = @_;
1984 return $self->{svm} if $self->{svm};
1985 my $svm;
1986 # see if we have it in our config, first:
1987 eval {
1988 my $section = "svn-remote.$self->{repo_id}";
1989 $svm = {
1990 source => tmp_config('--get', "$section.svm-source"),
1991 uuid => tmp_config('--get', "$section.svm-uuid"),
1992 replace => tmp_config('--get', "$section.svm-replace"),
1995 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1996 $self->{svm} = $svm;
1998 $self->{svm};
2001 sub _set_svm_vars {
2002 my ($self, $ra) = @_;
2003 return $ra if $self->svm;
2005 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2006 "(svm:source, svm:uuid) ",
2007 "from the following URLs:\n" );
2008 sub read_svm_props {
2009 my ($self, $ra, $path, $r) = @_;
2010 my $props = ($ra->get_dir($path, $r))[2];
2011 my $src = $props->{'svm:source'};
2012 my $uuid = $props->{'svm:uuid'};
2013 return undef if (!$src || !$uuid);
2015 chomp($src, $uuid);
2017 $uuid =~ m{^[0-9a-f\-]{30,}$}
2018 or die "doesn't look right - svm:uuid is '$uuid'\n";
2020 # the '!' is used to mark the repos_root!/relative/path
2021 $src =~ s{/?!/?}{/};
2022 $src =~ s{/+$}{}; # no trailing slashes please
2023 # username is of no interest
2024 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2026 my $replace = $ra->{url};
2027 $replace .= "/$path" if length $path;
2029 my $section = "svn-remote.$self->{repo_id}";
2030 tmp_config("$section.svm-source", $src);
2031 tmp_config("$section.svm-replace", $replace);
2032 tmp_config("$section.svm-uuid", $uuid);
2033 $self->{svm} = {
2034 source => $src,
2035 uuid => $uuid,
2036 replace => $replace
2040 my $r = $ra->get_latest_revnum;
2041 my $path = $self->{path};
2042 my %tried;
2043 while (length $path) {
2044 unless ($tried{"$self->{url}/$path"}) {
2045 return $ra if $self->read_svm_props($ra, $path, $r);
2046 $tried{"$self->{url}/$path"} = 1;
2048 $path =~ s#/?[^/]+$##;
2050 die "Path: '$path' should be ''\n" if $path ne '';
2051 return $ra if $self->read_svm_props($ra, $path, $r);
2052 $tried{"$self->{url}/$path"} = 1;
2054 if ($ra->{repos_root} eq $self->{url}) {
2055 die @err, (map { " $_\n" } keys %tried), "\n";
2058 # nope, make sure we're connected to the repository root:
2059 my $ok;
2060 my @tried_b;
2061 $path = $ra->{svn_path};
2062 $ra = Git::SVN::Ra->new($ra->{repos_root});
2063 while (length $path) {
2064 unless ($tried{"$ra->{url}/$path"}) {
2065 $ok = $self->read_svm_props($ra, $path, $r);
2066 last if $ok;
2067 $tried{"$ra->{url}/$path"} = 1;
2069 $path =~ s#/?[^/]+$##;
2071 die "Path: '$path' should be ''\n" if $path ne '';
2072 $ok ||= $self->read_svm_props($ra, $path, $r);
2073 $tried{"$ra->{url}/$path"} = 1;
2074 if (!$ok) {
2075 die @err, (map { " $_\n" } keys %tried), "\n";
2077 Git::SVN::Ra->new($self->{url});
2080 sub svnsync {
2081 my ($self) = @_;
2082 return $self->{svnsync} if $self->{svnsync};
2084 if ($self->no_metadata) {
2085 die "Can't have both 'noMetadata' and ",
2086 "'useSvnsyncProps' options set!\n";
2088 if ($self->rewrite_root) {
2089 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2090 "options set!\n";
2093 my $svnsync;
2094 # see if we have it in our config, first:
2095 eval {
2096 my $section = "svn-remote.$self->{repo_id}";
2098 my $url = tmp_config('--get', "$section.svnsync-url");
2099 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2100 die "doesn't look right - svn:sync-from-url is '$url'\n";
2102 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2103 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2104 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2106 $svnsync = { url => $url, uuid => $uuid }
2108 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2109 return $self->{svnsync} = $svnsync;
2112 my $err = "useSvnsyncProps set, but failed to read " .
2113 "svnsync property: svn:sync-from-";
2114 my $rp = $self->ra->rev_proplist(0);
2116 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2117 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2118 die "doesn't look right - svn:sync-from-url is '$url'\n";
2120 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2121 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2122 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2124 my $section = "svn-remote.$self->{repo_id}";
2125 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2126 tmp_config('--add', "$section.svnsync-url", $url);
2127 return $self->{svnsync} = { url => $url, uuid => $uuid };
2130 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2131 # remote lookup (useful for 'git svn log').
2132 sub ra_uuid {
2133 my ($self) = @_;
2134 unless ($self->{ra_uuid}) {
2135 my $key = "svn-remote.$self->{repo_id}.uuid";
2136 my $uuid = eval { tmp_config('--get', $key) };
2137 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2138 $self->{ra_uuid} = $uuid;
2139 } else {
2140 die "ra_uuid called without URL\n" unless $self->{url};
2141 $self->{ra_uuid} = $self->ra->get_uuid;
2142 tmp_config('--add', $key, $self->{ra_uuid});
2145 $self->{ra_uuid};
2148 sub _set_repos_root {
2149 my ($self, $repos_root) = @_;
2150 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2151 $repos_root ||= $self->ra->{repos_root};
2152 tmp_config($k, $repos_root);
2153 $repos_root;
2156 sub repos_root {
2157 my ($self) = @_;
2158 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2159 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2162 sub ra {
2163 my ($self) = shift;
2164 my $ra = Git::SVN::Ra->new($self->{url});
2165 $self->_set_repos_root($ra->{repos_root});
2166 if ($self->use_svm_props && !$self->{svm}) {
2167 if ($self->no_metadata) {
2168 die "Can't have both 'noMetadata' and ",
2169 "'useSvmProps' options set!\n";
2170 } elsif ($self->use_svnsync_props) {
2171 die "Can't have both 'useSvnsyncProps' and ",
2172 "'useSvmProps' options set!\n";
2174 $ra = $self->_set_svm_vars($ra);
2175 $self->{-want_revprops} = 1;
2177 $ra;
2180 sub rel_path {
2181 my ($self) = @_;
2182 my $repos_root = $self->ra->{repos_root};
2183 return $self->{path} if ($self->{url} eq $repos_root);
2184 my $url = $self->{url} .
2185 (length $self->{path} ? "/$self->{path}" : $self->{path});
2186 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2187 $url;
2190 # prop_walk(PATH, REV, SUB)
2191 # -------------------------
2192 # Recursively traverse PATH at revision REV and invoke SUB for each
2193 # directory that contains a SVN property. SUB will be invoked as
2194 # follows: &SUB(gs, path, props); where `gs' is this instance of
2195 # Git::SVN, `path' the path to the directory where the properties
2196 # `props' were found. The `path' will be relative to point of checkout,
2197 # that is, if url://repo/trunk is the current Git branch, and that
2198 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2199 # as `path' (note the trailing `/').
2200 sub prop_walk {
2201 my ($self, $path, $rev, $sub) = @_;
2203 $path =~ s#^/##;
2204 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2205 $path =~ s#^/*#/#g;
2206 my $p = $path;
2207 # Strip the irrelevant part of the path.
2208 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2209 # Ensure the path is terminated by a `/'.
2210 $p =~ s#/*$#/#;
2212 # The properties contain all the internal SVN stuff nobody
2213 # (usually) cares about.
2214 my $interesting_props = 0;
2215 foreach (keys %{$props}) {
2216 # If it doesn't start with `svn:', it must be a
2217 # user-defined property.
2218 ++$interesting_props and next if $_ !~ /^svn:/;
2219 # FIXME: Fragile, if SVN adds new public properties,
2220 # this needs to be updated.
2221 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2222 |eol-style|mime-type
2223 |externals|needs-lock)$/x;
2225 &$sub($self, $p, $props) if $interesting_props;
2227 foreach (sort keys %$dirent) {
2228 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2229 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2233 sub last_rev { ($_[0]->last_rev_commit)[0] }
2234 sub last_commit { ($_[0]->last_rev_commit)[1] }
2236 # returns the newest SVN revision number and newest commit SHA1
2237 sub last_rev_commit {
2238 my ($self) = @_;
2239 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2240 return ($self->{last_rev}, $self->{last_commit});
2242 my $c = ::verify_ref($self->refname.'^0');
2243 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2244 my $rev = (::cmt_metadata($c))[1];
2245 if (defined $rev) {
2246 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2247 return ($rev, $c);
2250 my $map_path = $self->map_path;
2251 unless (-e $map_path) {
2252 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2253 return (undef, undef);
2255 my ($rev, $commit) = $self->rev_map_max(1);
2256 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2257 return ($rev, $commit);
2260 sub get_fetch_range {
2261 my ($self, $min, $max) = @_;
2262 $max ||= $self->ra->get_latest_revnum;
2263 $min ||= $self->rev_map_max;
2264 (++$min, $max);
2267 sub tmp_config {
2268 my (@args) = @_;
2269 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2270 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2271 if (! -f $config && -f $old_def_config) {
2272 rename $old_def_config, $config or
2273 die "Failed rename $old_def_config => $config: $!\n";
2275 my $old_config = $ENV{GIT_CONFIG};
2276 $ENV{GIT_CONFIG} = $config;
2277 $@ = undef;
2278 my @ret = eval {
2279 unless (-f $config) {
2280 mkfile($config);
2281 open my $fh, '>', $config or
2282 die "Can't open $config: $!\n";
2283 print $fh "; This file is used internally by ",
2284 "git-svn\n" or die
2285 "Couldn't write to $config: $!\n";
2286 print $fh "; You should not have to edit it\n" or
2287 die "Couldn't write to $config: $!\n";
2288 close $fh or die "Couldn't close $config: $!\n";
2290 command('config', @args);
2292 my $err = $@;
2293 if (defined $old_config) {
2294 $ENV{GIT_CONFIG} = $old_config;
2295 } else {
2296 delete $ENV{GIT_CONFIG};
2298 die $err if $err;
2299 wantarray ? @ret : $ret[0];
2302 sub tmp_index_do {
2303 my ($self, $sub) = @_;
2304 my $old_index = $ENV{GIT_INDEX_FILE};
2305 $ENV{GIT_INDEX_FILE} = $self->{index};
2306 $@ = undef;
2307 my @ret = eval {
2308 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2309 mkpath([$dir]) unless -d $dir;
2310 &$sub;
2312 my $err = $@;
2313 if (defined $old_index) {
2314 $ENV{GIT_INDEX_FILE} = $old_index;
2315 } else {
2316 delete $ENV{GIT_INDEX_FILE};
2318 die $err if $err;
2319 wantarray ? @ret : $ret[0];
2322 sub assert_index_clean {
2323 my ($self, $treeish) = @_;
2325 $self->tmp_index_do(sub {
2326 command_noisy('read-tree', $treeish) unless -e $self->{index};
2327 my $x = command_oneline('write-tree');
2328 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2329 /^tree ($::sha1)/mo);
2330 return if $y eq $x;
2332 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2333 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2334 command_noisy('read-tree', $treeish);
2335 $x = command_oneline('write-tree');
2336 if ($y ne $x) {
2337 ::fatal "trees ($treeish) $y != $x\n",
2338 "Something is seriously wrong...";
2343 sub get_commit_parents {
2344 my ($self, $log_entry) = @_;
2345 my (%seen, @ret, @tmp);
2346 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2347 if (my $ip = $self->{inject_parents}) {
2348 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2349 push @tmp, $commit;
2352 if (my $cur = ::verify_ref($self->refname.'^0')) {
2353 push @tmp, $cur;
2355 if (my $ipd = $self->{inject_parents_dcommit}) {
2356 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2357 push @tmp, @$commit;
2360 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2361 while (my $p = shift @tmp) {
2362 next if $seen{$p};
2363 $seen{$p} = 1;
2364 push @ret, $p;
2365 # MAXPARENT is defined to 16 in commit-tree.c:
2366 last if @ret >= 16;
2368 if (@tmp) {
2369 die "r$log_entry->{revision}: No room for parents:\n\t",
2370 join("\n\t", @tmp), "\n";
2372 @ret;
2375 sub rewrite_root {
2376 my ($self) = @_;
2377 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2378 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2379 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2380 if ($rwr) {
2381 $rwr =~ s#/+$##;
2382 if ($rwr !~ m#^[a-z\+]+://#) {
2383 die "$rwr is not a valid URL (key: $k)\n";
2386 $self->{-rewrite_root} = $rwr;
2389 sub metadata_url {
2390 my ($self) = @_;
2391 ($self->rewrite_root || $self->{url}) .
2392 (length $self->{path} ? '/' . $self->{path} : '');
2395 sub full_url {
2396 my ($self) = @_;
2397 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2401 sub set_commit_header_env {
2402 my ($log_entry) = @_;
2403 my %env;
2404 foreach my $ned (qw/NAME EMAIL DATE/) {
2405 foreach my $ac (qw/AUTHOR COMMITTER/) {
2406 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2410 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2411 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2412 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2414 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2415 ? $log_entry->{commit_name}
2416 : $log_entry->{name};
2417 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2418 ? $log_entry->{commit_email}
2419 : $log_entry->{email};
2420 \%env;
2423 sub restore_commit_header_env {
2424 my ($env) = @_;
2425 foreach my $ned (qw/NAME EMAIL DATE/) {
2426 foreach my $ac (qw/AUTHOR COMMITTER/) {
2427 my $k = "GIT_${ac}_${ned}";
2428 if (defined $env->{$k}) {
2429 $ENV{$k} = $env->{$k};
2430 } else {
2431 delete $ENV{$k};
2437 sub gc {
2438 command_noisy('gc', '--auto');
2441 sub do_git_commit {
2442 my ($self, $log_entry) = @_;
2443 my $lr = $self->last_rev;
2444 if (defined $lr && $lr >= $log_entry->{revision}) {
2445 die "Last fetched revision of ", $self->refname,
2446 " was r$lr, but we are about to fetch: ",
2447 "r$log_entry->{revision}!\n";
2449 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2450 croak "$log_entry->{revision} = $c already exists! ",
2451 "Why are we refetching it?\n";
2453 my $old_env = set_commit_header_env($log_entry);
2454 my $tree = $log_entry->{tree};
2455 if (!defined $tree) {
2456 $tree = $self->tmp_index_do(sub {
2457 command_oneline('write-tree') });
2459 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2461 my @exec = ('git', 'commit-tree', $tree);
2462 foreach ($self->get_commit_parents($log_entry)) {
2463 push @exec, '-p', $_;
2465 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2466 or croak $!;
2467 binmode $msg_fh;
2469 # we always get UTF-8 from SVN, but we may want our commits in
2470 # a different encoding.
2471 if (my $enc = Git::config('i18n.commitencoding')) {
2472 require Encode;
2473 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2475 print $msg_fh $log_entry->{log} or croak $!;
2476 restore_commit_header_env($old_env);
2477 unless ($self->no_metadata) {
2478 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2479 or croak $!;
2481 $msg_fh->flush == 0 or croak $!;
2482 close $msg_fh or croak $!;
2483 chomp(my $commit = do { local $/; <$out_fh> });
2484 close $out_fh or croak $!;
2485 waitpid $pid, 0;
2486 croak $? if $?;
2487 if ($commit !~ /^$::sha1$/o) {
2488 die "Failed to commit, invalid sha1: $commit\n";
2491 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2493 $self->{last_rev} = $log_entry->{revision};
2494 $self->{last_commit} = $commit;
2495 print "r$log_entry->{revision}" unless $::_q > 1;
2496 if (defined $log_entry->{svm_revision}) {
2497 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2498 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2499 0, $self->svm_uuid);
2501 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2502 if (--$_gc_nr == 0) {
2503 $_gc_nr = $_gc_period;
2504 gc();
2506 return $commit;
2509 sub match_paths {
2510 my ($self, $paths, $r) = @_;
2511 return 1 if $self->{path} eq '';
2512 if (my $path = $paths->{"/$self->{path}"}) {
2513 return ($path->{action} eq 'D') ? 0 : 1;
2515 my $repos_root = $self->ra->{repos_root};
2516 my $extended_path = $self->{url} . '/' . $self->{path};
2517 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2518 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2519 if (grep /$self->{path_regex}/, keys %$paths) {
2520 return 1;
2522 my $c = '';
2523 foreach (split m#/#, $self->{path}) {
2524 $c .= "/$_";
2525 next unless ($paths->{$c} &&
2526 ($paths->{$c}->{action} =~ /^[AR]$/));
2527 if ($self->ra->check_path($self->{path}, $r) ==
2528 $SVN::Node::dir) {
2529 return 1;
2532 return 0;
2535 sub find_parent_branch {
2536 my ($self, $paths, $rev) = @_;
2537 return undef unless $self->follow_parent;
2538 unless (defined $paths) {
2539 my $err_handler = $SVN::Error::handler;
2540 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2541 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2542 $paths =
2543 Git::SVN::Ra::dup_changed_paths($_[0]) });
2544 $SVN::Error::handler = $err_handler;
2546 return undef unless defined $paths;
2548 # look for a parent from another branch:
2549 my @b_path_components = split m#/#, $self->rel_path;
2550 my @a_path_components;
2551 my $i;
2552 while (@b_path_components) {
2553 $i = $paths->{'/'.join('/', @b_path_components)};
2554 last if $i && defined $i->{copyfrom_path};
2555 unshift(@a_path_components, pop(@b_path_components));
2557 return undef unless defined $i && defined $i->{copyfrom_path};
2558 my $branch_from = $i->{copyfrom_path};
2559 if (@a_path_components) {
2560 print STDERR "branch_from: $branch_from => ";
2561 $branch_from .= '/'.join('/', @a_path_components);
2562 print STDERR $branch_from, "\n";
2564 my $r = $i->{copyfrom_rev};
2565 my $repos_root = $self->ra->{repos_root};
2566 my $url = $self->ra->{url};
2567 my $new_url = $repos_root . $branch_from;
2568 print STDERR "Found possible branch point: ",
2569 "$new_url => ", $self->full_url, ", $r\n";
2570 $branch_from =~ s#^/##;
2571 my $gs = $self->other_gs($new_url, $url, $repos_root,
2572 $branch_from, $r, $self->{ref_id});
2573 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2575 my ($base, $head);
2576 if (!defined $r0 || !defined $parent) {
2577 ($base, $head) = parse_revision_argument(0, $r);
2578 } else {
2579 if ($r0 < $r) {
2580 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2581 0, 1, sub { $base = $_[1] - 1 });
2584 if (defined $base && $base <= $r) {
2585 $gs->fetch($base, $r);
2587 ($r0, $parent) = $gs->find_rev_before($r, 1);
2589 if (defined $r0 && defined $parent) {
2590 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2591 my $ed;
2592 if ($self->ra->can_do_switch) {
2593 $self->assert_index_clean($parent);
2594 print STDERR "Following parent with do_switch\n";
2595 # do_switch works with svn/trunk >= r22312, but that
2596 # is not included with SVN 1.4.3 (the latest version
2597 # at the moment), so we can't rely on it
2598 $self->{last_rev} = $r0;
2599 $self->{last_commit} = $parent;
2600 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2601 $gs->ra->gs_do_switch($r0, $rev, $gs,
2602 $self->full_url, $ed)
2603 or die "SVN connection failed somewhere...\n";
2604 } elsif ($self->ra->trees_match($new_url, $r0,
2605 $self->full_url, $rev)) {
2606 print STDERR "Trees match:\n",
2607 " $new_url\@$r0\n",
2608 " ${\$self->full_url}\@$rev\n",
2609 "Following parent with no changes\n";
2610 $self->tmp_index_do(sub {
2611 command_noisy('read-tree', $parent);
2613 $self->{last_commit} = $parent;
2614 } else {
2615 print STDERR "Following parent with do_update\n";
2616 $ed = SVN::Git::Fetcher->new($self);
2617 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2618 or die "SVN connection failed somewhere...\n";
2620 print STDERR "Successfully followed parent\n";
2621 return $self->make_log_entry($rev, [$parent], $ed);
2623 return undef;
2626 sub do_fetch {
2627 my ($self, $paths, $rev) = @_;
2628 my $ed;
2629 my ($last_rev, @parents);
2630 if (my $lc = $self->last_commit) {
2631 # we can have a branch that was deleted, then re-added
2632 # under the same name but copied from another path, in
2633 # which case we'll have multiple parents (we don't
2634 # want to break the original ref, nor lose copypath info):
2635 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2636 push @{$log_entry->{parents}}, $lc;
2637 return $log_entry;
2639 $ed = SVN::Git::Fetcher->new($self);
2640 $last_rev = $self->{last_rev};
2641 $ed->{c} = $lc;
2642 @parents = ($lc);
2643 } else {
2644 $last_rev = $rev;
2645 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2646 return $log_entry;
2648 $ed = SVN::Git::Fetcher->new($self);
2650 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2651 die "SVN connection failed somewhere...\n";
2653 $self->make_log_entry($rev, \@parents, $ed);
2656 sub get_untracked {
2657 my ($self, $ed) = @_;
2658 my @out;
2659 my $h = $ed->{empty};
2660 foreach (sort keys %$h) {
2661 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2662 push @out, " $act: " . uri_encode($_);
2663 warn "W: $act: $_\n";
2665 foreach my $t (qw/dir_prop file_prop/) {
2666 $h = $ed->{$t} or next;
2667 foreach my $path (sort keys %$h) {
2668 my $ppath = $path eq '' ? '.' : $path;
2669 foreach my $prop (sort keys %{$h->{$path}}) {
2670 next if $SKIP_PROP{$prop};
2671 my $v = $h->{$path}->{$prop};
2672 my $t_ppath_prop = "$t: " .
2673 uri_encode($ppath) . ' ' .
2674 uri_encode($prop);
2675 if (defined $v) {
2676 push @out, " +$t_ppath_prop " .
2677 uri_encode($v);
2678 } else {
2679 push @out, " -$t_ppath_prop";
2684 foreach my $t (qw/absent_file absent_directory/) {
2685 $h = $ed->{$t} or next;
2686 foreach my $parent (sort keys %$h) {
2687 foreach my $path (sort @{$h->{$parent}}) {
2688 push @out, " $t: " .
2689 uri_encode("$parent/$path");
2690 warn "W: $t: $parent/$path ",
2691 "Insufficient permissions?\n";
2695 \@out;
2698 # parse_svn_date(DATE)
2699 # --------------------
2700 # Given a date (in UTC) from Subversion, return a string in the format
2701 # "<TZ Offset> <local date/time>" that Git will use.
2703 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2704 # is true we'll convert it to the local timezone instead.
2705 sub parse_svn_date {
2706 my $date = shift || return '+0000 1970-01-01 00:00:00';
2707 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2708 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2709 croak "Unable to parse date: $date\n";
2710 my $parsed_date; # Set next.
2712 if ($Git::SVN::_localtime) {
2713 # Translate the Subversion datetime to an epoch time.
2714 # Begin by switching ourselves to $date's timezone, UTC.
2715 my $old_env_TZ = $ENV{TZ};
2716 $ENV{TZ} = 'UTC';
2718 my $epoch_in_UTC =
2719 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2721 # Determine our local timezone (including DST) at the
2722 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2723 # value of TZ, if any, at the time we were run.
2724 if (defined $Git::SVN::Log::TZ) {
2725 $ENV{TZ} = $Git::SVN::Log::TZ;
2726 } else {
2727 delete $ENV{TZ};
2730 my $our_TZ =
2731 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2733 # This converts $epoch_in_UTC into our local timezone.
2734 my ($sec, $min, $hour, $mday, $mon, $year,
2735 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2737 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2738 $our_TZ, $year + 1900, $mon + 1,
2739 $mday, $hour, $min, $sec);
2741 # Reset us to the timezone in effect when we entered
2742 # this routine.
2743 if (defined $old_env_TZ) {
2744 $ENV{TZ} = $old_env_TZ;
2745 } else {
2746 delete $ENV{TZ};
2748 } else {
2749 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2752 return $parsed_date;
2755 sub other_gs {
2756 my ($self, $new_url, $url, $repos_root,
2757 $branch_from, $r, $old_ref_id) = @_;
2758 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2759 unless ($gs) {
2760 my $ref_id = $old_ref_id;
2761 $ref_id =~ s/\@\d+$//;
2762 $ref_id .= "\@$r";
2763 # just grow a tail if we're not unique enough :x
2764 $ref_id .= '-' while find_ref($ref_id);
2765 print STDERR "Initializing parent: $ref_id\n";
2766 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2767 if ($u =~ s#^\Q$url\E(/|$)##) {
2768 $p = $u;
2769 $u = $url;
2770 $repo_id = $self->{repo_id};
2772 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2777 sub call_authors_prog {
2778 my ($orig_author) = @_;
2779 my $author = `$::_authors_prog $orig_author`;
2780 if ($? != 0) {
2781 die "$::_authors_prog failed with exit code $?\n"
2783 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2784 my ($name, $email) = ($1, $2);
2785 $email = undef if length $2 == 0;
2786 return [$name, $email];
2787 } else {
2788 die "Author: $orig_author: $::_authors_prog returned "
2789 . "invalid author format: $author\n";
2793 sub check_author {
2794 my ($author) = @_;
2795 if (!defined $author || length $author == 0) {
2796 $author = '(no author)';
2798 if (!defined $::users{$author}) {
2799 if (defined $::_authors_prog) {
2800 $::users{$author} = call_authors_prog($author);
2801 } elsif (defined $::_authors) {
2802 die "Author: $author not defined in $::_authors file\n";
2805 $author;
2808 sub make_log_entry {
2809 my ($self, $rev, $parents, $ed) = @_;
2810 my $untracked = $self->get_untracked($ed);
2812 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2813 print $un "r$rev\n" or croak $!;
2814 print $un $_, "\n" foreach @$untracked;
2815 my %log_entry = ( parents => $parents || [], revision => $rev,
2816 log => '');
2818 my $headrev;
2819 my $logged = delete $self->{logged_rev_props};
2820 if (!$logged || $self->{-want_revprops}) {
2821 my $rp = $self->ra->rev_proplist($rev);
2822 foreach (sort keys %$rp) {
2823 my $v = $rp->{$_};
2824 if (/^svn:(author|date|log)$/) {
2825 $log_entry{$1} = $v;
2826 } elsif ($_ eq 'svm:headrev') {
2827 $headrev = $v;
2828 } else {
2829 print $un " rev_prop: ", uri_encode($_), ' ',
2830 uri_encode($v), "\n";
2833 } else {
2834 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2836 close $un or croak $!;
2838 $log_entry{date} = parse_svn_date($log_entry{date});
2839 $log_entry{log} .= "\n";
2840 my $author = $log_entry{author} = check_author($log_entry{author});
2841 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2842 : ($author, undef);
2844 my ($commit_name, $commit_email) = ($name, $email);
2845 if ($_use_log_author) {
2846 my $name_field;
2847 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2848 $name_field = $1;
2849 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2850 $name_field = $1;
2852 if (!defined $name_field) {
2853 if (!defined $email) {
2854 $email = $name;
2856 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2857 ($name, $email) = ($1, $2);
2858 } elsif ($name_field =~ /(.*)@/) {
2859 ($name, $email) = ($1, $name_field);
2860 } else {
2861 ($name, $email) = ($name_field, $name_field);
2864 if (defined $headrev && $self->use_svm_props) {
2865 if ($self->rewrite_root) {
2866 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2867 "options set!\n";
2869 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2870 # we don't want "SVM: initializing mirror for junk" ...
2871 return undef if $r == 0;
2872 my $svm = $self->svm;
2873 if ($uuid ne $svm->{uuid}) {
2874 die "UUID mismatch on SVM path:\n",
2875 "expected: $svm->{uuid}\n",
2876 " got: $uuid\n";
2878 my $full_url = $self->full_url;
2879 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2880 die "Failed to replace '$svm->{replace}' with ",
2881 "'$svm->{source}' in $full_url\n";
2882 # throw away username for storing in records
2883 remove_username($full_url);
2884 $log_entry{metadata} = "$full_url\@$r $uuid";
2885 $log_entry{svm_revision} = $r;
2886 $email ||= "$author\@$uuid";
2887 $commit_email ||= "$author\@$uuid";
2888 } elsif ($self->use_svnsync_props) {
2889 my $full_url = $self->svnsync->{url};
2890 $full_url .= "/$self->{path}" if length $self->{path};
2891 remove_username($full_url);
2892 my $uuid = $self->svnsync->{uuid};
2893 $log_entry{metadata} = "$full_url\@$rev $uuid";
2894 $email ||= "$author\@$uuid";
2895 $commit_email ||= "$author\@$uuid";
2896 } else {
2897 my $url = $self->metadata_url;
2898 remove_username($url);
2899 $log_entry{metadata} = "$url\@$rev " .
2900 $self->ra->get_uuid;
2901 $email ||= "$author\@" . $self->ra->get_uuid;
2902 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2904 $log_entry{name} = $name;
2905 $log_entry{email} = $email;
2906 $log_entry{commit_name} = $commit_name;
2907 $log_entry{commit_email} = $commit_email;
2908 \%log_entry;
2911 sub fetch {
2912 my ($self, $min_rev, $max_rev, @parents) = @_;
2913 my ($last_rev, $last_commit) = $self->last_rev_commit;
2914 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2915 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2918 sub set_tree_cb {
2919 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2920 $self->{inject_parents} = { $rev => $tree };
2921 $self->fetch(undef, undef);
2924 sub set_tree {
2925 my ($self, $tree) = (shift, shift);
2926 my $log_entry = ::get_commit_entry($tree);
2927 unless ($self->{last_rev}) {
2928 ::fatal("Must have an existing revision to commit");
2930 my %ed_opts = ( r => $self->{last_rev},
2931 log => $log_entry->{log},
2932 ra => $self->ra,
2933 tree_a => $self->{last_commit},
2934 tree_b => $tree,
2935 editor_cb => sub {
2936 $self->set_tree_cb($log_entry, $tree, @_) },
2937 svn_path => $self->{path} );
2938 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2939 print "No changes\nr$self->{last_rev} = $tree\n";
2943 sub rebuild_from_rev_db {
2944 my ($self, $path) = @_;
2945 my $r = -1;
2946 open my $fh, '<', $path or croak "open: $!";
2947 binmode $fh or croak "binmode: $!";
2948 while (<$fh>) {
2949 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2950 chomp($_);
2951 ++$r;
2952 next if $_ eq ('0' x 40);
2953 $self->rev_map_set($r, $_);
2954 print "r$r = $_\n";
2956 close $fh or croak "close: $!";
2957 unlink $path or croak "unlink: $!";
2960 sub rebuild {
2961 my ($self) = @_;
2962 my $map_path = $self->map_path;
2963 my $partial = (-e $map_path && ! -z $map_path);
2964 return unless ::verify_ref($self->refname.'^0');
2965 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2966 my $rev_db = $self->rev_db_path;
2967 $self->rebuild_from_rev_db($rev_db);
2968 if ($self->use_svm_props) {
2969 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2970 $self->rebuild_from_rev_db($svm_rev_db);
2972 $self->unlink_rev_db_symlink;
2973 return;
2975 print "Rebuilding $map_path ...\n" if (!$partial);
2976 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2977 (undef, undef));
2978 my ($log, $ctx) =
2979 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2980 ($head ? "$head.." : "") . $self->refname,
2981 '--');
2982 my $metadata_url = $self->metadata_url;
2983 remove_username($metadata_url);
2984 my $svn_uuid = $self->ra_uuid;
2985 my $c;
2986 while (<$log>) {
2987 if ( m{^commit ($::sha1)$} ) {
2988 $c = $1;
2989 next;
2991 next unless s{^\s*(git-svn-id:)}{$1};
2992 my ($url, $rev, $uuid) = ::extract_metadata($_);
2993 remove_username($url);
2995 # ignore merges (from set-tree)
2996 next if (!defined $rev || !$uuid);
2998 # if we merged or otherwise started elsewhere, this is
2999 # how we break out of it
3000 if (($uuid ne $svn_uuid) ||
3001 ($metadata_url && $url && ($url ne $metadata_url))) {
3002 next;
3004 if ($partial && $head) {
3005 print "Partial-rebuilding $map_path ...\n";
3006 print "Currently at $base_rev = $head\n";
3007 $head = undef;
3010 $self->rev_map_set($rev, $c);
3011 print "r$rev = $c\n";
3013 command_close_pipe($log, $ctx);
3014 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3015 my $rev_db_path = $self->rev_db_path;
3016 if (-f $self->rev_db_path) {
3017 unlink $self->rev_db_path or croak "unlink: $!";
3019 $self->unlink_rev_db_symlink;
3022 # rev_map:
3023 # Tie::File seems to be prone to offset errors if revisions get sparse,
3024 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3025 # one of my favorite modules is out :< Next up would be one of the DBM
3026 # modules, but I'm not sure which is most portable...
3028 # This is the replacement for the rev_db format, which was too big
3029 # and inefficient for large repositories with a lot of sparse history
3030 # (mainly tags)
3032 # The format is this:
3033 # - 24 bytes for every record,
3034 # * 4 bytes for the integer representing an SVN revision number
3035 # * 20 bytes representing the sha1 of a git commit
3036 # - No empty padding records like the old format
3037 # (except the last record, which can be overwritten)
3038 # - new records are written append-only since SVN revision numbers
3039 # increase monotonically
3040 # - lookups on SVN revision number are done via a binary search
3041 # - Piping the file to xxd -c24 is a good way of dumping it for
3042 # viewing or editing (piped back through xxd -r), should the need
3043 # ever arise.
3044 # - The last record can be padding revision with an all-zero sha1
3045 # This is used to optimize fetch performance when using multiple
3046 # "fetch" directives in .git/config
3048 # These files are disposable unless noMetadata or useSvmProps is set
3050 sub _rev_map_set {
3051 my ($fh, $rev, $commit) = @_;
3053 binmode $fh or croak "binmode: $!";
3054 my $size = (stat($fh))[7];
3055 ($size % 24) == 0 or croak "inconsistent size: $size";
3057 my $wr_offset = 0;
3058 if ($size > 0) {
3059 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3060 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3061 $read == 24 or croak "read only $read bytes (!= 24)";
3062 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3063 if ($last_commit eq ('0' x40)) {
3064 if ($size >= 48) {
3065 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3066 $read = sysread($fh, $buf, 24) or
3067 croak "read: $!";
3068 $read == 24 or
3069 croak "read only $read bytes (!= 24)";
3070 ($last_rev, $last_commit) =
3071 unpack(rev_map_fmt, $buf);
3072 if ($last_commit eq ('0' x40)) {
3073 croak "inconsistent .rev_map\n";
3076 if ($last_rev >= $rev) {
3077 croak "last_rev is higher!: $last_rev >= $rev";
3079 $wr_offset = -24;
3082 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3083 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3084 croak "write: $!";
3087 sub _rev_map_reset {
3088 my ($fh, $rev, $commit) = @_;
3089 my $c = _rev_map_get($fh, $rev);
3090 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3091 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3092 truncate $fh, $offset or croak "truncate: $!";
3095 sub mkfile {
3096 my ($path) = @_;
3097 unless (-e $path) {
3098 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3099 mkpath([$dir]) unless -d $dir;
3100 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3101 close $fh or die "Couldn't close (create) $path: $!\n";
3105 sub rev_map_set {
3106 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3107 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3108 my $db = $self->map_path($uuid);
3109 my $db_lock = "$db.lock";
3110 my $sig;
3111 $update_ref ||= 0;
3112 if ($update_ref) {
3113 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3114 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3116 mkfile($db);
3118 $LOCKFILES{$db_lock} = 1;
3119 my $sync;
3120 # both of these options make our .rev_db file very, very important
3121 # and we can't afford to lose it because rebuild() won't work
3122 if ($self->use_svm_props || $self->no_metadata) {
3123 $sync = 1;
3124 copy($db, $db_lock) or die "rev_map_set(@_): ",
3125 "Failed to copy: ",
3126 "$db => $db_lock ($!)\n";
3127 } else {
3128 rename $db, $db_lock or die "rev_map_set(@_): ",
3129 "Failed to rename: ",
3130 "$db => $db_lock ($!)\n";
3133 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3134 or croak "Couldn't open $db_lock: $!\n";
3135 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3136 _rev_map_set($fh, $rev, $commit);
3137 if ($sync) {
3138 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3139 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3141 close $fh or croak $!;
3142 if ($update_ref) {
3143 $_head = $self;
3144 my $note = "";
3145 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3146 command_noisy('update-ref', '-m', "r$rev$note",
3147 $self->refname, $commit);
3149 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3150 "$db_lock => $db ($!)\n";
3151 delete $LOCKFILES{$db_lock};
3152 if ($update_ref) {
3153 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3154 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3155 kill $sig, $$ if defined $sig;
3159 # If want_commit, this will return an array of (rev, commit) where
3160 # commit _must_ be a valid commit in the archive.
3161 # Otherwise, it'll return the max revision (whether or not the
3162 # commit is valid or just a 0x40 placeholder).
3163 sub rev_map_max {
3164 my ($self, $want_commit) = @_;
3165 $self->rebuild;
3166 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3167 $want_commit ? ($r, $c) : $r;
3170 sub rev_map_max_norebuild {
3171 my ($self, $want_commit) = @_;
3172 my $map_path = $self->map_path;
3173 stat $map_path or return $want_commit ? (0, undef) : 0;
3174 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3175 binmode $fh or croak "binmode: $!";
3176 my $size = (stat($fh))[7];
3177 ($size % 24) == 0 or croak "inconsistent size: $size";
3179 if ($size == 0) {
3180 close $fh or croak "close: $!";
3181 return $want_commit ? (0, undef) : 0;
3184 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3185 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3186 my ($r, $c) = unpack(rev_map_fmt, $buf);
3187 if ($want_commit && $c eq ('0' x40)) {
3188 if ($size < 48) {
3189 return $want_commit ? (0, undef) : 0;
3191 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3192 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3193 ($r, $c) = unpack(rev_map_fmt, $buf);
3194 if ($c eq ('0'x40)) {
3195 croak "Penultimate record is all-zeroes in $map_path";
3198 close $fh or croak "close: $!";
3199 $want_commit ? ($r, $c) : $r;
3202 sub rev_map_get {
3203 my ($self, $rev, $uuid) = @_;
3204 my $map_path = $self->map_path($uuid);
3205 return undef unless -e $map_path;
3207 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3208 my $c = _rev_map_get($fh, $rev);
3209 close($fh) or croak "close: $!";
3213 sub _rev_map_get {
3214 my ($fh, $rev) = @_;
3216 binmode $fh or croak "binmode: $!";
3217 my $size = (stat($fh))[7];
3218 ($size % 24) == 0 or croak "inconsistent size: $size";
3220 if ($size == 0) {
3221 return undef;
3224 my ($l, $u) = (0, $size - 24);
3225 my ($r, $c, $buf);
3227 while ($l <= $u) {
3228 my $i = int(($l/24 + $u/24) / 2) * 24;
3229 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3230 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3231 my ($r, $c) = unpack('NH40', $buf);
3233 if ($r < $rev) {
3234 $l = $i + 24;
3235 } elsif ($r > $rev) {
3236 $u = $i - 24;
3237 } else { # $r == $rev
3238 return $c eq ('0' x 40) ? undef : $c;
3241 undef;
3244 # Finds the first svn revision that exists on (if $eq_ok is true) or
3245 # before $rev for the current branch. It will not search any lower
3246 # than $min_rev. Returns the git commit hash and svn revision number
3247 # if found, else (undef, undef).
3248 sub find_rev_before {
3249 my ($self, $rev, $eq_ok, $min_rev) = @_;
3250 --$rev unless $eq_ok;
3251 $min_rev ||= 1;
3252 my $max_rev = $self->rev_map_max;
3253 $rev = $max_rev if ($rev > $max_rev);
3254 while ($rev >= $min_rev) {
3255 if (my $c = $self->rev_map_get($rev)) {
3256 return ($rev, $c);
3258 --$rev;
3260 return (undef, undef);
3263 # Finds the first svn revision that exists on (if $eq_ok is true) or
3264 # after $rev for the current branch. It will not search any higher
3265 # than $max_rev. Returns the git commit hash and svn revision number
3266 # if found, else (undef, undef).
3267 sub find_rev_after {
3268 my ($self, $rev, $eq_ok, $max_rev) = @_;
3269 ++$rev unless $eq_ok;
3270 $max_rev ||= $self->rev_map_max;
3271 while ($rev <= $max_rev) {
3272 if (my $c = $self->rev_map_get($rev)) {
3273 return ($rev, $c);
3275 ++$rev;
3277 return (undef, undef);
3280 sub _new {
3281 my ($class, $repo_id, $ref_id, $path) = @_;
3282 unless (defined $repo_id && length $repo_id) {
3283 $repo_id = $Git::SVN::default_repo_id;
3285 unless (defined $ref_id && length $ref_id) {
3286 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3288 $_[1] = $repo_id;
3289 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3290 $_[3] = $path = '' unless (defined $path);
3291 mkpath(["$ENV{GIT_DIR}/svn"]);
3292 bless {
3293 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3294 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3295 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3298 # for read-only access of old .rev_db formats
3299 sub unlink_rev_db_symlink {
3300 my ($self) = @_;
3301 my $link = $self->rev_db_path;
3302 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3303 if (-l $link) {
3304 unlink $link or croak "unlink: $link failed!";
3308 sub rev_db_path {
3309 my ($self, $uuid) = @_;
3310 my $db_path = $self->map_path($uuid);
3311 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3312 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3313 $db_path;
3316 # the new replacement for .rev_db
3317 sub map_path {
3318 my ($self, $uuid) = @_;
3319 $uuid ||= $self->ra_uuid;
3320 "$self->{map_root}.$uuid";
3323 sub uri_encode {
3324 my ($f) = @_;
3325 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3329 sub remove_username {
3330 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3333 package Git::SVN::Prompt;
3334 use strict;
3335 use warnings;
3336 require SVN::Core;
3337 use vars qw/$_no_auth_cache $_username/;
3339 sub simple {
3340 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3341 $may_save = undef if $_no_auth_cache;
3342 $default_username = $_username if defined $_username;
3343 if (defined $default_username && length $default_username) {
3344 if (defined $realm && length $realm) {
3345 print STDERR "Authentication realm: $realm\n";
3346 STDERR->flush;
3348 $cred->username($default_username);
3349 } else {
3350 username($cred, $realm, $may_save, $pool);
3352 $cred->password(_read_password("Password for '" .