Merge branch 'cb/maint-orphan-merge-noclobber'
[git/kirr.git] / git-svn.perl
blob757de82161e05b9d12c489efeff05c7fec341fe4
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use 5.008;
5 use warnings;
6 use strict;
7 use vars qw/ $AUTHOR $VERSION
8 $sha1 $sha1_short $_revision $_repository
9 $_q $_authors $_authors_prog %users/;
10 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
11 $VERSION = '@@GIT_VERSION@@';
13 # From which subdir have we been invoked?
14 my $cmd_dir_prefix = eval {
15 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
16 } || '';
18 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
19 $ENV{GIT_DIR} ||= '.git';
20 $Git::SVN::default_repo_id = 'svn';
21 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
22 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::_minimize_url = 'unset';
25 if (! exists $ENV{SVN_SSH}) {
26 if (exists $ENV{GIT_SSH}) {
27 $ENV{SVN_SSH} = $ENV{GIT_SSH};
28 if ($^O eq 'msys') {
29 $ENV{SVN_SSH} =~ s/\\/\\\\/g;
30 $ENV{SVN_SSH} =~ s/(.*)/"$1"/;
35 $Git::SVN::Log::TZ = $ENV{TZ};
36 $ENV{TZ} = 'UTC';
37 $| = 1; # unbuffer STDOUT
39 sub fatal (@) { print STDERR "@_\n"; exit 1 }
40 sub _req_svn {
41 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
42 require SVN::Ra;
43 require SVN::Delta;
44 if ($SVN::Core::VERSION lt '1.1.0') {
45 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
48 my $can_compress = eval { require Compress::Zlib; 1};
49 push @Git::SVN::Ra::ISA, 'SVN::Ra';
50 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
51 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
52 use Carp qw/croak/;
53 use Digest::MD5;
54 use IO::File qw//;
55 use File::Basename qw/dirname basename/;
56 use File::Path qw/mkpath/;
57 use File::Spec;
58 use File::Find;
59 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
60 use IPC::Open3;
61 use Git;
63 BEGIN {
64 # import functions from Git into our packages, en masse
65 no strict 'refs';
66 foreach (qw/command command_oneline command_noisy command_output_pipe
67 command_input_pipe command_close_pipe
68 command_bidi_pipe command_close_bidi_pipe/) {
69 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
70 Git::SVN::Migration Git::SVN::Log Git::SVN),
71 __PACKAGE__) {
72 *{"${package}::$_"} = \&{"Git::$_"};
77 my ($SVN);
79 $sha1 = qr/[a-f\d]{40}/;
80 $sha1_short = qr/[a-f\d]{4,40}/;
81 my ($_stdin, $_help, $_edit,
82 $_message, $_file, $_branch_dest,
83 $_template, $_shared,
84 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
85 $_merge, $_strategy, $_dry_run, $_local,
86 $_prefix, $_no_checkout, $_url, $_verbose,
87 $_git_format, $_commit_url, $_tag);
88 $Git::SVN::_follow_parent = 1;
89 $_q ||= 0;
90 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
91 'config-dir=s' => \$Git::SVN::Ra::config_dir,
92 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
93 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
94 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
95 'authors-file|A=s' => \$_authors,
96 'authors-prog=s' => \$_authors_prog,
97 'repack:i' => \$Git::SVN::_repack,
98 'noMetadata' => \$Git::SVN::_no_metadata,
99 'useSvmProps' => \$Git::SVN::_use_svm_props,
100 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
101 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
102 'no-checkout' => \$_no_checkout,
103 'quiet|q+' => \$_q,
104 'repack-flags|repack-args|repack-opts=s' =>
105 \$Git::SVN::_repack_flags,
106 'use-log-author' => \$Git::SVN::_use_log_author,
107 'add-author-from' => \$Git::SVN::_add_author_from,
108 'localtime' => \$Git::SVN::_localtime,
109 %remote_opts );
111 my ($_trunk, @_tags, @_branches, $_stdlayout);
112 my %icv;
113 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
114 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
115 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
116 'stdlayout|s' => \$_stdlayout,
117 'minimize-url|m!' => \$Git::SVN::_minimize_url,
118 'no-metadata' => sub { $icv{noMetadata} = 1 },
119 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
120 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
121 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
122 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
123 %remote_opts );
124 my %cmt_opts = ( 'edit|e' => \$_edit,
125 'rmdir' => \$SVN::Git::Editor::_rmdir,
126 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
127 'l=i' => \$SVN::Git::Editor::_rename_limit,
128 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
131 my %cmd = (
132 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
133 { 'revision|r=s' => \$_revision,
134 'fetch-all|all' => \$_fetch_all,
135 'parent|p' => \$_fetch_parent,
136 %fc_opts } ],
137 clone => [ \&cmd_clone, "Initialize and fetch revisions",
138 { 'revision|r=s' => \$_revision,
139 %fc_opts, %init_opts } ],
140 init => [ \&cmd_init, "Initialize a repo for tracking" .
141 " (requires URL argument)",
142 \%init_opts ],
143 'multi-init' => [ \&cmd_multi_init,
144 "Deprecated alias for ".
145 "'$0 init -T<trunk> -b<branches> -t<tags>'",
146 \%init_opts ],
147 dcommit => [ \&cmd_dcommit,
148 'Commit several diffs to merge with upstream',
149 { 'merge|m|M' => \$_merge,
150 'strategy|s=s' => \$_strategy,
151 'verbose|v' => \$_verbose,
152 'dry-run|n' => \$_dry_run,
153 'fetch-all|all' => \$_fetch_all,
154 'commit-url=s' => \$_commit_url,
155 'revision|r=i' => \$_revision,
156 'no-rebase' => \$_no_rebase,
157 %cmt_opts, %fc_opts } ],
158 branch => [ \&cmd_branch,
159 'Create a branch in the SVN repository',
160 { 'message|m=s' => \$_message,
161 'destination|d=s' => \$_branch_dest,
162 'dry-run|n' => \$_dry_run,
163 'tag|t' => \$_tag,
164 'username=s' => \$Git::SVN::Prompt::_username,
165 'commit-url=s' => \$_commit_url } ],
166 tag => [ sub { $_tag = 1; cmd_branch(@_) },
167 'Create a tag in the SVN repository',
168 { 'message|m=s' => \$_message,
169 'destination|d=s' => \$_branch_dest,
170 'dry-run|n' => \$_dry_run,
171 'username=s' => \$Git::SVN::Prompt::_username,
172 'commit-url=s' => \$_commit_url } ],
173 'set-tree' => [ \&cmd_set_tree,
174 "Set an SVN repository to a git tree-ish",
175 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
176 'create-ignore' => [ \&cmd_create_ignore,
177 'Create a .gitignore per svn:ignore',
178 { 'revision|r=i' => \$_revision
179 } ],
180 'mkdirs' => [ \&cmd_mkdirs ,
181 "recreate empty directories after a checkout",
182 { 'revision|r=i' => \$_revision } ],
183 'propget' => [ \&cmd_propget,
184 'Print the value of a property on a file or directory',
185 { 'revision|r=i' => \$_revision } ],
186 'proplist' => [ \&cmd_proplist,
187 'List all properties of a file or directory',
188 { 'revision|r=i' => \$_revision } ],
189 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
190 { 'revision|r=i' => \$_revision
191 } ],
192 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
193 { 'revision|r=i' => \$_revision
194 } ],
195 'multi-fetch' => [ \&cmd_multi_fetch,
196 "Deprecated alias for $0 fetch --all",
197 { 'revision|r=s' => \$_revision, %fc_opts } ],
198 'migrate' => [ sub { },
199 # no-op, we automatically run this anyways,
200 'Migrate configuration/metadata/layout from
201 previous versions of git-svn',
202 { 'minimize' => \$Git::SVN::Migration::_minimize,
203 %remote_opts } ],
204 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
205 { 'limit=i' => \$Git::SVN::Log::limit,
206 'revision|r=s' => \$_revision,
207 'verbose|v' => \$Git::SVN::Log::verbose,
208 'incremental' => \$Git::SVN::Log::incremental,
209 'oneline' => \$Git::SVN::Log::oneline,
210 'show-commit' => \$Git::SVN::Log::show_commit,
211 'non-recursive' => \$Git::SVN::Log::non_recursive,
212 'authors-file|A=s' => \$_authors,
213 'color' => \$Git::SVN::Log::color,
214 'pager=s' => \$Git::SVN::Log::pager
215 } ],
216 'find-rev' => [ \&cmd_find_rev,
217 "Translate between SVN revision numbers and tree-ish",
218 {} ],
219 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
220 { 'merge|m|M' => \$_merge,
221 'verbose|v' => \$_verbose,
222 'strategy|s=s' => \$_strategy,
223 'local|l' => \$_local,
224 'fetch-all|all' => \$_fetch_all,
225 'dry-run|n' => \$_dry_run,
226 %fc_opts } ],
227 'commit-diff' => [ \&cmd_commit_diff,
228 'Commit a diff between two trees',
229 { 'message|m=s' => \$_message,
230 'file|F=s' => \$_file,
231 'revision|r=s' => \$_revision,
232 %cmt_opts } ],
233 'info' => [ \&cmd_info,
234 "Show info about the latest SVN revision
235 on the current branch",
236 { 'url' => \$_url, } ],
237 'blame' => [ \&Git::SVN::Log::cmd_blame,
238 "Show what revision and author last modified each line of a file",
239 { 'git-format' => \$_git_format } ],
240 'reset' => [ \&cmd_reset,
241 "Undo fetches back to the specified SVN revision",
242 { 'revision|r=s' => \$_revision,
243 'parent|p' => \$_fetch_parent } ],
244 'gc' => [ \&cmd_gc,
245 "Compress unhandled.log files in .git/svn and remove " .
246 "index files in .git/svn",
247 {} ],
250 my $cmd;
251 for (my $i = 0; $i < @ARGV; $i++) {
252 if (defined $cmd{$ARGV[$i]}) {
253 $cmd = $ARGV[$i];
254 splice @ARGV, $i, 1;
255 last;
256 } elsif ($ARGV[$i] eq 'help') {
257 $cmd = $ARGV[$i+1];
258 usage(0);
262 # make sure we're always running at the top-level working directory
263 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
264 unless (-d $ENV{GIT_DIR}) {
265 if ($git_dir_user_set) {
266 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
267 "but it is not a directory\n";
269 my $git_dir = delete $ENV{GIT_DIR};
270 my $cdup = undef;
271 git_cmd_try {
272 $cdup = command_oneline(qw/rev-parse --show-cdup/);
273 $git_dir = '.' unless ($cdup);
274 chomp $cdup if ($cdup);
275 $cdup = "." unless ($cdup && length $cdup);
276 } "Already at toplevel, but $git_dir not found\n";
277 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
278 unless (-d $git_dir) {
279 die "$git_dir still not found after going to ",
280 "'$cdup'\n";
282 $ENV{GIT_DIR} = $git_dir;
284 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
287 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
289 read_git_config(\%opts);
290 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
291 Getopt::Long::Configure('pass_through');
293 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
294 'minimize-connections' => \$Git::SVN::Migration::_minimize,
295 'id|i=s' => \$Git::SVN::default_ref_id,
296 'svn-remote|remote|R=s' => sub {
297 $Git::SVN::no_reuse_existing = 1;
298 $Git::SVN::default_repo_id = $_[1] });
299 exit 1 if (!$rv && $cmd && $cmd ne 'log');
301 usage(0) if $_help;
302 version() if $_version;
303 usage(1) unless defined $cmd;
304 load_authors() if $_authors;
305 if (defined $_authors_prog) {
306 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
309 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
310 Git::SVN::Migration::migration_check();
312 Git::SVN::init_vars();
313 eval {
314 Git::SVN::verify_remotes_sanity();
315 $cmd{$cmd}->[0]->(@ARGV);
317 fatal $@ if $@;
318 post_fetch_checkout();
319 exit 0;
321 ####################### primary functions ######################
322 sub usage {
323 my $exit = shift || 0;
324 my $fd = $exit ? \*STDERR : \*STDOUT;
325 print $fd <<"";
326 git-svn - bidirectional operations between a single Subversion tree and git
327 Usage: git svn <command> [options] [arguments]\n
329 print $fd "Available commands:\n" unless $cmd;
331 foreach (sort keys %cmd) {
332 next if $cmd && $cmd ne $_;
333 next if /^multi-/; # don't show deprecated commands
334 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
335 foreach (sort keys %{$cmd{$_}->[2]}) {
336 # mixed-case options are for .git/config only
337 next if /[A-Z]/ && /^[a-z]+$/i;
338 # prints out arguments as they should be passed:
339 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
340 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
341 "--$_" : "-$_" }
342 split /\|/,$_)," $x\n";
345 print $fd <<"";
346 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
347 arbitrary identifier if you're tracking multiple SVN branches/repositories in
348 one git repository and want to keep them separate. See git-svn(1) for more
349 information.
351 exit $exit;
354 sub version {
355 ::_req_svn();
356 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
357 exit 0;
360 sub do_git_init_db {
361 unless (-d $ENV{GIT_DIR}) {
362 my @init_db = ('init');
363 push @init_db, "--template=$_template" if defined $_template;
364 if (defined $_shared) {
365 if ($_shared =~ /[a-z]/) {
366 push @init_db, "--shared=$_shared";
367 } else {
368 push @init_db, "--shared";
371 command_noisy(@init_db);
372 $_repository = Git->repository(Repository => ".git");
374 my $set;
375 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
376 foreach my $i (keys %icv) {
377 die "'$set' and '$i' cannot both be set\n" if $set;
378 next unless defined $icv{$i};
379 command_noisy('config', "$pfx.$i", $icv{$i});
380 $set = $i;
382 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
383 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
384 if defined $$ignore_regex;
387 sub init_subdir {
388 my $repo_path = shift or return;
389 mkpath([$repo_path]) unless -d $repo_path;
390 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
391 $ENV{GIT_DIR} = '.git';
392 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
395 sub cmd_clone {
396 my ($url, $path) = @_;
397 if (!defined $path &&
398 (defined $_trunk || @_branches || @_tags ||
399 defined $_stdlayout) &&
400 $url !~ m#^[a-z\+]+://#) {
401 $path = $url;
403 $path = basename($url) if !defined $path || !length $path;
404 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
405 cmd_init($url, $path);
406 command_oneline('config', 'svn.authorsfile', $authors_absolute)
407 if $_authors;
408 Git::SVN::fetch_all($Git::SVN::default_repo_id);
411 sub cmd_init {
412 if (defined $_stdlayout) {
413 $_trunk = 'trunk' if (!defined $_trunk);
414 @_tags = 'tags' if (! @_tags);
415 @_branches = 'branches' if (! @_branches);
417 if (defined $_trunk || @_branches || @_tags) {
418 return cmd_multi_init(@_);
420 my $url = shift or die "SVN repository location required ",
421 "as a command-line argument\n";
422 $url = canonicalize_url($url);
423 init_subdir(@_);
424 do_git_init_db();
426 if ($Git::SVN::_minimize_url eq 'unset') {
427 $Git::SVN::_minimize_url = 0;
430 Git::SVN->init($url);
433 sub cmd_fetch {
434 if (grep /^\d+=./, @_) {
435 die "'<rev>=<commit>' fetch arguments are ",
436 "no longer supported.\n";
438 my ($remote) = @_;
439 if (@_ > 1) {
440 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
442 $Git::SVN::no_reuse_existing = undef;
443 if ($_fetch_parent) {
444 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
445 unless ($gs) {
446 die "Unable to determine upstream SVN information from ",
447 "working tree history\n";
449 # just fetch, don't checkout.
450 $_no_checkout = 'true';
451 $_fetch_all ? $gs->fetch_all : $gs->fetch;
452 } elsif ($_fetch_all) {
453 cmd_multi_fetch();
454 } else {
455 $remote ||= $Git::SVN::default_repo_id;
456 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
460 sub cmd_set_tree {
461 my (@commits) = @_;
462 if ($_stdin || !@commits) {
463 print "Reading from stdin...\n";
464 @commits = ();
465 while (<STDIN>) {
466 if (/\b($sha1_short)\b/o) {
467 unshift @commits, $1;
471 my @revs;
472 foreach my $c (@commits) {
473 my @tmp = command('rev-parse',$c);
474 if (scalar @tmp == 1) {
475 push @revs, $tmp[0];
476 } elsif (scalar @tmp > 1) {
477 push @revs, reverse(command('rev-list',@tmp));
478 } else {
479 fatal "Failed to rev-parse $c";
482 my $gs = Git::SVN->new;
483 my ($r_last, $cmt_last) = $gs->last_rev_commit;
484 $gs->fetch;
485 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
486 fatal "There are new revisions that were fetched ",
487 "and need to be merged (or acknowledged) ",
488 "before committing.\nlast rev: $r_last\n",
489 " current: $gs->{last_rev}";
491 $gs->set_tree($_) foreach @revs;
492 print "Done committing ",scalar @revs," revisions to SVN\n";
493 unlink $gs->{index};
496 sub cmd_dcommit {
497 my $head = shift;
498 command_noisy(qw/update-index --refresh/);
499 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
500 'Cannot dcommit with a dirty index. Commit your changes first, '
501 . "or stash them with `git stash'.\n";
502 $head ||= 'HEAD';
504 my $old_head;
505 if ($head ne 'HEAD') {
506 $old_head = eval {
507 command_oneline([qw/symbolic-ref -q HEAD/])
509 if ($old_head) {
510 $old_head =~ s{^refs/heads/}{};
511 } else {
512 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
514 command(['checkout', $head], STDERR => 0);
517 my @refs;
518 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
519 unless ($gs) {
520 die "Unable to determine upstream SVN information from ",
521 "$head history.\nPerhaps the repository is empty.";
524 if (defined $_commit_url) {
525 $url = $_commit_url;
526 } else {
527 $url = eval { command_oneline('config', '--get',
528 "svn-remote.$gs->{repo_id}.commiturl") };
529 if (!$url) {
530 $url = $gs->full_url
534 my $last_rev = $_revision if defined $_revision;
535 if ($url) {
536 print "Committing to $url ...\n";
538 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
539 if ($_no_rebase && scalar(@$linear_refs) > 1) {
540 warn "Attempting to commit more than one change while ",
541 "--no-rebase is enabled.\n",
542 "If these changes depend on each other, re-running ",
543 "without --no-rebase may be required."
545 my $expect_url = $url;
546 Git::SVN::remove_username($expect_url);
547 while (1) {
548 my $d = shift @$linear_refs or last;
549 unless (defined $last_rev) {
550 (undef, $last_rev, undef) = cmt_metadata("$d~1");
551 unless (defined $last_rev) {
552 fatal "Unable to extract revision information ",
553 "from commit $d~1";
556 if ($_dry_run) {
557 print "diff-tree $d~1 $d\n";
558 } else {
559 my $cmt_rev;
560 my %ed_opts = ( r => $last_rev,
561 log => get_commit_entry($d)->{log},
562 ra => Git::SVN::Ra->new($url),
563 config => SVN::Core::config_get_config(
564 $Git::SVN::Ra::config_dir
566 tree_a => "$d~1",
567 tree_b => $d,
568 editor_cb => sub {
569 print "Committed r$_[0]\n";
570 $cmt_rev = $_[0];
572 svn_path => '');
573 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
574 print "No changes\n$d~1 == $d\n";
575 } elsif ($parents->{$d} && @{$parents->{$d}}) {
576 $gs->{inject_parents_dcommit}->{$cmt_rev} =
577 $parents->{$d};
579 $_fetch_all ? $gs->fetch_all : $gs->fetch;
580 $last_rev = $cmt_rev;
581 next if $_no_rebase;
583 # we always want to rebase against the current HEAD,
584 # not any head that was passed to us
585 my @diff = command('diff-tree', $d,
586 $gs->refname, '--');
587 my @finish;
588 if (@diff) {
589 @finish = rebase_cmd();
590 print STDERR "W: $d and ", $gs->refname,
591 " differ, using @finish:\n",
592 join("\n", @diff), "\n";
593 } else {
594 print "No changes between current HEAD and ",
595 $gs->refname,
596 "\nResetting to the latest ",
597 $gs->refname, "\n";
598 @finish = qw/reset --mixed/;
600 command_noisy(@finish, $gs->refname);
601 if (@diff) {
602 @refs = ();
603 my ($url_, $rev_, $uuid_, $gs_) =
604 working_head_info('HEAD', \@refs);
605 my ($linear_refs_, $parents_) =
606 linearize_history($gs_, \@refs);
607 if (scalar(@$linear_refs) !=
608 scalar(@$linear_refs_)) {
609 fatal "# of revisions changed ",
610 "\nbefore:\n",
611 join("\n", @$linear_refs),
612 "\n\nafter:\n",
613 join("\n", @$linear_refs_), "\n",
614 'If you are attempting to commit ',
615 "merges, try running:\n\t",
616 'git rebase --interactive',
617 '--preserve-merges ',
618 $gs->refname,
619 "\nBefore dcommitting";
621 if ($url_ ne $expect_url) {
622 if ($url_ eq $gs->metadata_url) {
623 print
624 "Accepting rewritten URL:",
625 " $url_\n";
626 } else {
627 fatal
628 "URL mismatch after rebase:",
629 " $url_ != $expect_url";
632 if ($uuid_ ne $uuid) {
633 fatal "uuid mismatch after rebase: ",
634 "$uuid_ != $uuid";
636 # remap parents
637 my (%p, @l, $i);
638 for ($i = 0; $i < scalar @$linear_refs; $i++) {
639 my $new = $linear_refs_->[$i] or next;
640 $p{$new} =
641 $parents->{$linear_refs->[$i]};
642 push @l, $new;
644 $parents = \%p;
645 $linear_refs = \@l;
650 if ($old_head) {
651 my $new_head = command_oneline(qw/rev-parse HEAD/);
652 my $new_is_symbolic = eval {
653 command_oneline(qw/symbolic-ref -q HEAD/);
655 if ($new_is_symbolic) {
656 print "dcommitted the branch ", $head, "\n";
657 } else {
658 print "dcommitted on a detached HEAD because you gave ",
659 "a revision argument.\n",
660 "The rewritten commit is: ", $new_head, "\n";
662 command(['checkout', $old_head], STDERR => 0);
665 unlink $gs->{index};
668 sub cmd_branch {
669 my ($branch_name, $head) = @_;
671 unless (defined $branch_name && length $branch_name) {
672 die(($_tag ? "tag" : "branch") . " name required\n");
674 $head ||= 'HEAD';
676 my (undef, $rev, undef, $gs) = working_head_info($head);
677 my $src = $gs->full_url;
679 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
680 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
681 my $glob;
682 if ($#{$allglobs} == 0) {
683 $glob = $allglobs->[0];
684 } else {
685 unless(defined $_branch_dest) {
686 die "Multiple ",
687 $_tag ? "tag" : "branch",
688 " paths defined for Subversion repository.\n",
689 "You must specify where you want to create the ",
690 $_tag ? "tag" : "branch",
691 " with the --destination argument.\n";
693 foreach my $g (@{$allglobs}) {
694 # SVN::Git::Editor could probably be moved to Git.pm..
695 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
696 if ($_branch_dest =~ /$re/) {
697 $glob = $g;
698 last;
701 unless (defined $glob) {
702 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
703 foreach my $g (@{$allglobs}) {
704 $g->{path}->{left} =~ /$dest_re/ or next;
705 if (defined $glob) {
706 die "Ambiguous destination: ",
707 $_branch_dest, "\nmatches both '",
708 $glob->{path}->{left}, "' and '",
709 $g->{path}->{left}, "'\n";
711 $glob = $g;
713 unless (defined $glob) {
714 die "Unknown ",
715 $_tag ? "tag" : "branch",
716 " destination $_branch_dest\n";
720 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
721 my $url;
722 if (defined $_commit_url) {
723 $url = $_commit_url;
724 } else {
725 $url = eval { command_oneline('config', '--get',
726 "svn-remote.$gs->{repo_id}.commiturl") };
727 if (!$url) {
728 $url = $remote->{url};
731 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
733 if ($dst =~ /^https:/ && $src =~ /^http:/) {
734 $src=~s/^http:/https:/;
737 ::_req_svn();
739 my $ctx = SVN::Client->new(
740 auth => Git::SVN::Ra::_auth_providers(),
741 log_msg => sub {
742 ${ $_[0] } = defined $_message
743 ? $_message
744 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
745 . $branch_name;
749 eval {
750 $ctx->ls($dst, 'HEAD', 0);
751 } and die "branch ${branch_name} already exists\n";
753 print "Copying ${src} at r${rev} to ${dst}...\n";
754 $ctx->copy($src, $rev, $dst)
755 unless $_dry_run;
757 $gs->fetch_all;
760 sub cmd_find_rev {
761 my $revision_or_hash = shift or die "SVN or git revision required ",
762 "as a command-line argument\n";
763 my $result;
764 if ($revision_or_hash =~ /^r\d+$/) {
765 my $head = shift;
766 $head ||= 'HEAD';
767 my @refs;
768 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
769 unless ($gs) {
770 die "Unable to determine upstream SVN information from ",
771 "$head history\n";
773 my $desired_revision = substr($revision_or_hash, 1);
774 $result = $gs->rev_map_get($desired_revision, $uuid);
775 } else {
776 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
777 $result = $rev;
779 print "$result\n" if $result;
782 sub cmd_rebase {
783 command_noisy(qw/update-index --refresh/);
784 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
785 unless ($gs) {
786 die "Unable to determine upstream SVN information from ",
787 "working tree history\n";
789 if ($_dry_run) {
790 print "Remote Branch: " . $gs->refname . "\n";
791 print "SVN URL: " . $url . "\n";
792 return;
794 if (command(qw/diff-index HEAD --/)) {
795 print STDERR "Cannot rebase with uncommited changes:\n";
796 command_noisy('status');
797 exit 1;
799 unless ($_local) {
800 # rebase will checkout for us, so no need to do it explicitly
801 $_no_checkout = 'true';
802 $_fetch_all ? $gs->fetch_all : $gs->fetch;
804 command_noisy(rebase_cmd(), $gs->refname);
805 $gs->mkemptydirs;
808 sub cmd_show_ignore {
809 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
810 $gs ||= Git::SVN->new;
811 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
812 $gs->prop_walk($gs->{path}, $r, sub {
813 my ($gs, $path, $props) = @_;
814 print STDOUT "\n# $path\n";
815 my $s = $props->{'svn:ignore'} or return;
816 $s =~ s/[\r\n]+/\n/g;
817 $s =~ s/^\n+//;
818 chomp $s;
819 $s =~ s#^#$path#gm;
820 print STDOUT "$s\n";
824 sub cmd_show_externals {
825 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
826 $gs ||= Git::SVN->new;
827 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
828 $gs->prop_walk($gs->{path}, $r, sub {
829 my ($gs, $path, $props) = @_;
830 print STDOUT "\n# $path\n";
831 my $s = $props->{'svn:externals'} or return;
832 $s =~ s/[\r\n]+/\n/g;
833 chomp $s;
834 $s =~ s#^#$path#gm;
835 print STDOUT "$s\n";
839 sub cmd_create_ignore {
840 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
841 $gs ||= Git::SVN->new;
842 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
843 $gs->prop_walk($gs->{path}, $r, sub {
844 my ($gs, $path, $props) = @_;
845 # $path is of the form /path/to/dir/
846 $path = '.' . $path;
847 # SVN can have attributes on empty directories,
848 # which git won't track
849 mkpath([$path]) unless -d $path;
850 my $ignore = $path . '.gitignore';
851 my $s = $props->{'svn:ignore'} or return;
852 open(GITIGNORE, '>', $ignore)
853 or fatal("Failed to open `$ignore' for writing: $!");
854 $s =~ s/[\r\n]+/\n/g;
855 $s =~ s/^\n+//;
856 chomp $s;
857 # Prefix all patterns so that the ignore doesn't apply
858 # to sub-directories.
859 $s =~ s#^#/#gm;
860 print GITIGNORE "$s\n";
861 close(GITIGNORE)
862 or fatal("Failed to close `$ignore': $!");
863 command_noisy('add', '-f', $ignore);
867 sub cmd_mkdirs {
868 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
869 $gs ||= Git::SVN->new;
870 $gs->mkemptydirs($_revision);
873 sub canonicalize_path {
874 my ($path) = @_;
875 my $dot_slash_added = 0;
876 if (substr($path, 0, 1) ne "/") {
877 $path = "./" . $path;
878 $dot_slash_added = 1;
880 # File::Spec->canonpath doesn't collapse x/../y into y (for a
881 # good reason), so let's do this manually.
882 $path =~ s#/+#/#g;
883 $path =~ s#/\.(?:/|$)#/#g;
884 $path =~ s#/[^/]+/\.\.##g;
885 $path =~ s#/$##g;
886 $path =~ s#^\./## if $dot_slash_added;
887 $path =~ s#^/##;
888 $path =~ s#^\.$##;
889 return $path;
892 sub canonicalize_url {
893 my ($url) = @_;
894 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
895 return $url;
898 # get_svnprops(PATH)
899 # ------------------
900 # Helper for cmd_propget and cmd_proplist below.
901 sub get_svnprops {
902 my $path = shift;
903 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
904 $gs ||= Git::SVN->new;
906 # prefix THE PATH by the sub-directory from which the user
907 # invoked us.
908 $path = $cmd_dir_prefix . $path;
909 fatal("No such file or directory: $path") unless -e $path;
910 my $is_dir = -d $path ? 1 : 0;
911 $path = $gs->{path} . '/' . $path;
913 # canonicalize the path (otherwise libsvn will abort or fail to
914 # find the file)
915 $path = canonicalize_path($path);
917 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
918 my $props;
919 if ($is_dir) {
920 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
922 else {
923 (undef, $props) = $gs->ra->get_file($path, $r, undef);
925 return $props;
928 # cmd_propget (PROP, PATH)
929 # ------------------------
930 # Print the SVN property PROP for PATH.
931 sub cmd_propget {
932 my ($prop, $path) = @_;
933 $path = '.' if not defined $path;
934 usage(1) if not defined $prop;
935 my $props = get_svnprops($path);
936 if (not defined $props->{$prop}) {
937 fatal("`$path' does not have a `$prop' SVN property.");
939 print $props->{$prop} . "\n";
942 # cmd_proplist (PATH)
943 # -------------------
944 # Print the list of SVN properties for PATH.
945 sub cmd_proplist {
946 my $path = shift;
947 $path = '.' if not defined $path;
948 my $props = get_svnprops($path);
949 print "Properties on '$path':\n";
950 foreach (sort keys %{$props}) {
951 print " $_\n";
955 sub cmd_multi_init {
956 my $url = shift;
957 unless (defined $_trunk || @_branches || @_tags) {
958 usage(1);
961 $_prefix = '' unless defined $_prefix;
962 if (defined $url) {
963 $url = canonicalize_url($url);
964 init_subdir(@_);
966 do_git_init_db();
967 if (defined $_trunk) {
968 $_trunk =~ s#^/+##;
969 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
970 # try both old-style and new-style lookups:
971 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
972 unless ($gs_trunk) {
973 my ($trunk_url, $trunk_path) =
974 complete_svn_url($url, $_trunk);
975 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
976 undef, $trunk_ref);
979 return unless @_branches || @_tags;
980 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
981 foreach my $path (@_branches) {
982 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
984 foreach my $path (@_tags) {
985 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
989 sub cmd_multi_fetch {
990 $Git::SVN::no_reuse_existing = undef;
991 my $remotes = Git::SVN::read_all_remotes();
992 foreach my $repo_id (sort keys %$remotes) {
993 if ($remotes->{$repo_id}->{url}) {
994 Git::SVN::fetch_all($repo_id, $remotes);
999 # this command is special because it requires no metadata
1000 sub cmd_commit_diff {
1001 my ($ta, $tb, $url) = @_;
1002 my $usage = "Usage: $0 commit-diff -r<revision> ".
1003 "<tree-ish> <tree-ish> [<URL>]";
1004 fatal($usage) if (!defined $ta || !defined $tb);
1005 my $svn_path = '';
1006 if (!defined $url) {
1007 my $gs = eval { Git::SVN->new };
1008 if (!$gs) {
1009 fatal("Needed URL or usable git-svn --id in ",
1010 "the command-line\n", $usage);
1012 $url = $gs->{url};
1013 $svn_path = $gs->{path};
1015 unless (defined $_revision) {
1016 fatal("-r|--revision is a required argument\n", $usage);
1018 if (defined $_message && defined $_file) {
1019 fatal("Both --message/-m and --file/-F specified ",
1020 "for the commit message.\n",
1021 "I have no idea what you mean");
1023 if (defined $_file) {
1024 $_message = file_to_s($_file);
1025 } else {
1026 $_message ||= get_commit_entry($tb)->{log};
1028 my $ra ||= Git::SVN::Ra->new($url);
1029 my $r = $_revision;
1030 if ($r eq 'HEAD') {
1031 $r = $ra->get_latest_revnum;
1032 } elsif ($r !~ /^\d+$/) {
1033 die "revision argument: $r not understood by git-svn\n";
1035 my %ed_opts = ( r => $r,
1036 log => $_message,
1037 ra => $ra,
1038 tree_a => $ta,
1039 tree_b => $tb,
1040 editor_cb => sub { print "Committed r$_[0]\n" },
1041 svn_path => $svn_path );
1042 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1043 print "No changes\n$ta == $tb\n";
1047 sub escape_uri_only {
1048 my ($uri) = @_;
1049 my @tmp;
1050 foreach (split m{/}, $uri) {
1051 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1052 push @tmp, $_;
1054 join('/', @tmp);
1057 sub escape_url {
1058 my ($url) = @_;
1059 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1060 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1061 $url = "$scheme://$domain$uri";
1063 $url;
1066 sub cmd_info {
1067 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1068 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1069 if (exists $_[1]) {
1070 die "Too many arguments specified\n";
1073 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1075 if (!$file_type && !$diff_status) {
1076 print STDERR "svn: '$path' is not under version control\n";
1077 exit 1;
1080 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1081 unless ($gs) {
1082 die "Unable to determine upstream SVN information from ",
1083 "working tree history\n";
1086 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1087 $path = "." if $path eq "";
1089 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1091 if ($_url) {
1092 print escape_url($full_url), "\n";
1093 return;
1096 my $result = "Path: $path\n";
1097 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1098 $result .= "URL: " . escape_url($full_url) . "\n";
1100 eval {
1101 my $repos_root = $gs->repos_root;
1102 Git::SVN::remove_username($repos_root);
1103 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1105 if ($@) {
1106 $result .= "Repository Root: (offline)\n";
1108 ::_req_svn();
1109 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1110 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1111 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1113 $result .= "Node Kind: " .
1114 ($file_type eq "dir" ? "directory" : "file") . "\n";
1116 my $schedule = $diff_status eq "A"
1117 ? "add"
1118 : ($diff_status eq "D" ? "delete" : "normal");
1119 $result .= "Schedule: $schedule\n";
1121 if ($diff_status eq "A") {
1122 print $result, "\n";
1123 return;
1126 my ($lc_author, $lc_rev, $lc_date_utc);
1127 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1128 my $log = command_output_pipe(@args);
1129 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1130 while (<$log>) {
1131 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1132 $lc_author = $1;
1133 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1134 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1135 (undef, $lc_rev, undef) = ::extract_metadata($1);
1138 close $log;
1140 Git::SVN::Log::set_local_timezone();
1142 $result .= "Last Changed Author: $lc_author\n";
1143 $result .= "Last Changed Rev: $lc_rev\n";
1144 $result .= "Last Changed Date: " .
1145 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1147 if ($file_type ne "dir") {
1148 my $text_last_updated_date =
1149 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1150 $result .=
1151 "Text Last Updated: " .
1152 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1153 "\n";
1154 my $checksum;
1155 if ($diff_status eq "D") {
1156 my ($fh, $ctx) =
1157 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1158 if ($file_type eq "link") {
1159 my $file_name = <$fh>;
1160 $checksum = md5sum("link $file_name");
1161 } else {
1162 $checksum = md5sum($fh);
1164 command_close_pipe($fh, $ctx);
1165 } elsif ($file_type eq "link") {
1166 my $file_name =
1167 command(qw(cat-file blob), "HEAD:$path");
1168 $checksum =
1169 md5sum("link " . $file_name);
1170 } else {
1171 open FILE, "<", $path or die $!;
1172 $checksum = md5sum(\*FILE);
1173 close FILE or die $!;
1175 $result .= "Checksum: " . $checksum . "\n";
1178 print $result, "\n";
1181 sub cmd_reset {
1182 my $target = shift || $_revision or die "SVN revision required\n";
1183 $target = $1 if $target =~ /^r(\d+)$/;
1184 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1185 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1186 unless ($gs) {
1187 die "Unable to determine upstream SVN information from ".
1188 "history\n";
1190 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1191 die "Cannot find SVN revision $target\n" unless defined($c);
1192 $gs->rev_map_set($r, $c, 'reset', $uuid);
1193 print "r$r = $c ($gs->{ref_id})\n";
1196 sub cmd_gc {
1197 if (!$can_compress) {
1198 warn "Compress::Zlib could not be found; unhandled.log " .
1199 "files will not be compressed.\n";
1201 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1204 ########################### utility functions #########################
1206 sub rebase_cmd {
1207 my @cmd = qw/rebase/;
1208 push @cmd, '-v' if $_verbose;
1209 push @cmd, qw/--merge/ if $_merge;
1210 push @cmd, "--strategy=$_strategy" if $_strategy;
1211 @cmd;
1214 sub post_fetch_checkout {
1215 return if $_no_checkout;
1216 my $gs = $Git::SVN::_head or return;
1217 return if verify_ref('refs/heads/master^0');
1219 # look for "trunk" ref if it exists
1220 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1221 my $fetch = $remote->{fetch};
1222 if ($fetch) {
1223 foreach my $p (keys %$fetch) {
1224 basename($fetch->{$p}) eq 'trunk' or next;
1225 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1226 last;
1230 my $valid_head = verify_ref('HEAD^0');
1231 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1232 return if ($valid_head || !verify_ref('HEAD^0'));
1234 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1235 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1236 return if -f $index;
1238 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1239 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1240 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1241 print STDERR "Checked out HEAD:\n ",
1242 $gs->full_url, " r", $gs->last_rev, "\n";
1243 $gs->mkemptydirs($gs->last_rev);
1246 sub complete_svn_url {
1247 my ($url, $path) = @_;
1248 $path =~ s#/+$##;
1249 if ($path !~ m#^[a-z\+]+://#) {
1250 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1251 fatal("E: '$path' is not a complete URL ",
1252 "and a separate URL is not specified");
1254 return ($url, $path);
1256 return ($path, '');
1259 sub complete_url_ls_init {
1260 my ($ra, $repo_path, $switch, $pfx) = @_;
1261 unless ($repo_path) {
1262 print STDERR "W: $switch not specified\n";
1263 return;
1265 $repo_path =~ s#/+$##;
1266 if ($repo_path =~ m#^[a-z\+]+://#) {
1267 $ra = Git::SVN::Ra->new($repo_path);
1268 $repo_path = '';
1269 } else {
1270 $repo_path =~ s#^/+##;
1271 unless ($ra) {
1272 fatal("E: '$repo_path' is not a complete URL ",
1273 "and a separate URL is not specified");
1276 my $url = $ra->{url};
1277 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1278 my $k = "svn-remote.$gs->{repo_id}.url";
1279 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1280 if ($orig_url && ($orig_url ne $gs->{url})) {
1281 die "$k already set: $orig_url\n",
1282 "wanted to set to: $gs->{url}\n";
1284 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1285 my $remote_path = "$gs->{path}/$repo_path";
1286 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1287 $remote_path =~ s#/+#/#g;
1288 $remote_path =~ s#^/##g;
1289 $remote_path .= "/*" if $remote_path !~ /\*/;
1290 my ($n) = ($switch =~ /^--(\w+)/);
1291 if (length $pfx && $pfx !~ m#/$#) {
1292 die "--prefix='$pfx' must have a trailing slash '/'\n";
1294 command_noisy('config',
1295 '--add',
1296 "svn-remote.$gs->{repo_id}.$n",
1297 "$remote_path:refs/remotes/$pfx*" .
1298 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1301 sub verify_ref {
1302 my ($ref) = @_;
1303 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1304 { STDERR => 0 }); };
1307 sub get_tree_from_treeish {
1308 my ($treeish) = @_;
1309 # $treeish can be a symbolic ref, too:
1310 my $type = command_oneline(qw/cat-file -t/, $treeish);
1311 my $expected;
1312 while ($type eq 'tag') {
1313 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1315 if ($type eq 'commit') {
1316 $expected = (grep /^tree /, command(qw/cat-file commit/,
1317 $treeish))[0];
1318 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1319 die "Unable to get tree from $treeish\n" unless $expected;
1320 } elsif ($type eq 'tree') {
1321 $expected = $treeish;
1322 } else {
1323 die "$treeish is a $type, expected tree, tag or commit\n";
1325 return $expected;
1328 sub get_commit_entry {
1329 my ($treeish) = shift;
1330 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1331 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1332 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1333 open my $log_fh, '>', $commit_editmsg or croak $!;
1335 my $type = command_oneline(qw/cat-file -t/, $treeish);
1336 if ($type eq 'commit' || $type eq 'tag') {
1337 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1338 $type, $treeish);
1339 my $in_msg = 0;
1340 my $author;
1341 my $saw_from = 0;
1342 my $msgbuf = "";
1343 while (<$msg_fh>) {
1344 if (!$in_msg) {
1345 $in_msg = 1 if (/^\s*$/);
1346 $author = $1 if (/^author (.*>)/);
1347 } elsif (/^git-svn-id: /) {
1348 # skip this for now, we regenerate the
1349 # correct one on re-fetch anyways
1350 # TODO: set *:merge properties or like...
1351 } else {
1352 if (/^From:/ || /^Signed-off-by:/) {
1353 $saw_from = 1;
1355 $msgbuf .= $_;
1358 $msgbuf =~ s/\s+$//s;
1359 if ($Git::SVN::_add_author_from && defined($author)
1360 && !$saw_from) {
1361 $msgbuf .= "\n\nFrom: $author";
1363 print $log_fh $msgbuf or croak $!;
1364 command_close_pipe($msg_fh, $ctx);
1366 close $log_fh or croak $!;
1368 if ($_edit || ($type eq 'tree')) {
1369 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1370 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1372 rename $commit_editmsg, $commit_msg or croak $!;
1374 require Encode;
1375 # SVN requires messages to be UTF-8 when entering the repo
1376 local $/;
1377 open $log_fh, '<', $commit_msg or croak $!;
1378 binmode $log_fh;
1379 chomp($log_entry{log} = <$log_fh>);
1381 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1382 my $msg = $log_entry{log};
1384 eval { $msg = Encode::decode($enc, $msg, 1) };
1385 if ($@) {
1386 die "Could not decode as $enc:\n", $msg,
1387 "\nPerhaps you need to set i18n.commitencoding\n";
1390 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1391 die "Could not encode as UTF-8:\n$msg\n" if $@;
1393 $log_entry{log} = $msg;
1395 close $log_fh or croak $!;
1397 unlink $commit_msg;
1398 \%log_entry;
1401 sub s_to_file {
1402 my ($str, $file, $mode) = @_;
1403 open my $fd,'>',$file or croak $!;
1404 print $fd $str,"\n" or croak $!;
1405 close $fd or croak $!;
1406 chmod ($mode &~ umask, $file) if (defined $mode);
1409 sub file_to_s {
1410 my $file = shift;
1411 open my $fd,'<',$file or croak "$!: file: $file\n";
1412 local $/;
1413 my $ret = <$fd>;
1414 close $fd or croak $!;
1415 $ret =~ s/\s*$//s;
1416 return $ret;
1419 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1420 sub load_authors {
1421 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1422 my $log = $cmd eq 'log';
1423 while (<$authors>) {
1424 chomp;
1425 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1426 my ($user, $name, $email) = ($1, $2, $3);
1427 if ($log) {
1428 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1429 } else {
1430 $users{$user} = [$name, $email];
1433 close $authors or croak $!;
1436 # convert GetOpt::Long specs for use by git-config
1437 sub read_git_config {
1438 my $opts = shift;
1439 my @config_only;
1440 foreach my $o (keys %$opts) {
1441 # if we have mixedCase and a long option-only, then
1442 # it's a config-only variable that we don't need for
1443 # the command-line.
1444 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1445 my $v = $opts->{$o};
1446 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1447 $key =~ s/-//g;
1448 my $arg = 'git config';
1449 $arg .= ' --int' if ($o =~ /[:=]i$/);
1450 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1451 if (ref $v eq 'ARRAY') {
1452 chomp(my @tmp = `$arg --get-all svn.$key`);
1453 @$v = @tmp if @tmp;
1454 } else {
1455 chomp(my $tmp = `$arg --get svn.$key`);
1456 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1457 $$v = $tmp;
1461 delete @$opts{@config_only} if @config_only;
1464 sub extract_metadata {
1465 my $id = shift or return (undef, undef, undef);
1466 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1467 \s([a-f\d\-]+)$/ix);
1468 if (!defined $rev || !$uuid || !$url) {
1469 # some of the original repositories I made had
1470 # identifiers like this:
1471 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1473 return ($url, $rev, $uuid);
1476 sub cmt_metadata {
1477 return extract_metadata((grep(/^git-svn-id: /,
1478 command(qw/cat-file commit/, shift)))[-1]);
1481 sub cmt_sha2rev_batch {
1482 my %s2r;
1483 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1484 my $list = shift;
1486 foreach my $sha (@{$list}) {
1487 my $first = 1;
1488 my $size = 0;
1489 print $out $sha, "\n";
1491 while (my $line = <$in>) {
1492 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1493 last;
1494 } elsif ($first &&
1495 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1496 $first = 0;
1497 $size = $1;
1498 next;
1499 } elsif ($line =~ /^(git-svn-id: )/) {
1500 my (undef, $rev, undef) =
1501 extract_metadata($line);
1502 $s2r{$sha} = $rev;
1505 $size -= length($line);
1506 last if ($size == 0);
1510 command_close_bidi_pipe($pid, $in, $out, $ctx);
1512 return \%s2r;
1515 sub working_head_info {
1516 my ($head, $refs) = @_;
1517 my @args = qw/log --no-color --no-decorate --first-parent
1518 --pretty=medium/;
1519 my ($fh, $ctx) = command_output_pipe(@args, $head);
1520 my $hash;
1521 my %max;
1522 while (<$fh>) {
1523 if ( m{^commit ($::sha1)$} ) {
1524 unshift @$refs, $hash if $hash and $refs;
1525 $hash = $1;
1526 next;
1528 next unless s{^\s*(git-svn-id:)}{$1};
1529 my ($url, $rev, $uuid) = extract_metadata($_);
1530 if (defined $url && defined $rev) {
1531 next if $max{$url} and $max{$url} < $rev;
1532 if (my $gs = Git::SVN->find_by_url($url)) {
1533 my $c = $gs->rev_map_get($rev, $uuid);
1534 if ($c && $c eq $hash) {
1535 close $fh; # break the pipe
1536 return ($url, $rev, $uuid, $gs);
1537 } else {
1538 $max{$url} ||= $gs->rev_map_max;
1543 command_close_pipe($fh, $ctx);
1544 (undef, undef, undef, undef);
1547 sub read_commit_parents {
1548 my ($parents, $c) = @_;
1549 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1550 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1551 @{$parents->{$c}} = split(/ /, $p);
1554 sub linearize_history {
1555 my ($gs, $refs) = @_;
1556 my %parents;
1557 foreach my $c (@$refs) {
1558 read_commit_parents(\%parents, $c);
1561 my @linear_refs;
1562 my %skip = ();
1563 my $last_svn_commit = $gs->last_commit;
1564 foreach my $c (reverse @$refs) {
1565 next if $c eq $last_svn_commit;
1566 last if $skip{$c};
1568 unshift @linear_refs, $c;
1569 $skip{$c} = 1;
1571 # we only want the first parent to diff against for linear
1572 # history, we save the rest to inject when we finalize the
1573 # svn commit
1574 my $fp_a = verify_ref("$c~1");
1575 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1576 if (!$fp_a || !$fp_b) {
1577 die "Commit $c\n",
1578 "has no parent commit, and therefore ",
1579 "nothing to diff against.\n",
1580 "You should be working from a repository ",
1581 "originally created by git-svn\n";
1583 if ($fp_a ne $fp_b) {
1584 die "$c~1 = $fp_a, however parsing commit $c ",
1585 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1588 foreach my $p (@{$parents{$c}}) {
1589 $skip{$p} = 1;
1592 (\@linear_refs, \%parents);
1595 sub find_file_type_and_diff_status {
1596 my ($path) = @_;
1597 return ('dir', '') if $path eq '';
1599 my $diff_output =
1600 command_oneline(qw(diff --cached --name-status --), $path) || "";
1601 my $diff_status = (split(' ', $diff_output))[0] || "";
1603 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1605 return (undef, undef) if !$diff_status && !$ls_tree;
1607 if ($diff_status eq "A") {
1608 return ("link", $diff_status) if -l $path;
1609 return ("dir", $diff_status) if -d $path;
1610 return ("file", $diff_status);
1613 my $mode = (split(' ', $ls_tree))[0] || "";
1615 return ("link", $diff_status) if $mode eq "120000";
1616 return ("dir", $diff_status) if $mode eq "040000";
1617 return ("file", $diff_status);
1620 sub md5sum {
1621 my $arg = shift;
1622 my $ref = ref $arg;
1623 my $md5 = Digest::MD5->new();
1624 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1625 $md5->addfile($arg) or croak $!;
1626 } elsif ($ref eq 'SCALAR') {
1627 $md5->add($$arg) or croak $!;
1628 } elsif (!$ref) {
1629 $md5->add($arg) or croak $!;
1630 } else {
1631 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1633 return $md5->hexdigest();
1636 sub gc_directory {
1637 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1638 my $out_filename = $_ . ".gz";
1639 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1640 binmode $in_fh;
1641 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1642 die "Unable to open $out_filename: $!\n";
1644 my $res;
1645 while ($res = sysread($in_fh, my $str, 1024)) {
1646 $gz->gzwrite($str) or
1647 die "Unable to write: ".$gz->gzerror()."!\n";
1649 unlink $_ or die "unlink $File::Find::name: $!\n";
1650 } elsif (-f $_ && basename($_) eq "index") {
1651 unlink $_ or die "unlink $_: $!\n";
1655 package Git::SVN;
1656 use strict;
1657 use warnings;
1658 use Fcntl qw/:DEFAULT :seek/;
1659 use constant rev_map_fmt => 'NH40';
1660 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1661 $_repack $_repack_flags $_use_svm_props $_head
1662 $_use_svnsync_props $no_reuse_existing $_minimize_url
1663 $_use_log_author $_add_author_from $_localtime/;
1664 use Carp qw/croak/;
1665 use File::Path qw/mkpath/;
1666 use File::Copy qw/copy/;
1667 use IPC::Open3;
1668 use Memoize; # core since 5.8.0, Jul 2002
1669 use Memoize::Storable;
1671 my ($_gc_nr, $_gc_period);
1673 # properties that we do not log:
1674 my %SKIP_PROP;
1675 BEGIN {
1676 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1677 svn:special svn:executable
1678 svn:entry:committed-rev
1679 svn:entry:last-author
1680 svn:entry:uuid
1681 svn:entry:committed-date/;
1683 # some options are read globally, but can be overridden locally
1684 # per [svn-remote "..."] section. Command-line options will *NOT*
1685 # override options set in an [svn-remote "..."] section
1686 no strict 'refs';
1687 for my $option (qw/follow_parent no_metadata use_svm_props
1688 use_svnsync_props/) {
1689 my $key = $option;
1690 $key =~ tr/_//d;
1691 my $prop = "-$option";
1692 *$option = sub {
1693 my ($self) = @_;
1694 return $self->{$prop} if exists $self->{$prop};
1695 my $k = "svn-remote.$self->{repo_id}.$key";
1696 eval { command_oneline(qw/config --get/, $k) };
1697 if ($@) {
1698 $self->{$prop} = ${"Git::SVN::_$option"};
1699 } else {
1700 my $v = command_oneline(qw/config --bool/,$k);
1701 $self->{$prop} = $v eq 'false' ? 0 : 1;
1703 return $self->{$prop};
1709 my (%LOCKFILES, %INDEX_FILES);
1710 END {
1711 unlink keys %LOCKFILES if %LOCKFILES;
1712 unlink keys %INDEX_FILES if %INDEX_FILES;
1715 sub resolve_local_globs {
1716 my ($url, $fetch, $glob_spec) = @_;
1717 return unless defined $glob_spec;
1718 my $ref = $glob_spec->{ref};
1719 my $path = $glob_spec->{path};
1720 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1721 next unless m#^$ref->{regex}$#;
1722 my $p = $1;
1723 my $pathname = desanitize_refname($path->full_path($p));
1724 my $refname = desanitize_refname($ref->full_path($p));
1725 if (my $existing = $fetch->{$pathname}) {
1726 if ($existing ne $refname) {
1727 die "Refspec conflict:\n",
1728 "existing: $existing\n",
1729 " globbed: $refname\n";
1731 my $u = (::cmt_metadata("$refname"))[0];
1732 $u =~ s!^\Q$url\E(/|$)!! or die
1733 "$refname: '$url' not found in '$u'\n";
1734 if ($pathname ne $u) {
1735 warn "W: Refspec glob conflict ",
1736 "(ref: $refname):\n",
1737 "expected path: $pathname\n",
1738 " real path: $u\n",
1739 "Continuing ahead with $u\n";
1740 next;
1742 } else {
1743 $fetch->{$pathname} = $refname;
1748 sub parse_revision_argument {
1749 my ($base, $head) = @_;
1750 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1751 return ($base, $head);
1753 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1754 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1755 return ($head, $head) if ($::_revision eq 'HEAD');
1756 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1757 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1758 die "revision argument: $::_revision not understood by git-svn\n";
1761 sub fetch_all {
1762 my ($repo_id, $remotes) = @_;
1763 if (ref $repo_id) {
1764 my $gs = $repo_id;
1765 $repo_id = undef;
1766 $repo_id = $gs->{repo_id};
1768 $remotes ||= read_all_remotes();
1769 my $remote = $remotes->{$repo_id} or
1770 die "[svn-remote \"$repo_id\"] unknown\n";
1771 my $fetch = $remote->{fetch};
1772 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1773 my (@gs, @globs);
1774 my $ra = Git::SVN::Ra->new($url);
1775 my $uuid = $ra->get_uuid;
1776 my $head = $ra->get_latest_revnum;
1778 # ignore errors, $head revision may not even exist anymore
1779 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1780 warn "W: $@\n" if $@;
1782 my $base = defined $fetch ? $head : 0;
1784 # read the max revs for wildcard expansion (branches/*, tags/*)
1785 foreach my $t (qw/branches tags/) {
1786 defined $remote->{$t} or next;
1787 push @globs, @{$remote->{$t}};
1789 my $max_rev = eval { tmp_config(qw/--int --get/,
1790 "svn-remote.$repo_id.${t}-maxRev") };
1791 if (defined $max_rev && ($max_rev < $base)) {
1792 $base = $max_rev;
1793 } elsif (!defined $max_rev) {
1794 $base = 0;
1798 if ($fetch) {
1799 foreach my $p (sort keys %$fetch) {
1800 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1801 my $lr = $gs->rev_map_max;
1802 if (defined $lr) {
1803 $base = $lr if ($lr < $base);
1805 push @gs, $gs;
1809 ($base, $head) = parse_revision_argument($base, $head);
1810 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1813 sub read_all_remotes {
1814 my $r = {};
1815 my $use_svm_props = eval { command_oneline(qw/config --bool
1816 svn.useSvmProps/) };
1817 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1818 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1819 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1820 if (m!^(.+)\.fetch=$svn_refspec$!) {
1821 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1822 die("svn-remote.$remote: remote ref '$remote_ref' "
1823 . "must start with 'refs/'\n")
1824 unless $remote_ref =~ m{^refs/};
1825 $local_ref = uri_decode($local_ref);
1826 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1827 $r->{$remote}->{svm} = {} if $use_svm_props;
1828 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1829 $r->{$1}->{svm} = {};
1830 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1831 $r->{$1}->{url} = $2;
1832 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1833 my ($remote, $t, $local_ref, $remote_ref) =
1834 ($1, $2, $3, $4);
1835 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1836 . "must start with 'refs/'\n")
1837 unless $remote_ref =~ m{^refs/};
1838 $local_ref = uri_decode($local_ref);
1839 my $rs = {
1840 t => $t,
1841 remote => $remote,
1842 path => Git::SVN::GlobSpec->new($local_ref, 1),
1843 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1844 if (length($rs->{ref}->{right}) != 0) {
1845 die "The '*' glob character must be the last ",
1846 "character of '$remote_ref'\n";
1848 push @{ $r->{$remote}->{$t} }, $rs;
1852 map {
1853 if (defined $r->{$_}->{svm}) {
1854 my $svm;
1855 eval {
1856 my $section = "svn-remote.$_";
1857 $svm = {
1858 source => tmp_config('--get',
1859 "$section.svm-source"),
1860 replace => tmp_config('--get',
1861 "$section.svm-replace"),
1864 $r->{$_}->{svm} = $svm;
1866 } keys %$r;
1871 sub init_vars {
1872 $_gc_nr = $_gc_period = 1000;
1873 if (defined $_repack || defined $_repack_flags) {
1874 warn "Repack options are obsolete; they have no effect.\n";
1878 sub verify_remotes_sanity {
1879 return unless -d $ENV{GIT_DIR};
1880 my %seen;
1881 foreach (command(qw/config -l/)) {
1882 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1883 if ($seen{$1}) {
1884 die "Remote ref refs/remote/$1 is tracked by",
1885 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1886 "Please resolve this ambiguity in ",
1887 "your git configuration file before ",
1888 "continuing\n";
1890 $seen{$1} = $_;
1895 sub find_existing_remote {
1896 my ($url, $remotes) = @_;
1897 return undef if $no_reuse_existing;
1898 my $existing;
1899 foreach my $repo_id (keys %$remotes) {
1900 my $u = $remotes->{$repo_id}->{url} or next;
1901 next if $u ne $url;
1902 $existing = $repo_id;
1903 last;
1905 $existing;
1908 sub init_remote_config {
1909 my ($self, $url, $no_write) = @_;
1910 $url =~ s!/+$!!; # strip trailing slash
1911 my $r = read_all_remotes();
1912 my $existing = find_existing_remote($url, $r);
1913 if ($existing) {
1914 unless ($no_write) {
1915 print STDERR "Using existing ",
1916 "[svn-remote \"$existing\"]\n";
1918 $self->{repo_id} = $existing;
1919 } elsif ($_minimize_url) {
1920 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1921 $existing = find_existing_remote($min_url, $r);
1922 if ($existing) {
1923 unless ($no_write) {
1924 print STDERR "Using existing ",
1925 "[svn-remote \"$existing\"]\n";
1927 $self->{repo_id} = $existing;
1929 if ($min_url ne $url) {
1930 unless ($no_write) {
1931 print STDERR "Using higher level of URL: ",
1932 "$url => $min_url\n";
1934 my $old_path = $self->{path};
1935 $self->{path} = $url;
1936 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1937 if (length $old_path) {
1938 $self->{path} .= "/$old_path";
1940 $url = $min_url;
1943 my $orig_url;
1944 if (!$existing) {
1945 # verify that we aren't overwriting anything:
1946 $orig_url = eval {
1947 command_oneline('config', '--get',
1948 "svn-remote.$self->{repo_id}.url")
1950 if ($orig_url && ($orig_url ne $url)) {
1951 die "svn-remote.$self->{repo_id}.url already set: ",
1952 "$orig_url\nwanted to set to: $url\n";
1955 my ($xrepo_id, $xpath) = find_ref($self->refname);
1956 if (!$no_write && defined $xpath) {
1957 die "svn-remote.$xrepo_id.fetch already set to track ",
1958 "$xpath:", $self->refname, "\n";
1960 unless ($no_write) {
1961 command_noisy('config',
1962 "svn-remote.$self->{repo_id}.url", $url);
1963 $self->{path} =~ s{^/}{};
1964 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1965 command_noisy('config', '--add',
1966 "svn-remote.$self->{repo_id}.fetch",
1967 "$self->{path}:".$self->refname);
1969 $self->{url} = $url;
1972 sub find_by_url { # repos_root and, path are optional
1973 my ($class, $full_url, $repos_root, $path) = @_;
1975 return undef unless defined $full_url;
1976 remove_username($full_url);
1977 remove_username($repos_root) if defined $repos_root;
1978 my $remotes = read_all_remotes();
1979 if (defined $full_url && defined $repos_root && !defined $path) {
1980 $path = $full_url;
1981 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1983 foreach my $repo_id (keys %$remotes) {
1984 my $u = $remotes->{$repo_id}->{url} or next;
1985 remove_username($u);
1986 next if defined $repos_root && $repos_root ne $u;
1988 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1989 foreach my $t (qw/branches tags/) {
1990 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1991 resolve_local_globs($u, $fetch, $globspec);
1994 my $p = $path;
1995 my $rwr = rewrite_root({repo_id => $repo_id});
1996 my $svm = $remotes->{$repo_id}->{svm}
1997 if defined $remotes->{$repo_id}->{svm};
1998 unless (defined $p) {
1999 $p = $full_url;
2000 my $z = $u;
2001 my $prefix = '';
2002 if ($rwr) {
2003 $z = $rwr;
2004 remove_username($z);
2005 } elsif (defined $svm) {
2006 $z = $svm->{source};
2007 $prefix = $svm->{replace};
2008 $prefix =~ s#^\Q$u\E(?:/|$)##;
2009 $prefix =~ s#/$##;
2011 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2013 foreach my $f (keys %$fetch) {
2014 next if $f ne $p;
2015 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2018 undef;
2021 sub init {
2022 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2023 my $self = _new($class, $repo_id, $ref_id, $path);
2024 if (defined $url) {
2025 $self->init_remote_config($url, $no_write);
2027 $self;
2030 sub find_ref {
2031 my ($ref_id) = @_;
2032 foreach (command(qw/config -l/)) {
2033 next unless m!^svn-remote\.(.+)\.fetch=
2034 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2035 my ($repo_id, $path, $ref) = ($1, $2, $3);
2036 if ($ref eq $ref_id) {
2037 $path = '' if ($path =~ m#^\./?#);
2038 return ($repo_id, $path);
2041 (undef, undef, undef);
2044 sub new {
2045 my ($class, $ref_id, $repo_id, $path) = @_;
2046 if (defined $ref_id && !defined $repo_id && !defined $path) {
2047 ($repo_id, $path) = find_ref($ref_id);
2048 if (!defined $repo_id) {
2049 die "Could not find a \"svn-remote.*.fetch\" key ",
2050 "in the repository configuration matching: ",
2051 "$ref_id\n";
2054 my $self = _new($class, $repo_id, $ref_id, $path);
2055 if (!defined $self->{path} || !length $self->{path}) {
2056 my $fetch = command_oneline('config', '--get',
2057 "svn-remote.$repo_id.fetch",
2058 ":$ref_id\$") or
2059 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2060 "\":$ref_id\$\" in config\n";
2061 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2063 $self->{path} =~ s{/+}{/}g;
2064 $self->{path} =~ s{\A/}{};
2065 $self->{path} =~ s{/\z}{};
2066 $self->{url} = command_oneline('config', '--get',
2067 "svn-remote.$repo_id.url") or
2068 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2069 $self->rebuild;
2070 $self;
2073 sub refname {
2074 my ($refname) = $_[0]->{ref_id} ;
2076 # It cannot end with a slash /, we'll throw up on this because
2077 # SVN can't have directories with a slash in their name, either:
2078 if ($refname =~ m{/$}) {
2079 die "ref: '$refname' ends with a trailing slash, this is ",
2080 "not permitted by git nor Subversion\n";
2083 # It cannot have ASCII control character space, tilde ~, caret ^,
2084 # colon :, question-mark ?, asterisk *, space, or open bracket [
2085 # anywhere.
2087 # Additionally, % must be escaped because it is used for escaping
2088 # and we want our escaped refname to be reversible
2089 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2091 # no slash-separated component can begin with a dot .
2092 # /.* becomes /%2E*
2093 $refname =~ s{/\.}{/%2E}g;
2095 # It cannot have two consecutive dots .. anywhere
2096 # .. becomes %2E%2E
2097 $refname =~ s{\.\.}{%2E%2E}g;
2099 # trailing dots and .lock are not allowed
2100 # .$ becomes %2E and .lock becomes %2Elock
2101 $refname =~ s{\.(?=$|lock$)}{%2E};
2103 # the sequence @{ is used to access the reflog
2104 # @{ becomes %40{
2105 $refname =~ s{\@\{}{%40\{}g;
2107 return $refname;
2110 sub desanitize_refname {
2111 my ($refname) = @_;
2112 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2113 return $refname;
2116 sub svm_uuid {
2117 my ($self) = @_;
2118 return $self->{svm}->{uuid} if $self->svm;
2119 $self->ra;
2120 unless ($self->{svm}) {
2121 die "SVM UUID not cached, and reading remotely failed\n";
2123 $self->{svm}->{uuid};
2126 sub svm {
2127 my ($self) = @_;
2128 return $self->{svm} if $self->{svm};
2129 my $svm;
2130 # see if we have it in our config, first:
2131 eval {
2132 my $section = "svn-remote.$self->{repo_id}";
2133 $svm = {
2134 source => tmp_config('--get', "$section.svm-source"),
2135 uuid => tmp_config('--get', "$section.svm-uuid"),
2136 replace => tmp_config('--get', "$section.svm-replace"),
2139 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2140 $self->{svm} = $svm;
2142 $self->{svm};
2145 sub _set_svm_vars {
2146 my ($self, $ra) = @_;
2147 return $ra if $self->svm;
2149 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2150 "(svm:source, svm:uuid) ",
2151 "from the following URLs:\n" );
2152 sub read_svm_props {
2153 my ($self, $ra, $path, $r) = @_;
2154 my $props = ($ra->get_dir($path, $r))[2];
2155 my $src = $props->{'svm:source'};
2156 my $uuid = $props->{'svm:uuid'};
2157 return undef if (!$src || !$uuid);
2159 chomp($src, $uuid);
2161 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2162 or die "doesn't look right - svm:uuid is '$uuid'\n";
2164 # the '!' is used to mark the repos_root!/relative/path
2165 $src =~ s{/?!/?}{/};
2166 $src =~ s{/+$}{}; # no trailing slashes please
2167 # username is of no interest
2168 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2170 my $replace = $ra->{url};
2171 $replace .= "/$path" if length $path;
2173 my $section = "svn-remote.$self->{repo_id}";
2174 tmp_config("$section.svm-source", $src);
2175 tmp_config("$section.svm-replace", $replace);
2176 tmp_config("$section.svm-uuid", $uuid);
2177 $self->{svm} = {
2178 source => $src,
2179 uuid => $uuid,
2180 replace => $replace
2184 my $r = $ra->get_latest_revnum;
2185 my $path = $self->{path};
2186 my %tried;
2187 while (length $path) {
2188 unless ($tried{"$self->{url}/$path"}) {
2189 return $ra if $self->read_svm_props($ra, $path, $r);
2190 $tried{"$self->{url}/$path"} = 1;
2192 $path =~ s#/?[^/]+$##;
2194 die "Path: '$path' should be ''\n" if $path ne '';
2195 return $ra if $self->read_svm_props($ra, $path, $r);
2196 $tried{"$self->{url}/$path"} = 1;
2198 if ($ra->{repos_root} eq $self->{url}) {
2199 die @err, (map { " $_\n" } keys %tried), "\n";
2202 # nope, make sure we're connected to the repository root:
2203 my $ok;
2204 my @tried_b;
2205 $path = $ra->{svn_path};
2206 $ra = Git::SVN::Ra->new($ra->{repos_root});
2207 while (length $path) {
2208 unless ($tried{"$ra->{url}/$path"}) {
2209 $ok = $self->read_svm_props($ra, $path, $r);
2210 last if $ok;
2211 $tried{"$ra->{url}/$path"} = 1;
2213 $path =~ s#/?[^/]+$##;
2215 die "Path: '$path' should be ''\n" if $path ne '';
2216 $ok ||= $self->read_svm_props($ra, $path, $r);
2217 $tried{"$ra->{url}/$path"} = 1;
2218 if (!$ok) {
2219 die @err, (map { " $_\n" } keys %tried), "\n";
2221 Git::SVN::Ra->new($self->{url});
2224 sub svnsync {
2225 my ($self) = @_;
2226 return $self->{svnsync} if $self->{svnsync};
2228 if ($self->no_metadata) {
2229 die "Can't have both 'noMetadata' and ",
2230 "'useSvnsyncProps' options set!\n";
2232 if ($self->rewrite_root) {
2233 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2234 "options set!\n";
2236 if ($self->rewrite_uuid) {
2237 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2238 "options set!\n";
2241 my $svnsync;
2242 # see if we have it in our config, first:
2243 eval {
2244 my $section = "svn-remote.$self->{repo_id}";
2246 my $url = tmp_config('--get', "$section.svnsync-url");
2247 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2248 die "doesn't look right - svn:sync-from-url is '$url'\n";
2250 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2251 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2252 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2254 $svnsync = { url => $url, uuid => $uuid }
2256 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2257 return $self->{svnsync} = $svnsync;
2260 my $err = "useSvnsyncProps set, but failed to read " .
2261 "svnsync property: svn:sync-from-";
2262 my $rp = $self->ra->rev_proplist(0);
2264 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2265 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2266 die "doesn't look right - svn:sync-from-url is '$url'\n";
2268 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2269 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2270 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2272 my $section = "svn-remote.$self->{repo_id}";
2273 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2274 tmp_config('--add', "$section.svnsync-url", $url);
2275 return $self->{svnsync} = { url => $url, uuid => $uuid };
2278 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2279 # remote lookup (useful for 'git svn log').
2280 sub ra_uuid {
2281 my ($self) = @_;
2282 unless ($self->{ra_uuid}) {
2283 my $key = "svn-remote.$self->{repo_id}.uuid";
2284 my $uuid = eval { tmp_config('--get', $key) };
2285 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2286 $self->{ra_uuid} = $uuid;
2287 } else {
2288 die "ra_uuid called without URL\n" unless $self->{url};
2289 $self->{ra_uuid} = $self->ra->get_uuid;
2290 tmp_config('--add', $key, $self->{ra_uuid});
2293 $self->{ra_uuid};
2296 sub _set_repos_root {
2297 my ($self, $repos_root) = @_;
2298 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2299 $repos_root ||= $self->ra->{repos_root};
2300 tmp_config($k, $repos_root);
2301 $repos_root;
2304 sub repos_root {
2305 my ($self) = @_;
2306 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2307 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2310 sub ra {
2311 my ($self) = shift;
2312 my $ra = Git::SVN::Ra->new($self->{url});
2313 $self->_set_repos_root($ra->{repos_root});
2314 if ($self->use_svm_props && !$self->{svm}) {
2315 if ($self->no_metadata) {
2316 die "Can't have both 'noMetadata' and ",
2317 "'useSvmProps' options set!\n";
2318 } elsif ($self->use_svnsync_props) {
2319 die "Can't have both 'useSvnsyncProps' and ",
2320 "'useSvmProps' options set!\n";
2322 $ra = $self->_set_svm_vars($ra);
2323 $self->{-want_revprops} = 1;
2325 $ra;
2328 # prop_walk(PATH, REV, SUB)
2329 # -------------------------
2330 # Recursively traverse PATH at revision REV and invoke SUB for each
2331 # directory that contains a SVN property. SUB will be invoked as
2332 # follows: &SUB(gs, path, props); where `gs' is this instance of
2333 # Git::SVN, `path' the path to the directory where the properties
2334 # `props' were found. The `path' will be relative to point of checkout,
2335 # that is, if url://repo/trunk is the current Git branch, and that
2336 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2337 # as `path' (note the trailing `/').
2338 sub prop_walk {
2339 my ($self, $path, $rev, $sub) = @_;
2341 $path =~ s#^/##;
2342 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2343 $path =~ s#^/*#/#g;
2344 my $p = $path;
2345 # Strip the irrelevant part of the path.
2346 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2347 # Ensure the path is terminated by a `/'.
2348 $p =~ s#/*$#/#;
2350 # The properties contain all the internal SVN stuff nobody
2351 # (usually) cares about.
2352 my $interesting_props = 0;
2353 foreach (keys %{$props}) {
2354 # If it doesn't start with `svn:', it must be a
2355 # user-defined property.
2356 ++$interesting_props and next if $_ !~ /^svn:/;
2357 # FIXME: Fragile, if SVN adds new public properties,
2358 # this needs to be updated.
2359 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2360 |eol-style|mime-type
2361 |externals|needs-lock)$/x;
2363 &$sub($self, $p, $props) if $interesting_props;
2365 foreach (sort keys %$dirent) {
2366 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2367 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2371 sub last_rev { ($_[0]->last_rev_commit)[0] }
2372 sub last_commit { ($_[0]->last_rev_commit)[1] }
2374 # returns the newest SVN revision number and newest commit SHA1
2375 sub last_rev_commit {
2376 my ($self) = @_;
2377 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2378 return ($self->{last_rev}, $self->{last_commit});
2380 my $c = ::verify_ref($self->refname.'^0');
2381 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2382 my $rev = (::cmt_metadata($c))[1];
2383 if (defined $rev) {
2384 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2385 return ($rev, $c);
2388 my $map_path = $self->map_path;
2389 unless (-e $map_path) {
2390 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2391 return (undef, undef);
2393 my ($rev, $commit) = $self->rev_map_max(1);
2394 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2395 return ($rev, $commit);
2398 sub get_fetch_range {
2399 my ($self, $min, $max) = @_;
2400 $max ||= $self->ra->get_latest_revnum;
2401 $min ||= $self->rev_map_max;
2402 (++$min, $max);
2405 sub tmp_config {
2406 my (@args) = @_;
2407 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2408 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2409 if (! -f $config && -f $old_def_config) {
2410 rename $old_def_config, $config or
2411 die "Failed rename $old_def_config => $config: $!\n";
2413 my $old_config = $ENV{GIT_CONFIG};
2414 $ENV{GIT_CONFIG} = $config;
2415 $@ = undef;
2416 my @ret = eval {
2417 unless (-f $config) {
2418 mkfile($config);
2419 open my $fh, '>', $config or
2420 die "Can't open $config: $!\n";
2421 print $fh "; This file is used internally by ",
2422 "git-svn\n" or die
2423 "Couldn't write to $config: $!\n";
2424 print $fh "; You should not have to edit it\n" or
2425 die "Couldn't write to $config: $!\n";
2426 close $fh or die "Couldn't close $config: $!\n";
2428 command('config', @args);
2430 my $err = $@;
2431 if (defined $old_config) {
2432 $ENV{GIT_CONFIG} = $old_config;
2433 } else {
2434 delete $ENV{GIT_CONFIG};
2436 die $err if $err;
2437 wantarray ? @ret : $ret[0];
2440 sub tmp_index_do {
2441 my ($self, $sub) = @_;
2442 my $old_index = $ENV{GIT_INDEX_FILE};
2443 $ENV{GIT_INDEX_FILE} = $self->{index};
2444 $@ = undef;
2445 my @ret = eval {
2446 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2447 mkpath([$dir]) unless -d $dir;
2448 &$sub;
2450 my $err = $@;
2451 if (defined $old_index) {
2452 $ENV{GIT_INDEX_FILE} = $old_index;
2453 } else {
2454 delete $ENV{GIT_INDEX_FILE};
2456 die $err if $err;
2457 wantarray ? @ret : $ret[0];
2460 sub assert_index_clean {
2461 my ($self, $treeish) = @_;
2463 $self->tmp_index_do(sub {
2464 command_noisy('read-tree', $treeish) unless -e $self->{index};
2465 my $x = command_oneline('write-tree');
2466 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2467 /^tree ($::sha1)/mo);
2468 return if $y eq $x;
2470 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2471 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2472 command_noisy('read-tree', $treeish);
2473 $x = command_oneline('write-tree');
2474 if ($y ne $x) {
2475 ::fatal "trees ($treeish) $y != $x\n",
2476 "Something is seriously wrong...";
2481 sub get_commit_parents {
2482 my ($self, $log_entry) = @_;
2483 my (%seen, @ret, @tmp);
2484 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2485 if (my $ip = $self->{inject_parents}) {
2486 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2487 push @tmp, $commit;
2490 if (my $cur = ::verify_ref($self->refname.'^0')) {
2491 push @tmp, $cur;
2493 if (my $ipd = $self->{inject_parents_dcommit}) {
2494 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2495 push @tmp, @$commit;
2498 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2499 while (my $p = shift @tmp) {
2500 next if $seen{$p};
2501 $seen{$p} = 1;
2502 push @ret, $p;
2504 @ret;
2507 sub rewrite_root {
2508 my ($self) = @_;
2509 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2510 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2511 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2512 if ($rwr) {
2513 $rwr =~ s#/+$##;
2514 if ($rwr !~ m#^[a-z\+]+://#) {
2515 die "$rwr is not a valid URL (key: $k)\n";
2518 $self->{-rewrite_root} = $rwr;
2521 sub rewrite_uuid {
2522 my ($self) = @_;
2523 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2524 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2525 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2526 if ($rwid) {
2527 $rwid =~ s#/+$##;
2528 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2529 die "$rwid is not a valid UUID (key: $k)\n";
2532 $self->{-rewrite_uuid} = $rwid;
2535 sub metadata_url {
2536 my ($self) = @_;
2537 ($self->rewrite_root || $self->{url}) .
2538 (length $self->{path} ? '/' . $self->{path} : '');
2541 sub full_url {
2542 my ($self) = @_;
2543 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2547 sub set_commit_header_env {
2548 my ($log_entry) = @_;
2549 my %env;
2550 foreach my $ned (qw/NAME EMAIL DATE/) {
2551 foreach my $ac (qw/AUTHOR COMMITTER/) {
2552 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2556 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2557 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2558 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2560 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2561 ? $log_entry->{commit_name}
2562 : $log_entry->{name};
2563 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2564 ? $log_entry->{commit_email}
2565 : $log_entry->{email};
2566 \%env;
2569 sub restore_commit_header_env {
2570 my ($env) = @_;
2571 foreach my $ned (qw/NAME EMAIL DATE/) {
2572 foreach my $ac (qw/AUTHOR COMMITTER/) {
2573 my $k = "GIT_${ac}_${ned}";
2574 if (defined $env->{$k}) {
2575 $ENV{$k} = $env->{$k};
2576 } else {
2577 delete $ENV{$k};
2583 sub gc {
2584 command_noisy('gc', '--auto');
2587 sub do_git_commit {
2588 my ($self, $log_entry) = @_;
2589 my $lr = $self->last_rev;
2590 if (defined $lr && $lr >= $log_entry->{revision}) {
2591 die "Last fetched revision of ", $self->refname,
2592 " was r$lr, but we are about to fetch: ",
2593 "r$log_entry->{revision}!\n";
2595 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2596 croak "$log_entry->{revision} = $c already exists! ",
2597 "Why are we refetching it?\n";
2599 my $old_env = set_commit_header_env($log_entry);
2600 my $tree = $log_entry->{tree};
2601 if (!defined $tree) {
2602 $tree = $self->tmp_index_do(sub {
2603 command_oneline('write-tree') });
2605 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2607 my @exec = ('git', 'commit-tree', $tree);
2608 foreach ($self->get_commit_parents($log_entry)) {
2609 push @exec, '-p', $_;
2611 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2612 or croak $!;
2613 binmode $msg_fh;
2615 # we always get UTF-8 from SVN, but we may want our commits in
2616 # a different encoding.
2617 if (my $enc = Git::config('i18n.commitencoding')) {
2618 require Encode;
2619 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2621 print $msg_fh $log_entry->{log} or croak $!;
2622 restore_commit_header_env($old_env);
2623 unless ($self->no_metadata) {
2624 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2625 or croak $!;
2627 $msg_fh->flush == 0 or croak $!;
2628 close $msg_fh or croak $!;
2629 chomp(my $commit = do { local $/; <$out_fh> });
2630 close $out_fh or croak $!;
2631 waitpid $pid, 0;
2632 croak $? if $?;
2633 if ($commit !~ /^$::sha1$/o) {
2634 die "Failed to commit, invalid sha1: $commit\n";
2637 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2639 $self->{last_rev} = $log_entry->{revision};
2640 $self->{last_commit} = $commit;
2641 print "r$log_entry->{revision}" unless $::_q > 1;
2642 if (defined $log_entry->{svm_revision}) {
2643 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2644 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2645 0, $self->svm_uuid);
2647 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2648 if (--$_gc_nr == 0) {
2649 $_gc_nr = $_gc_period;
2650 gc();
2652 return $commit;
2655 sub match_paths {
2656 my ($self, $paths, $r) = @_;
2657 return 1 if $self->{path} eq '';
2658 if (my $path = $paths->{"/$self->{path}"}) {
2659 return ($path->{action} eq 'D') ? 0 : 1;
2661 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2662 if (grep /$self->{path_regex}/, keys %$paths) {
2663 return 1;
2665 my $c = '';
2666 foreach (split m#/#, $self->{path}) {
2667 $c .= "/$_";
2668 next unless ($paths->{$c} &&
2669 ($paths->{$c}->{action} =~ /^[AR]$/));
2670 if ($self->ra->check_path($self->{path}, $r) ==
2671 $SVN::Node::dir) {
2672 return 1;
2675 return 0;
2678 sub find_parent_branch {
2679 my ($self, $paths, $rev) = @_;
2680 return undef unless $self->follow_parent;
2681 unless (defined $paths) {
2682 my $err_handler = $SVN::Error::handler;
2683 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2684 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2685 sub { $paths = $_[0] });
2686 $SVN::Error::handler = $err_handler;
2688 return undef unless defined $paths;
2690 # look for a parent from another branch:
2691 my @b_path_components = split m#/#, $self->{path};
2692 my @a_path_components;
2693 my $i;
2694 while (@b_path_components) {
2695 $i = $paths->{'/'.join('/', @b_path_components)};
2696 last if $i && defined $i->{copyfrom_path};
2697 unshift(@a_path_components, pop(@b_path_components));
2699 return undef unless defined $i && defined $i->{copyfrom_path};
2700 my $branch_from = $i->{copyfrom_path};
2701 if (@a_path_components) {
2702 print STDERR "branch_from: $branch_from => ";
2703 $branch_from .= '/'.join('/', @a_path_components);
2704 print STDERR $branch_from, "\n";
2706 my $r = $i->{copyfrom_rev};
2707 my $repos_root = $self->ra->{repos_root};
2708 my $url = $self->ra->{url};
2709 my $new_url = $url . $branch_from;
2710 print STDERR "Found possible branch point: ",
2711 "$new_url => ", $self->full_url, ", $r\n"
2712 unless $::_q > 1;
2713 $branch_from =~ s#^/##;
2714 my $gs = $self->other_gs($new_url, $url,
2715 $branch_from, $r, $self->{ref_id});
2716 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2718 my ($base, $head);
2719 if (!defined $r0 || !defined $parent) {
2720 ($base, $head) = parse_revision_argument(0, $r);
2721 } else {
2722 if ($r0 < $r) {
2723 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2724 0, 1, sub { $base = $_[1] - 1 });
2727 if (defined $base && $base <= $r) {
2728 $gs->fetch($base, $r);
2730 ($r0, $parent) = $gs->find_rev_before($r, 1);
2732 if (defined $r0 && defined $parent) {
2733 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2734 unless $::_q > 1;
2735 my $ed;
2736 if ($self->ra->can_do_switch) {
2737 $self->assert_index_clean($parent);
2738 print STDERR "Following parent with do_switch\n"
2739 unless $::_q > 1;
2740 # do_switch works with svn/trunk >= r22312, but that
2741 # is not included with SVN 1.4.3 (the latest version
2742 # at the moment), so we can't rely on it
2743 $self->{last_rev} = $r0;
2744 $self->{last_commit} = $parent;
2745 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2746 $gs->ra->gs_do_switch($r0, $rev, $gs,
2747 $self->full_url, $ed)
2748 or die "SVN connection failed somewhere...\n";
2749 } elsif ($self->ra->trees_match($new_url, $r0,
2750 $self->full_url, $rev)) {
2751 print STDERR "Trees match:\n",
2752 " $new_url\@$r0\n",
2753 " ${\$self->full_url}\@$rev\n",
2754 "Following parent with no changes\n"
2755 unless $::_q > 1;
2756 $self->tmp_index_do(sub {
2757 command_noisy('read-tree', $parent);
2759 $self->{last_commit} = $parent;
2760 } else {
2761 print STDERR "Following parent with do_update\n"
2762 unless $::_q > 1;
2763 $ed = SVN::Git::Fetcher->new($self);
2764 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2765 or die "SVN connection failed somewhere...\n";
2767 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2768 return $self->make_log_entry($rev, [$parent], $ed);
2770 return undef;
2773 sub do_fetch {
2774 my ($self, $paths, $rev) = @_;
2775 my $ed;
2776 my ($last_rev, @parents);
2777 if (my $lc = $self->last_commit) {
2778 # we can have a branch that was deleted, then re-added
2779 # under the same name but copied from another path, in
2780 # which case we'll have multiple parents (we don't
2781 # want to break the original ref, nor lose copypath info):
2782 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2783 push @{$log_entry->{parents}}, $lc;
2784 return $log_entry;
2786 $ed = SVN::Git::Fetcher->new($self);
2787 $last_rev = $self->{last_rev};
2788 $ed->{c} = $lc;
2789 @parents = ($lc);
2790 } else {
2791 $last_rev = $rev;
2792 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2793 return $log_entry;
2795 $ed = SVN::Git::Fetcher->new($self);
2797 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2798 die "SVN connection failed somewhere...\n";
2800 $self->make_log_entry($rev, \@parents, $ed);
2803 sub mkemptydirs {
2804 my ($self, $r) = @_;
2806 sub scan {
2807 my ($r, $empty_dirs, $line) = @_;
2808 if (defined $r && $line =~ /^r(\d+)$/) {
2809 return 0 if $1 > $r;
2810 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2811 $empty_dirs->{$1} = 1;
2812 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2813 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2814 delete @$empty_dirs{@d};
2816 1; # continue
2819 my %empty_dirs = ();
2820 my $gz_file = "$self->{dir}/unhandled.log.gz";
2821 if (-f $gz_file) {
2822 if (!$can_compress) {
2823 warn "Compress::Zlib could not be found; ",
2824 "empty directories in $gz_file will not be read\n";
2825 } else {
2826 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2827 die "Unable to open $gz_file: $!\n";
2828 my $line;
2829 while ($gz->gzreadline($line) > 0) {
2830 scan($r, \%empty_dirs, $line) or last;
2832 $gz->gzclose;
2836 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2837 binmode $fh or croak "binmode: $!";
2838 while (<$fh>) {
2839 scan($r, \%empty_dirs, $_) or last;
2841 close $fh;
2844 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2845 foreach my $d (sort keys %empty_dirs) {
2846 $d = uri_decode($d);
2847 $d =~ s/$strip//;
2848 next unless length($d);
2849 next if -d $d;
2850 if (-e $d) {
2851 warn "$d exists but is not a directory\n";
2852 } else {
2853 print "creating empty directory: $d\n";
2854 mkpath([$d]);
2859 sub get_untracked {
2860 my ($self, $ed) = @_;
2861 my @out;
2862 my $h = $ed->{empty};
2863 foreach (sort keys %$h) {
2864 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2865 push @out, " $act: " . uri_encode($_);
2866 warn "W: $act: $_\n";
2868 foreach my $t (qw/dir_prop file_prop/) {
2869 $h = $ed->{$t} or next;
2870 foreach my $path (sort keys %$h) {
2871 my $ppath = $path eq '' ? '.' : $path;
2872 foreach my $prop (sort keys %{$h->{$path}}) {
2873 next if $SKIP_PROP{$prop};
2874 my $v = $h->{$path}->{$prop};
2875 my $t_ppath_prop = "$t: " .
2876 uri_encode($ppath) . ' ' .
2877 uri_encode($prop);
2878 if (defined $v) {
2879 push @out, " +$t_ppath_prop " .
2880 uri_encode($v);
2881 } else {
2882 push @out, " -$t_ppath_prop";
2887 foreach my $t (qw/absent_file absent_directory/) {
2888 $h = $ed->{$t} or next;
2889 foreach my $parent (sort keys %$h) {
2890 foreach my $path (sort @{$h->{$parent}}) {
2891 push @out, " $t: " .
2892 uri_encode("$parent/$path");
2893 warn "W: $t: $parent/$path ",
2894 "Insufficient permissions?\n";
2898 \@out;
2901 # parse_svn_date(DATE)
2902 # --------------------
2903 # Given a date (in UTC) from Subversion, return a string in the format
2904 # "<TZ Offset> <local date/time>" that Git will use.
2906 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2907 # is true we'll convert it to the local timezone instead.
2908 sub parse_svn_date {
2909 my $date = shift || return '+0000 1970-01-01 00:00:00';
2910 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2911 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2912 croak "Unable to parse date: $date\n";
2913 my $parsed_date; # Set next.
2915 if ($Git::SVN::_localtime) {
2916 # Translate the Subversion datetime to an epoch time.
2917 # Begin by switching ourselves to $date's timezone, UTC.
2918 my $old_env_TZ = $ENV{TZ};
2919 $ENV{TZ} = 'UTC';
2921 my $epoch_in_UTC =
2922 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2924 # Determine our local timezone (including DST) at the
2925 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2926 # value of TZ, if any, at the time we were run.
2927 if (defined $Git::SVN::Log::TZ) {
2928 $ENV{TZ} = $Git::SVN::Log::TZ;
2929 } else {
2930 delete $ENV{TZ};
2933 my $our_TZ =
2934 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2936 # This converts $epoch_in_UTC into our local timezone.
2937 my ($sec, $min, $hour, $mday, $mon, $year,
2938 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2940 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2941 $our_TZ, $year + 1900, $mon + 1,
2942 $mday, $hour, $min, $sec);
2944 # Reset us to the timezone in effect when we entered
2945 # this routine.
2946 if (defined $old_env_TZ) {
2947 $ENV{TZ} = $old_env_TZ;
2948 } else {
2949 delete $ENV{TZ};
2951 } else {
2952 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2955 return $parsed_date;
2958 sub other_gs {
2959 my ($self, $new_url, $url,
2960 $branch_from, $r, $old_ref_id) = @_;
2961 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2962 unless ($gs) {
2963 my $ref_id = $old_ref_id;
2964 $ref_id =~ s/\@\d+-*$//;
2965 $ref_id .= "\@$r";
2966 # just grow a tail if we're not unique enough :x
2967 $ref_id .= '-' while find_ref($ref_id);
2968 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2969 if ($u =~ s#^\Q$url\E(/|$)##) {
2970 $p = $u;
2971 $u = $url;
2972 $repo_id = $self->{repo_id};
2974 while (1) {
2975 # It is possible to tag two different subdirectories at
2976 # the same revision. If the url for an existing ref
2977 # does not match, we must either find a ref with a
2978 # matching url or create a new ref by growing a tail.
2979 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2980 my (undef, $max_commit) = $gs->rev_map_max(1);
2981 last if (!$max_commit);
2982 my ($url) = ::cmt_metadata($max_commit);
2983 last if ($url eq $gs->full_url);
2984 $ref_id .= '-';
2986 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
2991 sub call_authors_prog {
2992 my ($orig_author) = @_;
2993 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
2994 my $author = `$::_authors_prog $orig_author`;
2995 if ($? != 0) {
2996 die "$::_authors_prog failed with exit code $?\n"
2998 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2999 my ($name, $email) = ($1, $2);
3000 $email = undef if length $2 == 0;
3001 return [$name, $email];
3002 } else {
3003 die "Author: $orig_author: $::_authors_prog returned "
3004 . "invalid author format: $author\n";
3008 sub check_author {
3009 my ($author) = @_;
3010 if (!defined $author || length $author == 0) {
3011 $author = '(no author)';
3013 if (!defined $::users{$author}) {
3014 if (defined $::_authors_prog) {
3015 $::users{$author} = call_authors_prog($author);
3016 } elsif (defined $::_authors) {
3017 die "Author: $author not defined in $::_authors file\n";
3020 $author;
3023 sub find_extra_svk_parents {
3024 my ($self, $ed, $tickets, $parents) = @_;
3025 # aha! svk:merge property changed...
3026 my @tickets = split "\n", $tickets;
3027 my @known_parents;
3028 for my $ticket ( @tickets ) {
3029 my ($uuid, $path, $rev) = split /:/, $ticket;
3030 if ( $uuid eq $self->ra_uuid ) {
3031 my $url = $self->{url};
3032 my $repos_root = $url;
3033 my $branch_from = $path;
3034 $branch_from =~ s{^/}{};
3035 my $gs = $self->other_gs($repos_root."/".$branch_from,
3036 $url,
3037 $branch_from,
3038 $rev,
3039 $self->{ref_id});
3040 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3041 # wahey! we found it, but it might be
3042 # an old one (!)
3043 push @known_parents, [ $rev, $commit ];
3047 # Ordering matters; highest-numbered commit merge tickets
3048 # first, as they may account for later merge ticket additions
3049 # or changes.
3050 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3051 for my $parent ( @known_parents ) {
3052 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3053 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3054 my $new;
3055 while ( <$msg_fh> ) {
3056 $new=1;last;
3058 command_close_pipe($msg_fh, $ctx);
3059 if ( $new ) {
3060 print STDERR
3061 "Found merge parent (svk:merge ticket): $parent\n";
3062 push @$parents, $parent;
3067 sub lookup_svn_merge {
3068 my $uuid = shift;
3069 my $url = shift;
3070 my $merge = shift;
3072 my ($source, $revs) = split ":", $merge;
3073 my $path = $source;
3074 $path =~ s{^/}{};
3075 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3076 if ( !$gs ) {
3077 warn "Couldn't find revmap for $url$source\n";
3078 return;
3080 my @ranges = split ",", $revs;
3081 my ($tip, $tip_commit);
3082 my @merged_commit_ranges;
3083 # find the tip
3084 for my $range ( @ranges ) {
3085 my ($bottom, $top) = split "-", $range;
3086 $top ||= $bottom;
3087 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3088 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3090 unless ($top_commit and $bottom_commit) {
3091 warn "W:unknown path/rev in svn:mergeinfo "
3092 ."dirprop: $source:$range\n";
3093 next;
3096 push @merged_commit_ranges,
3097 "$bottom_commit^..$top_commit";
3099 if ( !defined $tip or $top > $tip ) {
3100 $tip = $top;
3101 $tip_commit = $top_commit;
3104 return ($tip_commit, @merged_commit_ranges);
3107 sub _rev_list {
3108 my ($msg_fh, $ctx) = command_output_pipe(
3109 "rev-list", @_,
3111 my @rv;
3112 while ( <$msg_fh> ) {
3113 chomp;
3114 push @rv, $_;
3116 command_close_pipe($msg_fh, $ctx);
3117 @rv;
3120 sub check_cherry_pick {
3121 my $base = shift;
3122 my $tip = shift;
3123 my $parents = shift;
3124 my @ranges = @_;
3125 my %commits = map { $_ => 1 }
3126 _rev_list("--no-merges", $tip, "--not", $base, @$parents);
3127 for my $range ( @ranges ) {
3128 delete @commits{_rev_list($range)};
3130 for my $commit (keys %commits) {
3131 if (has_no_changes($commit)) {
3132 delete $commits{$commit};
3135 return (keys %commits);
3138 sub has_no_changes {
3139 my $commit = shift;
3141 my @revs = split / /, command_oneline(
3142 qw(rev-list --parents -1 -m), $commit);
3144 # Commits with no parents, e.g. the start of a partial branch,
3145 # have changes by definition.
3146 return 1 if (@revs < 2);
3148 # Commits with multiple parents, e.g a merge, have no changes
3149 # by definition.
3150 return 0 if (@revs > 2);
3152 return (command_oneline("rev-parse", "$commit^{tree}") eq
3153 command_oneline("rev-parse", "$commit~1^{tree}"));
3156 # The GIT_DIR environment variable is not always set until after the command
3157 # line arguments are processed, so we can't memoize in a BEGIN block.
3159 my $memoized = 0;
3161 sub memoize_svn_mergeinfo_functions {
3162 return if $memoized;
3163 $memoized = 1;
3165 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3166 mkpath([$cache_path]) unless -d $cache_path;
3168 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3169 "$cache_path/lookup_svn_merge.db", 'nstore';
3170 memoize 'lookup_svn_merge',
3171 SCALAR_CACHE => 'FAULT',
3172 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3175 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3176 "$cache_path/check_cherry_pick.db", 'nstore';
3177 memoize 'check_cherry_pick',
3178 SCALAR_CACHE => 'FAULT',
3179 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3182 tie my %has_no_changes_cache => 'Memoize::Storable',
3183 "$cache_path/has_no_changes.db", 'nstore';
3184 memoize 'has_no_changes',
3185 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3186 LIST_CACHE => 'FAULT',
3190 sub unmemoize_svn_mergeinfo_functions {
3191 return if not $memoized;
3192 $memoized = 0;
3194 Memoize::unmemoize 'lookup_svn_merge';
3195 Memoize::unmemoize 'check_cherry_pick';
3196 Memoize::unmemoize 'has_no_changes';
3200 END {
3201 # Force cache writeout explicitly instead of waiting for
3202 # global destruction to avoid segfault in Storable:
3203 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3204 unmemoize_svn_mergeinfo_functions();
3207 sub parents_exclude {
3208 my $parents = shift;
3209 my @commits = @_;
3210 return unless @commits;
3212 my @excluded;
3213 my $excluded;
3214 do {
3215 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3216 $excluded = command_oneline(@cmd);
3217 if ( $excluded ) {
3218 my @new;
3219 my $found;
3220 for my $commit ( @commits ) {
3221 if ( $commit eq $excluded ) {
3222 push @excluded, $commit;
3223 $found++;
3224 last;
3226 else {
3227 push @new, $commit;
3230 die "saw commit '$excluded' in rev-list output, "
3231 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3232 unless $found;
3233 @commits = @new;
3236 while ($excluded and @commits);
3238 return @excluded;
3242 # note: this function should only be called if the various dirprops
3243 # have actually changed
3244 sub find_extra_svn_parents {
3245 my ($self, $ed, $mergeinfo, $parents) = @_;
3246 # aha! svk:merge property changed...
3248 memoize_svn_mergeinfo_functions();
3250 # We first search for merged tips which are not in our
3251 # history. Then, we figure out which git revisions are in
3252 # that tip, but not this revision. If all of those revisions
3253 # are now marked as merge, we can add the tip as a parent.
3254 my @merges = split "\n", $mergeinfo;
3255 my @merge_tips;
3256 my $url = $self->{url};
3257 my $uuid = $self->ra_uuid;
3258 my %ranges;
3259 for my $merge ( @merges ) {
3260 my ($tip_commit, @ranges) =
3261 lookup_svn_merge( $uuid, $url, $merge );
3262 unless (!$tip_commit or
3263 grep { $_ eq $tip_commit } @$parents ) {
3264 push @merge_tips, $tip_commit;
3265 $ranges{$tip_commit} = \@ranges;
3266 } else {
3267 push @merge_tips, undef;
3271 my %excluded = map { $_ => 1 }
3272 parents_exclude($parents, grep { defined } @merge_tips);
3274 # check merge tips for new parents
3275 my @new_parents;
3276 for my $merge_tip ( @merge_tips ) {
3277 my $spec = shift @merges;
3278 next unless $merge_tip and $excluded{$merge_tip};
3280 my $ranges = $ranges{$merge_tip};
3282 # check out 'new' tips
3283 my $merge_base;
3284 eval {
3285 $merge_base = command_oneline(
3286 "merge-base",
3287 @$parents, $merge_tip,
3290 if ($@) {
3291 die "An error occurred during merge-base"
3292 unless $@->isa("Git::Error::Command");
3294 warn "W: Cannot find common ancestor between ".
3295 "@$parents and $merge_tip. Ignoring merge info.\n";
3296 next;
3299 # double check that there are no missing non-merge commits
3300 my (@incomplete) = check_cherry_pick(
3301 $merge_base, $merge_tip,
3302 $parents,
3303 @$ranges,
3306 if ( @incomplete ) {
3307 warn "W:svn cherry-pick ignored ($spec) - missing "
3308 .@incomplete." commit(s) (eg $incomplete[0])\n";
3309 } else {
3310 warn
3311 "Found merge parent (svn:mergeinfo prop): ",
3312 $merge_tip, "\n";
3313 push @new_parents, $merge_tip;
3317 # cater for merges which merge commits from multiple branches
3318 if ( @new_parents > 1 ) {
3319 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3320 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3321 next if $i == $j;
3322 next unless $new_parents[$i];
3323 next unless $new_parents[$j];
3324 my $revs = command_oneline(
3325 "rev-list", "-1",
3326 "$new_parents[$i]..$new_parents[$j]",
3328 if ( !$revs ) {
3329 undef($new_parents[$j]);
3334 push @$parents, grep { defined } @new_parents;
3337 sub make_log_entry {
3338 my ($self, $rev, $parents, $ed) = @_;
3339 my $untracked = $self->get_untracked($ed);
3341 my @parents = @$parents;
3342 my $ps = $ed->{path_strip} || "";
3343 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3344 my $props = $ed->{dir_prop}{$path};
3345 if ( $props->{"svk:merge"} ) {
3346 $self->find_extra_svk_parents
3347 ($ed, $props->{"svk:merge"}, \@parents);
3349 if ( $props->{"svn:mergeinfo"} ) {
3350 $self->find_extra_svn_parents
3351 ($ed,
3352 $props->{"svn:mergeinfo"},
3353 \@parents);
3357 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3358 print $un "r$rev\n" or croak $!;
3359 print $un $_, "\n" foreach @$untracked;
3360 my %log_entry = ( parents => \@parents, revision => $rev,
3361 log => '');
3363 my $headrev;
3364 my $logged = delete $self->{logged_rev_props};
3365 if (!$logged || $self->{-want_revprops}) {
3366 my $rp = $self->ra->rev_proplist($rev);
3367 foreach (sort keys %$rp) {
3368 my $v = $rp->{$_};
3369 if (/^svn:(author|date|log)$/) {
3370 $log_entry{$1} = $v;
3371 } elsif ($_ eq 'svm:headrev') {
3372 $headrev = $v;
3373 } else {
3374 print $un " rev_prop: ", uri_encode($_), ' ',
3375 uri_encode($v), "\n";
3378 } else {
3379 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3381 close $un or croak $!;
3383 $log_entry{date} = parse_svn_date($log_entry{date});
3384 $log_entry{log} .= "\n";
3385 my $author = $log_entry{author} = check_author($log_entry{author});
3386 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3387 : ($author, undef);
3389 my ($commit_name, $commit_email) = ($name, $email);
3390 if ($_use_log_author) {
3391 my $name_field;
3392 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3393 $name_field = $1;
3394 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3395 $name_field = $1;
3397 if (!defined $name_field) {
3398 if (!defined $email) {
3399 $email = $name;
3401 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3402 ($name, $email) = ($1, $2);
3403 } elsif ($name_field =~ /(.*)@/) {
3404 ($name, $email) = ($1, $name_field);
3405 } else {
3406 ($name, $email) = ($name_field, $name_field);
3409 if (defined $headrev && $self->use_svm_props) {
3410 if ($self->rewrite_root) {
3411 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3412 "options set!\n";
3414 if ($self->rewrite_uuid) {
3415 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3416 "options set!\n";
3418 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3419 # we don't want "SVM: initializing mirror for junk" ...
3420 return undef if $r == 0;
3421 my $svm = $self->svm;
3422 if ($uuid ne $svm->{uuid}) {
3423 die "UUID mismatch on SVM path:\n",
3424 "expected: $svm->{uuid}\n",
3425 " got: $uuid\n";
3427 my $full_url = $self->full_url;
3428 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3429 die "Failed to replace '$svm->{replace}' with ",
3430 "'$svm->{source}' in $full_url\n";
3431 # throw away username for storing in records
3432 remove_username($full_url);
3433 $log_entry{metadata} = "$full_url\@$r $uuid";
3434 $log_entry{svm_revision} = $r;
3435 $email ||= "$author\@$uuid";
3436 $commit_email ||= "$author\@$uuid";
3437 } elsif ($self->use_svnsync_props) {
3438 my $full_url = $self->svnsync->{url};
3439 $full_url .= "/$self->{path}" if length $self->{path};
3440 remove_username($full_url);
3441 my $uuid = $self->svnsync->{uuid};
3442 $log_entry{metadata} = "$full_url\@$rev $uuid";
3443 $email ||= "$author\@$uuid";
3444 $commit_email ||= "$author\@$uuid";
3445 } else {
3446 my $url = $self->metadata_url;
3447 remove_username($url);
3448 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3449 $log_entry{metadata} = "$url\@$rev " . $uuid;
3450 $email ||= "$author\@" . $uuid;
3451 $commit_email ||= "$author\@" . $uuid;
3453 $log_entry{name} = $name;
3454 $log_entry{email} = $email;
3455 $log_entry{commit_name} = $commit_name;
3456 $log_entry{commit_email} = $commit_email;
3457 \%log_entry;
3460 sub fetch {
3461 my ($self, $min_rev, $max_rev, @parents) = @_;
3462 my ($last_rev, $last_commit) = $self->last_rev_commit;
3463 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3464 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3467 sub set_tree_cb {
3468 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3469 $self->{inject_parents} = { $rev => $tree };
3470 $self->fetch(undef, undef);
3473 sub set_tree {
3474 my ($self, $tree) = (shift, shift);
3475 my $log_entry = ::get_commit_entry($tree);
3476 unless ($self->{last_rev}) {
3477 ::fatal("Must have an existing revision to commit");
3479 my %ed_opts = ( r => $self->{last_rev},
3480 log => $log_entry->{log},
3481 ra => $self->ra,
3482 tree_a => $self->{last_commit},
3483 tree_b => $tree,
3484 editor_cb => sub {
3485 $self->set_tree_cb($log_entry, $tree, @_) },
3486 svn_path => $self->{path} );
3487 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3488 print "No changes\nr$self->{last_rev} = $tree\n";
3492 sub rebuild_from_rev_db {
3493 my ($self, $path) = @_;
3494 my $r = -1;
3495 open my $fh, '<', $path or croak "open: $!";
3496 binmode $fh or croak "binmode: $!";
3497 while (<$fh>) {
3498 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3499 chomp($_);
3500 ++$r;
3501 next if $_ eq ('0' x 40);
3502 $self->rev_map_set($r, $_);
3503 print "r$r = $_\n";
3505 close $fh or croak "close: $!";
3506 unlink $path or croak "unlink: $!";
3509 sub rebuild {
3510 my ($self) = @_;
3511 my $map_path = $self->map_path;
3512 my $partial = (-e $map_path && ! -z $map_path);
3513 return unless ::verify_ref($self->refname.'^0');
3514 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3515 my $rev_db = $self->rev_db_path;
3516 $self->rebuild_from_rev_db($rev_db);
3517 if ($self->use_svm_props) {
3518 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3519 $self->rebuild_from_rev_db($svm_rev_db);
3521 $self->unlink_rev_db_symlink;
3522 return;
3524 print "Rebuilding $map_path ...\n" if (!$partial);
3525 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3526 (undef, undef));
3527 my ($log, $ctx) =
3528 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3529 ($head ? "$head.." : "") . $self->refname,
3530 '--');
3531 my $metadata_url = $self->metadata_url;
3532 remove_username($metadata_url);
3533 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3534 my $c;
3535 while (<$log>) {
3536 if ( m{^commit ($::sha1)$} ) {
3537 $c = $1;
3538 next;
3540 next unless s{^\s*(git-svn-id:)}{$1};
3541 my ($url, $rev, $uuid) = ::extract_metadata($_);
3542 remove_username($url);
3544 # ignore merges (from set-tree)
3545 next if (!defined $rev || !$uuid);
3547 # if we merged or otherwise started elsewhere, this is
3548 # how we break out of it
3549 if (($uuid ne $svn_uuid) ||
3550 ($metadata_url && $url && ($url ne $metadata_url))) {
3551 next;
3553 if ($partial && $head) {
3554 print "Partial-rebuilding $map_path ...\n";
3555 print "Currently at $base_rev = $head\n";
3556 $head = undef;
3559 $self->rev_map_set($rev, $c);
3560 print "r$rev = $c\n";
3562 command_close_pipe($log, $ctx);
3563 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3564 my $rev_db_path = $self->rev_db_path;
3565 if (-f $self->rev_db_path) {
3566 unlink $self->rev_db_path or croak "unlink: $!";
3568 $self->unlink_rev_db_symlink;
3571 # rev_map:
3572 # Tie::File seems to be prone to offset errors if revisions get sparse,
3573 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3574 # one of my favorite modules is out :< Next up would be one of the DBM
3575 # modules, but I'm not sure which is most portable...
3577 # This is the replacement for the rev_db format, which was too big
3578 # and inefficient for large repositories with a lot of sparse history
3579 # (mainly tags)
3581 # The format is this:
3582 # - 24 bytes for every record,
3583 # * 4 bytes for the integer representing an SVN revision number
3584 # * 20 bytes representing the sha1 of a git commit
3585 # - No empty padding records like the old format
3586 # (except the last record, which can be overwritten)
3587 # - new records are written append-only since SVN revision numbers
3588 # increase monotonically
3589 # - lookups on SVN revision number are done via a binary search
3590 # - Piping the file to xxd -c24 is a good way of dumping it for
3591 # viewing or editing (piped back through xxd -r), should the need
3592 # ever arise.
3593 # - The last record can be padding revision with an all-zero sha1
3594 # This is used to optimize fetch performance when using multiple
3595 # "fetch" directives in .git/config
3597 # These files are disposable unless noMetadata or useSvmProps is set
3599 sub _rev_map_set {
3600 my ($fh, $rev, $commit) = @_;
3602 binmode $fh or croak "binmode: $!";
3603 my $size = (stat($fh))[7];
3604 ($size % 24) == 0 or croak "inconsistent size: $size";
3606 my $wr_offset = 0;
3607 if ($size > 0) {
3608 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3609 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3610 $read == 24 or croak "read only $read bytes (!= 24)";
3611 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3612 if ($last_commit eq ('0' x40)) {
3613 if ($size >= 48) {
3614 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3615 $read = sysread($fh, $buf, 24) or
3616 croak "read: $!";
3617 $read == 24 or
3618 croak "read only $read bytes (!= 24)";
3619 ($last_rev, $last_commit) =
3620 unpack(rev_map_fmt, $buf);
3621 if ($last_commit eq ('0' x40)) {
3622 croak "inconsistent .rev_map\n";
3625 if ($last_rev >= $rev) {
3626 croak "last_rev is higher!: $last_rev >= $rev";
3628 $wr_offset = -24;
3631 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3632 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3633 croak "write: $!";
3636 sub _rev_map_reset {
3637 my ($fh, $rev, $commit) = @_;
3638 my $c = _rev_map_get($fh, $rev);
3639 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3640 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3641 truncate $fh, $offset or croak "truncate: $!";
3644 sub mkfile {
3645 my ($path) = @_;
3646 unless (-e $path) {
3647 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3648 mkpath([$dir]) unless -d $dir;
3649 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3650 close $fh or die "Couldn't close (create) $path: $!\n";
3654 sub rev_map_set {
3655 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3656 defined $commit or die "missing arg3\n";
3657 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3658 my $db = $self->map_path($uuid);
3659 my $db_lock = "$db.lock";
3660 my $sig;
3661 $update_ref ||= 0;
3662 if ($update_ref) {
3663 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3664 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3666 mkfile($db);
3668 $LOCKFILES{$db_lock} = 1;
3669 my $sync;
3670 # both of these options make our .rev_db file very, very important
3671 # and we can't afford to lose it because rebuild() won't work
3672 if ($self->use_svm_props || $self->no_metadata) {
3673 $sync = 1;
3674 copy($db, $db_lock) or die "rev_map_set(@_): ",
3675 "Failed to copy: ",
3676 "$db => $db_lock ($!)\n";
3677 } else {
3678 rename $db, $db_lock or die "rev_map_set(@_): ",
3679 "Failed to rename: ",
3680 "$db => $db_lock ($!)\n";
3683 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3684 or croak "Couldn't open $db_lock: $!\n";
3685 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3686 _rev_map_set($fh, $rev, $commit);
3687 if ($sync) {
3688 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3689 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3691 close $fh or croak $!;
3692 if ($update_ref) {
3693 $_head = $self;
3694 my $note = "";
3695 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3696 command_noisy('update-ref', '-m', "r$rev$note",
3697 $self->refname, $commit);
3699 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3700 "$db_lock => $db ($!)\n";
3701 delete $LOCKFILES{$db_lock};
3702 if ($update_ref) {
3703 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3704 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3705 kill $sig, $$ if defined $sig;
3709 # If want_commit, this will return an array of (rev, commit) where
3710 # commit _must_ be a valid commit in the archive.
3711 # Otherwise, it'll return the max revision (whether or not the
3712 # commit is valid or just a 0x40 placeholder).
3713 sub rev_map_max {
3714 my ($self, $want_commit) = @_;
3715 $self->rebuild;
3716 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3717 $want_commit ? ($r, $c) : $r;
3720 sub rev_map_max_norebuild {
3721 my ($self, $want_commit) = @_;
3722 my $map_path = $self->map_path;
3723 stat $map_path or return $want_commit ? (0, undef) : 0;
3724 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3725 binmode $fh or croak "binmode: $!";
3726 my $size = (stat($fh))[7];
3727 ($size % 24) == 0 or croak "inconsistent size: $size";
3729 if ($size == 0) {
3730 close $fh or croak "close: $!";
3731 return $want_commit ? (0, undef) : 0;
3734 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3735 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3736 my ($r, $c) = unpack(rev_map_fmt, $buf);
3737 if ($want_commit && $c eq ('0' x40)) {
3738 if ($size < 48) {
3739 return $want_commit ? (0, undef) : 0;
3741 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3742 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3743 ($r, $c) = unpack(rev_map_fmt, $buf);
3744 if ($c eq ('0'x40)) {
3745 croak "Penultimate record is all-zeroes in $map_path";
3748 close $fh or croak "close: $!";
3749 $want_commit ? ($r, $c) : $r;
3752 sub rev_map_get {
3753 my ($self, $rev, $uuid) = @_;
3754 my $map_path = $self->map_path($uuid);
3755 return undef unless -e $map_path;
3757 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3758 my $c = _rev_map_get($fh, $rev);
3759 close($fh) or croak "close: $!";
3763 sub _rev_map_get {
3764 my ($fh, $rev) = @_;
3766 binmode $fh or croak "binmode: $!";
3767 my $size = (stat($fh))[7];
3768 ($size % 24) == 0 or croak "inconsistent size: $size";
3770 if ($size == 0) {
3771 return undef;
3774 my ($l, $u) = (0, $size - 24);
3775 my ($r, $c, $buf);
3777 while ($l <= $u) {
3778 my $i = int(($l/24 + $u/24) / 2) * 24;
3779 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3780 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3781 my ($r, $c) = unpack(rev_map_fmt, $buf);
3783 if ($r < $rev) {
3784 $l = $i + 24;
3785 } elsif ($r > $rev) {
3786 $u = $i - 24;
3787 } else { # $r == $rev
3788 return $c eq ('0' x 40) ? undef : $c;
3791 undef;
3794 # Finds the first svn revision that exists on (if $eq_ok is true) or
3795 # before $rev for the current branch. It will not search any lower
3796 # than $min_rev. Returns the git commit hash and svn revision number
3797 # if found, else (undef, undef).
3798 sub find_rev_before {
3799 my ($self, $rev, $eq_ok, $min_rev) = @_;
3800 --$rev unless $eq_ok;
3801 $min_rev ||= 1;
3802 my $max_rev = $self->rev_map_max;
3803 $rev = $max_rev if ($rev > $max_rev);
3804 while ($rev >= $min_rev) {
3805 if (my $c = $self->rev_map_get($rev)) {
3806 return ($rev, $c);
3808 --$rev;
3810 return (undef, undef);
3813 # Finds the first svn revision that exists on (if $eq_ok is true) or
3814 # after $rev for the current branch. It will not search any higher
3815 # than $max_rev. Returns the git commit hash and svn revision number
3816 # if found, else (undef, undef).
3817 sub find_rev_after {
3818 my ($self, $rev, $eq_ok, $max_rev) = @_;
3819 ++$rev unless $eq_ok;
3820 $max_rev ||= $self->rev_map_max;
3821 while ($rev <= $max_rev) {
3822 if (my $c = $self->rev_map_get($rev)) {
3823 return ($rev, $c);
3825 ++$rev;
3827 return (undef, undef);
3830 sub _new {
3831 my ($class, $repo_id, $ref_id, $path) = @_;
3832 unless (defined $repo_id && length $repo_id) {
3833 $repo_id = $Git::SVN::default_repo_id;
3835 unless (defined $ref_id && length $ref_id) {
3836 $_prefix = '' unless defined($_prefix);
3837 $_[2] = $ref_id =
3838 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3840 $_[1] = $repo_id;
3841 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3843 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3844 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3845 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3846 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3847 if (-d $old_dir && ! -d $dir) {
3848 $dir = $old_dir;
3852 $_[3] = $path = '' unless (defined $path);
3853 mkpath([$dir]);
3854 bless {
3855 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3856 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3857 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3860 # for read-only access of old .rev_db formats
3861 sub unlink_rev_db_symlink {
3862 my ($self) = @_;
3863 my $link = $self->rev_db_path;
3864 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3865 if (-l $link) {
3866 unlink $link or croak "unlink: $link failed!";
3870 sub rev_db_path {
3871 my ($self, $uuid) = @_;
3872 my $db_path = $self->map_path($uuid);
3873 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3874 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3875 $db_path;
3878 # the new replacement for .rev_db
3879 sub map_path {
3880 my ($self, $uuid) = @_;
3881 $uuid ||= $self->ra_uuid;
3882 "$self->{map_root}.$uuid";
3885 sub uri_encode {
3886 my ($f) = @_;
3887 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3891 sub uri_decode {
3892 my ($f) = @_;
3893 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3897 sub remove_username {
3898 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3901 package Git::SVN::Prompt;
3902 use strict;
3903 use warnings;
3904 require SVN::Core;
3905 use vars qw/$_no_auth_cache $_username/;
3907 sub simple {
3908 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3909 $may_save = undef if $_no_auth_cache;
3910 $default_username = $_username if defined $_username;
3911 if (defined $default_username && length $default_username) {
3912 if (defined $realm && length $realm) {
3913 print STDERR "Authentication realm: $realm\n";
3914 STDERR->flush;
3916 $cred->username($default_username);
3917 } else {
3918 username($cred, $realm, $may_save, $pool);
3920 $cred->password(_read_password("Password for '" .
3921 $cred->username . "': ", $realm));
3922 $cred->may_save($may_save);
3923 $SVN::_Core::SVN_NO_ERROR;
3926 sub ssl_server_trust {
3927 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3928 $may_save = undef if $_no_auth_cache;
3929 print STDERR "Error validating server certificate for '$realm':\n";
3931 no warnings 'once';
3932 # All variables SVN::Auth::SSL::* are used only once,
3933 # so we're shutting up Perl warnings about this.
3934 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3935 print STDERR " - The certificate is not issued ",
3936 "by a trusted authority. Use the\n",
3937 " fingerprint to validate ",
3938 "the certificate manually!\n";
3940 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3941 print STDERR " - The certificate hostname ",
3942 "does not match.\n";
3944 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3945 print STDERR " - The certificate is not yet valid.\n";
3947 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3948 print STDERR " - The certificate has expired.\n";
3950 if ($failures & $SVN::Auth::SSL::OTHER) {
3951 print STDERR " - The certificate has ",
3952 "an unknown error.\n";
3954 } # no warnings 'once'
3955 printf STDERR
3956 "Certificate information:\n".
3957 " - Hostname: %s\n".
3958 " - Valid: from %s until %s\n".
3959 " - Issuer: %s\n".
3960 " - Fingerprint: %s\n",
3961 map $cert_info->$_, qw(hostname valid_from valid_until
3962 issuer_dname fingerprint);
3963 my $choice;
3964 prompt:
3965 print STDERR $may_save ?
3966 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3967 "(R)eject or accept (t)emporarily? ";
3968 STDERR->flush;
3969 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3970 if ($choice =~ /^t$/i) {
3971 $cred->may_save(undef);
3972 } elsif ($choice =~ /^r$/i) {
3973 return -1;
3974 } elsif ($may_save && $choice =~ /^p$/i) {
3975 $cred->may_save($may_save);
3976 } else {
3977 goto prompt;
3979 $cred->accepted_failures($failures);
3980 $SVN::_Core::SVN_NO_ERROR;
3983 sub ssl_client_cert {
3984 my ($cred, $realm, $may_save, $pool) = @_;
3985 $may_save = undef if $_no_auth_cache;
3986 print STDERR "Client certificate filename: ";
3987 STDERR->flush;
3988 chomp(my $filename = <STDIN>);
3989 $cred->cert_file($filename);
3990 $cred->may_save($may_save);
3991 $SVN::_Core::SVN_NO_ERROR;
3994 sub ssl_client_cert_pw {
3995 my ($cred, $realm, $may_save, $pool) = @_;
3996 $may_save = undef if $_no_auth_cache;
3997 $cred->password(_read_password("Password: ", $realm));
3998 $cred->may_save($may_save);
3999 $SVN::_Core::SVN_NO_ERROR;
4002 sub username {
4003 my ($cred, $realm, $may_save, $pool) = @_;
4004 $may_save = undef if $_no_auth_cache;
4005 if (defined $realm && length $realm) {
4006 print STDERR "Authentication realm: $realm\n";
4008 my $username;
4009 if (defined $_username) {
4010 $username = $_username;
4011 } else {
4012 print STDERR "Username: ";
4013 STDERR->flush;
4014 chomp($username = <STDIN>);
4016 $cred->username($username);
4017 $cred->may_save($may_save);
4018 $SVN::_Core::SVN_NO_ERROR;
4021 sub _read_password {
4022 my ($prompt, $realm) = @_;
4023 my $password = '';
4024 if (exists $ENV{GIT_ASKPASS}) {
4025 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4026 $password = <PH>;
4027 $password =~ s/[\012\015]//; # \n\r
4028 close(PH);
4029 } else {
4030 print STDERR $prompt;
4031 STDERR->flush;
4032 require Term::ReadKey;
4033 Term::ReadKey::ReadMode('noecho');
4034 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4035 last if $key =~ /[\012\015]/; # \n\r
4036 $password .= $key;
4038 Term::ReadKey::ReadMode('restore');
4039 print STDERR "\n";
4040 STDERR->flush;
4042 $password;
4045 package SVN::Git::Fetcher;
4046 use vars qw/@ISA/;
4047 use strict;
4048 use warnings;
4049 use Carp qw/croak/;
4050 use IO::File qw//;
4051 use vars qw/$_ignore_regex/;
4053 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4054 sub new {
4055 my ($class, $git_svn, $switch_path) = @_;
4056 my $self = SVN::Delta::Editor->new;
4057 bless $self, $class;
4058 if (exists $git_svn->{last_commit}) {
4059 $self->{c} = $git_svn->{last_commit};
4060 $self->{empty_symlinks} =
4061 _mark_empty_symlinks($git_svn, $switch_path);
4063 $self->{ignore_regex} = eval { command_oneline('config', '--get',
4064 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
4065 $self->{empty} = {};
4066 $self->{dir_prop} = {};
4067 $self->{file_prop} = {};
4068 $self->{absent_dir} = {};
4069 $self->{absent_file} = {};
4070 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4071 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4072 $self;
4075 # this uses the Ra object, so it must be called before do_{switch,update},
4076 # not inside them (when the Git::SVN::Fetcher object is passed) to
4077 # do_{switch,update}
4078 sub _mark_empty_symlinks {
4079 my ($git_svn, $switch_path) = @_;
4080 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4081 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4083 my %ret;
4084 my ($rev, $cmt) = $git_svn->last_rev_commit;
4085 return {} unless ($rev && $cmt);
4087 # allow the warning to be printed for each revision we fetch to
4088 # ensure the user sees it. The user can also disable the workaround
4089 # on the repository even while git svn is running and the next
4090 # revision fetched will skip this expensive function.
4091 my $printed_warning;
4092 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4093 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4094 local $/ = "\0";
4095 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4096 $pfx .= '/' if length($pfx);
4097 while (<$ls>) {
4098 chomp;
4099 s/\A100644 blob $empty_blob\t//o or next;
4100 unless ($printed_warning) {
4101 print STDERR "Scanning for empty symlinks, ",
4102 "this may take a while if you have ",
4103 "many empty files\n",
4104 "You may disable this with `",
4105 "git config svn.brokenSymlinkWorkaround ",
4106 "false'.\n",
4107 "This may be done in a different ",
4108 "terminal without restarting ",
4109 "git svn\n";
4110 $printed_warning = 1;
4112 my $path = $_;
4113 my (undef, $props) =
4114 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4115 if ($props->{'svn:special'}) {
4116 $ret{$path} = 1;
4119 command_close_pipe($ls, $ctx);
4120 \%ret;
4123 # returns true if a given path is inside a ".git" directory
4124 sub in_dot_git {
4125 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4128 # return value: 0 -- don't ignore, 1 -- ignore
4129 sub is_path_ignored {
4130 my ($self, $path) = @_;
4131 return 1 if in_dot_git($path);
4132 return 1 if defined($self->{ignore_regex}) &&
4133 $path =~ m!$self->{ignore_regex}!;
4134 return 0 unless defined($_ignore_regex);
4135 return 1 if $path =~ m!$_ignore_regex!o;
4136 return 0;
4139 sub set_path_strip {
4140 my ($self, $path) = @_;
4141 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4144 sub open_root {
4145 { path => '' };
4148 sub open_directory {
4149 my ($self, $path, $pb, $rev) = @_;
4150 { path => $path };
4153 sub git_path {
4154 my ($self, $path) = @_;
4155 if (my $enc = $self->{pathnameencoding}) {
4156 require Encode;
4157 Encode::from_to($path, 'UTF-8', $enc);
4159 if ($self->{path_strip}) {
4160 $path =~ s!$self->{path_strip}!! or
4161 die "Failed to strip path '$path' ($self->{path_strip})\n";
4163 $path;
4166 sub delete_entry {
4167 my ($self, $path, $rev, $pb) = @_;
4168 return undef if $self->is_path_ignored($path);
4170 my $gpath = $self->git_path($path);
4171 return undef if ($gpath eq '');
4173 # remove entire directories.
4174 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4175 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4176 if ($tree) {
4177 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4178 -r --name-only -z/,
4179 $tree);
4180 local $/ = "\0";
4181 while (<$ls>) {
4182 chomp;
4183 my $rmpath = "$gpath/$_";
4184 $self->{gii}->remove($rmpath);
4185 print "\tD\t$rmpath\n" unless $::_q;
4187 print "\tD\t$gpath/\n" unless $::_q;
4188 command_close_pipe($ls, $ctx);
4189 } else {
4190 $self->{gii