i18n: mark init-db messages for translation
[git/mjg.git] / git-svn.perl
blobbf0451b46835357af7811096538e9e7d75311166
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;
62 use Memoize; # core since 5.8.0, Jul 2002
64 BEGIN {
65 # import functions from Git into our packages, en masse
66 no strict 'refs';
67 foreach (qw/command command_oneline command_noisy command_output_pipe
68 command_input_pipe command_close_pipe
69 command_bidi_pipe command_close_bidi_pipe/) {
70 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
71 Git::SVN::Migration Git::SVN::Log Git::SVN),
72 __PACKAGE__) {
73 *{"${package}::$_"} = \&{"Git::$_"};
76 Memoize::memoize 'Git::config';
77 Memoize::memoize 'Git::config_bool';
80 my ($SVN);
82 $sha1 = qr/[a-f\d]{40}/;
83 $sha1_short = qr/[a-f\d]{4,40}/;
84 my ($_stdin, $_help, $_edit,
85 $_message, $_file, $_branch_dest,
86 $_template, $_shared,
87 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
88 $_merge, $_strategy, $_dry_run, $_local,
89 $_prefix, $_no_checkout, $_url, $_verbose,
90 $_git_format, $_commit_url, $_tag, $_merge_info);
91 $Git::SVN::_follow_parent = 1;
92 $_q ||= 0;
93 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
94 'config-dir=s' => \$Git::SVN::Ra::config_dir,
95 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
96 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
97 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
98 'authors-file|A=s' => \$_authors,
99 'authors-prog=s' => \$_authors_prog,
100 'repack:i' => \$Git::SVN::_repack,
101 'noMetadata' => \$Git::SVN::_no_metadata,
102 'useSvmProps' => \$Git::SVN::_use_svm_props,
103 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
104 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
105 'no-checkout' => \$_no_checkout,
106 'quiet|q+' => \$_q,
107 'repack-flags|repack-args|repack-opts=s' =>
108 \$Git::SVN::_repack_flags,
109 'use-log-author' => \$Git::SVN::_use_log_author,
110 'add-author-from' => \$Git::SVN::_add_author_from,
111 'localtime' => \$Git::SVN::_localtime,
112 %remote_opts );
114 my ($_trunk, @_tags, @_branches, $_stdlayout);
115 my %icv;
116 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
117 'trunk|T=s' => \$_trunk, 'tags|t=s@' => \@_tags,
118 'branches|b=s@' => \@_branches, 'prefix=s' => \$_prefix,
119 'stdlayout|s' => \$_stdlayout,
120 'minimize-url|m!' => \$Git::SVN::_minimize_url,
121 'no-metadata' => sub { $icv{noMetadata} = 1 },
122 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
123 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
124 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
125 'rewrite-uuid=s' => sub { $icv{rewriteUUID} = $_[1] },
126 %remote_opts );
127 my %cmt_opts = ( 'edit|e' => \$_edit,
128 'rmdir' => \$SVN::Git::Editor::_rmdir,
129 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
130 'l=i' => \$SVN::Git::Editor::_rename_limit,
131 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
134 my %cmd = (
135 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
136 { 'revision|r=s' => \$_revision,
137 'fetch-all|all' => \$_fetch_all,
138 'parent|p' => \$_fetch_parent,
139 %fc_opts } ],
140 clone => [ \&cmd_clone, "Initialize and fetch revisions",
141 { 'revision|r=s' => \$_revision,
142 %fc_opts, %init_opts } ],
143 init => [ \&cmd_init, "Initialize a repo for tracking" .
144 " (requires URL argument)",
145 \%init_opts ],
146 'multi-init' => [ \&cmd_multi_init,
147 "Deprecated alias for ".
148 "'$0 init -T<trunk> -b<branches> -t<tags>'",
149 \%init_opts ],
150 dcommit => [ \&cmd_dcommit,
151 'Commit several diffs to merge with upstream',
152 { 'merge|m|M' => \$_merge,
153 'strategy|s=s' => \$_strategy,
154 'verbose|v' => \$_verbose,
155 'dry-run|n' => \$_dry_run,
156 'fetch-all|all' => \$_fetch_all,
157 'commit-url=s' => \$_commit_url,
158 'revision|r=i' => \$_revision,
159 'no-rebase' => \$_no_rebase,
160 'mergeinfo=s' => \$_merge_info,
161 %cmt_opts, %fc_opts } ],
162 branch => [ \&cmd_branch,
163 'Create a branch in the SVN repository',
164 { 'message|m=s' => \$_message,
165 'destination|d=s' => \$_branch_dest,
166 'dry-run|n' => \$_dry_run,
167 'tag|t' => \$_tag,
168 'username=s' => \$Git::SVN::Prompt::_username,
169 'commit-url=s' => \$_commit_url } ],
170 tag => [ sub { $_tag = 1; cmd_branch(@_) },
171 'Create a tag in the SVN repository',
172 { 'message|m=s' => \$_message,
173 'destination|d=s' => \$_branch_dest,
174 'dry-run|n' => \$_dry_run,
175 'username=s' => \$Git::SVN::Prompt::_username,
176 'commit-url=s' => \$_commit_url } ],
177 'set-tree' => [ \&cmd_set_tree,
178 "Set an SVN repository to a git tree-ish",
179 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
180 'create-ignore' => [ \&cmd_create_ignore,
181 'Create a .gitignore per svn:ignore',
182 { 'revision|r=i' => \$_revision
183 } ],
184 'mkdirs' => [ \&cmd_mkdirs ,
185 "recreate empty directories after a checkout",
186 { 'revision|r=i' => \$_revision } ],
187 'propget' => [ \&cmd_propget,
188 'Print the value of a property on a file or directory',
189 { 'revision|r=i' => \$_revision } ],
190 'proplist' => [ \&cmd_proplist,
191 'List all properties of a file or directory',
192 { 'revision|r=i' => \$_revision } ],
193 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
194 { 'revision|r=i' => \$_revision
195 } ],
196 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
197 { 'revision|r=i' => \$_revision
198 } ],
199 'multi-fetch' => [ \&cmd_multi_fetch,
200 "Deprecated alias for $0 fetch --all",
201 { 'revision|r=s' => \$_revision, %fc_opts } ],
202 'migrate' => [ sub { },
203 # no-op, we automatically run this anyways,
204 'Migrate configuration/metadata/layout from
205 previous versions of git-svn',
206 { 'minimize' => \$Git::SVN::Migration::_minimize,
207 %remote_opts } ],
208 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
209 { 'limit=i' => \$Git::SVN::Log::limit,
210 'revision|r=s' => \$_revision,
211 'verbose|v' => \$Git::SVN::Log::verbose,
212 'incremental' => \$Git::SVN::Log::incremental,
213 'oneline' => \$Git::SVN::Log::oneline,
214 'show-commit' => \$Git::SVN::Log::show_commit,
215 'non-recursive' => \$Git::SVN::Log::non_recursive,
216 'authors-file|A=s' => \$_authors,
217 'color' => \$Git::SVN::Log::color,
218 'pager=s' => \$Git::SVN::Log::pager
219 } ],
220 'find-rev' => [ \&cmd_find_rev,
221 "Translate between SVN revision numbers and tree-ish",
222 {} ],
223 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
224 { 'merge|m|M' => \$_merge,
225 'verbose|v' => \$_verbose,
226 'strategy|s=s' => \$_strategy,
227 'local|l' => \$_local,
228 'fetch-all|all' => \$_fetch_all,
229 'dry-run|n' => \$_dry_run,
230 %fc_opts } ],
231 'commit-diff' => [ \&cmd_commit_diff,
232 'Commit a diff between two trees',
233 { 'message|m=s' => \$_message,
234 'file|F=s' => \$_file,
235 'revision|r=s' => \$_revision,
236 %cmt_opts } ],
237 'info' => [ \&cmd_info,
238 "Show info about the latest SVN revision
239 on the current branch",
240 { 'url' => \$_url, } ],
241 'blame' => [ \&Git::SVN::Log::cmd_blame,
242 "Show what revision and author last modified each line of a file",
243 { 'git-format' => \$_git_format } ],
244 'reset' => [ \&cmd_reset,
245 "Undo fetches back to the specified SVN revision",
246 { 'revision|r=s' => \$_revision,
247 'parent|p' => \$_fetch_parent } ],
248 'gc' => [ \&cmd_gc,
249 "Compress unhandled.log files in .git/svn and remove " .
250 "index files in .git/svn",
251 {} ],
254 my $cmd;
255 for (my $i = 0; $i < @ARGV; $i++) {
256 if (defined $cmd{$ARGV[$i]}) {
257 $cmd = $ARGV[$i];
258 splice @ARGV, $i, 1;
259 last;
260 } elsif ($ARGV[$i] eq 'help') {
261 $cmd = $ARGV[$i+1];
262 usage(0);
266 # make sure we're always running at the top-level working directory
267 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
268 unless (-d $ENV{GIT_DIR}) {
269 if ($git_dir_user_set) {
270 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
271 "but it is not a directory\n";
273 my $git_dir = delete $ENV{GIT_DIR};
274 my $cdup = undef;
275 git_cmd_try {
276 $cdup = command_oneline(qw/rev-parse --show-cdup/);
277 $git_dir = '.' unless ($cdup);
278 chomp $cdup if ($cdup);
279 $cdup = "." unless ($cdup && length $cdup);
280 } "Already at toplevel, but $git_dir not found\n";
281 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
282 unless (-d $git_dir) {
283 die "$git_dir still not found after going to ",
284 "'$cdup'\n";
286 $ENV{GIT_DIR} = $git_dir;
288 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
291 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
293 read_git_config(\%opts);
294 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
295 Getopt::Long::Configure('pass_through');
297 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
298 'minimize-connections' => \$Git::SVN::Migration::_minimize,
299 'id|i=s' => \$Git::SVN::default_ref_id,
300 'svn-remote|remote|R=s' => sub {
301 $Git::SVN::no_reuse_existing = 1;
302 $Git::SVN::default_repo_id = $_[1] });
303 exit 1 if (!$rv && $cmd && $cmd ne 'log');
305 usage(0) if $_help;
306 version() if $_version;
307 usage(1) unless defined $cmd;
308 load_authors() if $_authors;
309 if (defined $_authors_prog) {
310 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
313 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
314 Git::SVN::Migration::migration_check();
316 Git::SVN::init_vars();
317 eval {
318 Git::SVN::verify_remotes_sanity();
319 $cmd{$cmd}->[0]->(@ARGV);
321 fatal $@ if $@;
322 post_fetch_checkout();
323 exit 0;
325 ####################### primary functions ######################
326 sub usage {
327 my $exit = shift || 0;
328 my $fd = $exit ? \*STDERR : \*STDOUT;
329 print $fd <<"";
330 git-svn - bidirectional operations between a single Subversion tree and git
331 Usage: git svn <command> [options] [arguments]\n
333 print $fd "Available commands:\n" unless $cmd;
335 foreach (sort keys %cmd) {
336 next if $cmd && $cmd ne $_;
337 next if /^multi-/; # don't show deprecated commands
338 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
339 foreach (sort keys %{$cmd{$_}->[2]}) {
340 # mixed-case options are for .git/config only
341 next if /[A-Z]/ && /^[a-z]+$/i;
342 # prints out arguments as they should be passed:
343 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
344 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
345 "--$_" : "-$_" }
346 split /\|/,$_)," $x\n";
349 print $fd <<"";
350 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
351 arbitrary identifier if you're tracking multiple SVN branches/repositories in
352 one git repository and want to keep them separate. See git-svn(1) for more
353 information.
355 exit $exit;
358 sub version {
359 ::_req_svn();
360 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
361 exit 0;
364 sub do_git_init_db {
365 unless (-d $ENV{GIT_DIR}) {
366 my @init_db = ('init');
367 push @init_db, "--template=$_template" if defined $_template;
368 if (defined $_shared) {
369 if ($_shared =~ /[a-z]/) {
370 push @init_db, "--shared=$_shared";
371 } else {
372 push @init_db, "--shared";
375 command_noisy(@init_db);
376 $_repository = Git->repository(Repository => ".git");
378 my $set;
379 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
380 foreach my $i (keys %icv) {
381 die "'$set' and '$i' cannot both be set\n" if $set;
382 next unless defined $icv{$i};
383 command_noisy('config', "$pfx.$i", $icv{$i});
384 $set = $i;
386 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
387 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
388 if defined $$ignore_regex;
391 sub init_subdir {
392 my $repo_path = shift or return;
393 mkpath([$repo_path]) unless -d $repo_path;
394 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
395 $ENV{GIT_DIR} = '.git';
396 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
399 sub cmd_clone {
400 my ($url, $path) = @_;
401 if (!defined $path &&
402 (defined $_trunk || @_branches || @_tags ||
403 defined $_stdlayout) &&
404 $url !~ m#^[a-z\+]+://#) {
405 $path = $url;
407 $path = basename($url) if !defined $path || !length $path;
408 my $authors_absolute = $_authors ? File::Spec->rel2abs($_authors) : "";
409 cmd_init($url, $path);
410 command_oneline('config', 'svn.authorsfile', $authors_absolute)
411 if $_authors;
412 Git::SVN::fetch_all($Git::SVN::default_repo_id);
415 sub cmd_init {
416 if (defined $_stdlayout) {
417 $_trunk = 'trunk' if (!defined $_trunk);
418 @_tags = 'tags' if (! @_tags);
419 @_branches = 'branches' if (! @_branches);
421 if (defined $_trunk || @_branches || @_tags) {
422 return cmd_multi_init(@_);
424 my $url = shift or die "SVN repository location required ",
425 "as a command-line argument\n";
426 $url = canonicalize_url($url);
427 init_subdir(@_);
428 do_git_init_db();
430 if ($Git::SVN::_minimize_url eq 'unset') {
431 $Git::SVN::_minimize_url = 0;
434 Git::SVN->init($url);
437 sub cmd_fetch {
438 if (grep /^\d+=./, @_) {
439 die "'<rev>=<commit>' fetch arguments are ",
440 "no longer supported.\n";
442 my ($remote) = @_;
443 if (@_ > 1) {
444 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
446 $Git::SVN::no_reuse_existing = undef;
447 if ($_fetch_parent) {
448 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
449 unless ($gs) {
450 die "Unable to determine upstream SVN information from ",
451 "working tree history\n";
453 # just fetch, don't checkout.
454 $_no_checkout = 'true';
455 $_fetch_all ? $gs->fetch_all : $gs->fetch;
456 } elsif ($_fetch_all) {
457 cmd_multi_fetch();
458 } else {
459 $remote ||= $Git::SVN::default_repo_id;
460 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
464 sub cmd_set_tree {
465 my (@commits) = @_;
466 if ($_stdin || !@commits) {
467 print "Reading from stdin...\n";
468 @commits = ();
469 while (<STDIN>) {
470 if (/\b($sha1_short)\b/o) {
471 unshift @commits, $1;
475 my @revs;
476 foreach my $c (@commits) {
477 my @tmp = command('rev-parse',$c);
478 if (scalar @tmp == 1) {
479 push @revs, $tmp[0];
480 } elsif (scalar @tmp > 1) {
481 push @revs, reverse(command('rev-list',@tmp));
482 } else {
483 fatal "Failed to rev-parse $c";
486 my $gs = Git::SVN->new;
487 my ($r_last, $cmt_last) = $gs->last_rev_commit;
488 $gs->fetch;
489 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
490 fatal "There are new revisions that were fetched ",
491 "and need to be merged (or acknowledged) ",
492 "before committing.\nlast rev: $r_last\n",
493 " current: $gs->{last_rev}";
495 $gs->set_tree($_) foreach @revs;
496 print "Done committing ",scalar @revs," revisions to SVN\n";
497 unlink $gs->{index};
500 sub cmd_dcommit {
501 my $head = shift;
502 command_noisy(qw/update-index --refresh/);
503 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
504 'Cannot dcommit with a dirty index. Commit your changes first, '
505 . "or stash them with `git stash'.\n";
506 $head ||= 'HEAD';
508 my $old_head;
509 if ($head ne 'HEAD') {
510 $old_head = eval {
511 command_oneline([qw/symbolic-ref -q HEAD/])
513 if ($old_head) {
514 $old_head =~ s{^refs/heads/}{};
515 } else {
516 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
518 command(['checkout', $head], STDERR => 0);
521 my @refs;
522 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
523 unless ($gs) {
524 die "Unable to determine upstream SVN information from ",
525 "$head history.\nPerhaps the repository is empty.";
528 if (defined $_commit_url) {
529 $url = $_commit_url;
530 } else {
531 $url = eval { command_oneline('config', '--get',
532 "svn-remote.$gs->{repo_id}.commiturl") };
533 if (!$url) {
534 $url = $gs->full_pushurl
538 my $last_rev = $_revision if defined $_revision;
539 if ($url) {
540 print "Committing to $url ...\n";
542 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
543 if ($_no_rebase && scalar(@$linear_refs) > 1) {
544 warn "Attempting to commit more than one change while ",
545 "--no-rebase is enabled.\n",
546 "If these changes depend on each other, re-running ",
547 "without --no-rebase may be required."
549 my $expect_url = $url;
550 Git::SVN::remove_username($expect_url);
551 while (1) {
552 my $d = shift @$linear_refs or last;
553 unless (defined $last_rev) {
554 (undef, $last_rev, undef) = cmt_metadata("$d~1");
555 unless (defined $last_rev) {
556 fatal "Unable to extract revision information ",
557 "from commit $d~1";
560 if ($_dry_run) {
561 print "diff-tree $d~1 $d\n";
562 } else {
563 my $cmt_rev;
564 my %ed_opts = ( r => $last_rev,
565 log => get_commit_entry($d)->{log},
566 ra => Git::SVN::Ra->new($url),
567 config => SVN::Core::config_get_config(
568 $Git::SVN::Ra::config_dir
570 tree_a => "$d~1",
571 tree_b => $d,
572 editor_cb => sub {
573 print "Committed r$_[0]\n";
574 $cmt_rev = $_[0];
576 mergeinfo => $_merge_info,
577 svn_path => '');
578 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
579 print "No changes\n$d~1 == $d\n";
580 } elsif ($parents->{$d} && @{$parents->{$d}}) {
581 $gs->{inject_parents_dcommit}->{$cmt_rev} =
582 $parents->{$d};
584 $_fetch_all ? $gs->fetch_all : $gs->fetch;
585 $last_rev = $cmt_rev;
586 next if $_no_rebase;
588 # we always want to rebase against the current HEAD,
589 # not any head that was passed to us
590 my @diff = command('diff-tree', $d,
591 $gs->refname, '--');
592 my @finish;
593 if (@diff) {
594 @finish = rebase_cmd();
595 print STDERR "W: $d and ", $gs->refname,
596 " differ, using @finish:\n",
597 join("\n", @diff), "\n";
598 } else {
599 print "No changes between current HEAD and ",
600 $gs->refname,
601 "\nResetting to the latest ",
602 $gs->refname, "\n";
603 @finish = qw/reset --mixed/;
605 command_noisy(@finish, $gs->refname);
606 if (@diff) {
607 @refs = ();
608 my ($url_, $rev_, $uuid_, $gs_) =
609 working_head_info('HEAD', \@refs);
610 my ($linear_refs_, $parents_) =
611 linearize_history($gs_, \@refs);
612 if (scalar(@$linear_refs) !=
613 scalar(@$linear_refs_)) {
614 fatal "# of revisions changed ",
615 "\nbefore:\n",
616 join("\n", @$linear_refs),
617 "\n\nafter:\n",
618 join("\n", @$linear_refs_), "\n",
619 'If you are attempting to commit ',
620 "merges, try running:\n\t",
621 'git rebase --interactive',
622 '--preserve-merges ',
623 $gs->refname,
624 "\nBefore dcommitting";
626 if ($url_ ne $expect_url) {
627 if ($url_ eq $gs->metadata_url) {
628 print
629 "Accepting rewritten URL:",
630 " $url_\n";
631 } else {
632 fatal
633 "URL mismatch after rebase:",
634 " $url_ != $expect_url";
637 if ($uuid_ ne $uuid) {
638 fatal "uuid mismatch after rebase: ",
639 "$uuid_ != $uuid";
641 # remap parents
642 my (%p, @l, $i);
643 for ($i = 0; $i < scalar @$linear_refs; $i++) {
644 my $new = $linear_refs_->[$i] or next;
645 $p{$new} =
646 $parents->{$linear_refs->[$i]};
647 push @l, $new;
649 $parents = \%p;
650 $linear_refs = \@l;
655 if ($old_head) {
656 my $new_head = command_oneline(qw/rev-parse HEAD/);
657 my $new_is_symbolic = eval {
658 command_oneline(qw/symbolic-ref -q HEAD/);
660 if ($new_is_symbolic) {
661 print "dcommitted the branch ", $head, "\n";
662 } else {
663 print "dcommitted on a detached HEAD because you gave ",
664 "a revision argument.\n",
665 "The rewritten commit is: ", $new_head, "\n";
667 command(['checkout', $old_head], STDERR => 0);
670 unlink $gs->{index};
673 sub cmd_branch {
674 my ($branch_name, $head) = @_;
676 unless (defined $branch_name && length $branch_name) {
677 die(($_tag ? "tag" : "branch") . " name required\n");
679 $head ||= 'HEAD';
681 my (undef, $rev, undef, $gs) = working_head_info($head);
682 my $src = $gs->full_pushurl;
684 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
685 my $allglobs = $remote->{ $_tag ? 'tags' : 'branches' };
686 my $glob;
687 if ($#{$allglobs} == 0) {
688 $glob = $allglobs->[0];
689 } else {
690 unless(defined $_branch_dest) {
691 die "Multiple ",
692 $_tag ? "tag" : "branch",
693 " paths defined for Subversion repository.\n",
694 "You must specify where you want to create the ",
695 $_tag ? "tag" : "branch",
696 " with the --destination argument.\n";
698 foreach my $g (@{$allglobs}) {
699 # SVN::Git::Editor could probably be moved to Git.pm..
700 my $re = SVN::Git::Editor::glob2pat($g->{path}->{left});
701 if ($_branch_dest =~ /$re/) {
702 $glob = $g;
703 last;
706 unless (defined $glob) {
707 my $dest_re = qr/\b\Q$_branch_dest\E\b/;
708 foreach my $g (@{$allglobs}) {
709 $g->{path}->{left} =~ /$dest_re/ or next;
710 if (defined $glob) {
711 die "Ambiguous destination: ",
712 $_branch_dest, "\nmatches both '",
713 $glob->{path}->{left}, "' and '",
714 $g->{path}->{left}, "'\n";
716 $glob = $g;
718 unless (defined $glob) {
719 die "Unknown ",
720 $_tag ? "tag" : "branch",
721 " destination $_branch_dest\n";
725 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
726 my $url;
727 if (defined $_commit_url) {
728 $url = $_commit_url;
729 } else {
730 $url = eval { command_oneline('config', '--get',
731 "svn-remote.$gs->{repo_id}.commiturl") };
732 if (!$url) {
733 $url = $remote->{pushurl} || $remote->{url};
736 my $dst = join '/', $url, $lft, $branch_name, ($rgt || ());
738 if ($dst =~ /^https:/ && $src =~ /^http:/) {
739 $src=~s/^http:/https:/;
742 ::_req_svn();
744 my $ctx = SVN::Client->new(
745 auth => Git::SVN::Ra::_auth_providers(),
746 log_msg => sub {
747 ${ $_[0] } = defined $_message
748 ? $_message
749 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
750 . $branch_name;
754 eval {
755 $ctx->ls($dst, 'HEAD', 0);
756 } and die "branch ${branch_name} already exists\n";
758 print "Copying ${src} at r${rev} to ${dst}...\n";
759 $ctx->copy($src, $rev, $dst)
760 unless $_dry_run;
762 $gs->fetch_all;
765 sub cmd_find_rev {
766 my $revision_or_hash = shift or die "SVN or git revision required ",
767 "as a command-line argument\n";
768 my $result;
769 if ($revision_or_hash =~ /^r\d+$/) {
770 my $head = shift;
771 $head ||= 'HEAD';
772 my @refs;
773 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
774 unless ($gs) {
775 die "Unable to determine upstream SVN information from ",
776 "$head history\n";
778 my $desired_revision = substr($revision_or_hash, 1);
779 $result = $gs->rev_map_get($desired_revision, $uuid);
780 } else {
781 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
782 $result = $rev;
784 print "$result\n" if $result;
787 sub cmd_rebase {
788 command_noisy(qw/update-index --refresh/);
789 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
790 unless ($gs) {
791 die "Unable to determine upstream SVN information from ",
792 "working tree history\n";
794 if ($_dry_run) {
795 print "Remote Branch: " . $gs->refname . "\n";
796 print "SVN URL: " . $url . "\n";
797 return;
799 if (command(qw/diff-index HEAD --/)) {
800 print STDERR "Cannot rebase with uncommited changes:\n";
801 command_noisy('status');
802 exit 1;
804 unless ($_local) {
805 # rebase will checkout for us, so no need to do it explicitly
806 $_no_checkout = 'true';
807 $_fetch_all ? $gs->fetch_all : $gs->fetch;
809 command_noisy(rebase_cmd(), $gs->refname);
810 $gs->mkemptydirs;
813 sub cmd_show_ignore {
814 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
815 $gs ||= Git::SVN->new;
816 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
817 $gs->prop_walk($gs->{path}, $r, sub {
818 my ($gs, $path, $props) = @_;
819 print STDOUT "\n# $path\n";
820 my $s = $props->{'svn:ignore'} or return;
821 $s =~ s/[\r\n]+/\n/g;
822 $s =~ s/^\n+//;
823 chomp $s;
824 $s =~ s#^#$path#gm;
825 print STDOUT "$s\n";
829 sub cmd_show_externals {
830 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
831 $gs ||= Git::SVN->new;
832 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
833 $gs->prop_walk($gs->{path}, $r, sub {
834 my ($gs, $path, $props) = @_;
835 print STDOUT "\n# $path\n";
836 my $s = $props->{'svn:externals'} or return;
837 $s =~ s/[\r\n]+/\n/g;
838 chomp $s;
839 $s =~ s#^#$path#gm;
840 print STDOUT "$s\n";
844 sub cmd_create_ignore {
845 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
846 $gs ||= Git::SVN->new;
847 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
848 $gs->prop_walk($gs->{path}, $r, sub {
849 my ($gs, $path, $props) = @_;
850 # $path is of the form /path/to/dir/
851 $path = '.' . $path;
852 # SVN can have attributes on empty directories,
853 # which git won't track
854 mkpath([$path]) unless -d $path;
855 my $ignore = $path . '.gitignore';
856 my $s = $props->{'svn:ignore'} or return;
857 open(GITIGNORE, '>', $ignore)
858 or fatal("Failed to open `$ignore' for writing: $!");
859 $s =~ s/[\r\n]+/\n/g;
860 $s =~ s/^\n+//;
861 chomp $s;
862 # Prefix all patterns so that the ignore doesn't apply
863 # to sub-directories.
864 $s =~ s#^#/#gm;
865 print GITIGNORE "$s\n";
866 close(GITIGNORE)
867 or fatal("Failed to close `$ignore': $!");
868 command_noisy('add', '-f', $ignore);
872 sub cmd_mkdirs {
873 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
874 $gs ||= Git::SVN->new;
875 $gs->mkemptydirs($_revision);
878 sub canonicalize_path {
879 my ($path) = @_;
880 my $dot_slash_added = 0;
881 if (substr($path, 0, 1) ne "/") {
882 $path = "./" . $path;
883 $dot_slash_added = 1;
885 # File::Spec->canonpath doesn't collapse x/../y into y (for a
886 # good reason), so let's do this manually.
887 $path =~ s#/+#/#g;
888 $path =~ s#/\.(?:/|$)#/#g;
889 $path =~ s#/[^/]+/\.\.##g;
890 $path =~ s#/$##g;
891 $path =~ s#^\./## if $dot_slash_added;
892 $path =~ s#^/##;
893 $path =~ s#^\.$##;
894 return $path;
897 sub canonicalize_url {
898 my ($url) = @_;
899 $url =~ s#^([^:]+://[^/]*/)(.*)$#$1 . canonicalize_path($2)#e;
900 return $url;
903 # get_svnprops(PATH)
904 # ------------------
905 # Helper for cmd_propget and cmd_proplist below.
906 sub get_svnprops {
907 my $path = shift;
908 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
909 $gs ||= Git::SVN->new;
911 # prefix THE PATH by the sub-directory from which the user
912 # invoked us.
913 $path = $cmd_dir_prefix . $path;
914 fatal("No such file or directory: $path") unless -e $path;
915 my $is_dir = -d $path ? 1 : 0;
916 $path = $gs->{path} . '/' . $path;
918 # canonicalize the path (otherwise libsvn will abort or fail to
919 # find the file)
920 $path = canonicalize_path($path);
922 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
923 my $props;
924 if ($is_dir) {
925 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
927 else {
928 (undef, $props) = $gs->ra->get_file($path, $r, undef);
930 return $props;
933 # cmd_propget (PROP, PATH)
934 # ------------------------
935 # Print the SVN property PROP for PATH.
936 sub cmd_propget {
937 my ($prop, $path) = @_;
938 $path = '.' if not defined $path;
939 usage(1) if not defined $prop;
940 my $props = get_svnprops($path);
941 if (not defined $props->{$prop}) {
942 fatal("`$path' does not have a `$prop' SVN property.");
944 print $props->{$prop} . "\n";
947 # cmd_proplist (PATH)
948 # -------------------
949 # Print the list of SVN properties for PATH.
950 sub cmd_proplist {
951 my $path = shift;
952 $path = '.' if not defined $path;
953 my $props = get_svnprops($path);
954 print "Properties on '$path':\n";
955 foreach (sort keys %{$props}) {
956 print " $_\n";
960 sub cmd_multi_init {
961 my $url = shift;
962 unless (defined $_trunk || @_branches || @_tags) {
963 usage(1);
966 $_prefix = '' unless defined $_prefix;
967 if (defined $url) {
968 $url = canonicalize_url($url);
969 init_subdir(@_);
971 do_git_init_db();
972 if (defined $_trunk) {
973 $_trunk =~ s#^/+##;
974 my $trunk_ref = 'refs/remotes/' . $_prefix . 'trunk';
975 # try both old-style and new-style lookups:
976 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
977 unless ($gs_trunk) {
978 my ($trunk_url, $trunk_path) =
979 complete_svn_url($url, $_trunk);
980 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
981 undef, $trunk_ref);
984 return unless @_branches || @_tags;
985 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
986 foreach my $path (@_branches) {
987 complete_url_ls_init($ra, $path, '--branches/-b', $_prefix);
989 foreach my $path (@_tags) {
990 complete_url_ls_init($ra, $path, '--tags/-t', $_prefix.'tags/');
994 sub cmd_multi_fetch {
995 $Git::SVN::no_reuse_existing = undef;
996 my $remotes = Git::SVN::read_all_remotes();
997 foreach my $repo_id (sort keys %$remotes) {
998 if ($remotes->{$repo_id}->{url}) {
999 Git::SVN::fetch_all($repo_id, $remotes);
1004 # this command is special because it requires no metadata
1005 sub cmd_commit_diff {
1006 my ($ta, $tb, $url) = @_;
1007 my $usage = "Usage: $0 commit-diff -r<revision> ".
1008 "<tree-ish> <tree-ish> [<URL>]";
1009 fatal($usage) if (!defined $ta || !defined $tb);
1010 my $svn_path = '';
1011 if (!defined $url) {
1012 my $gs = eval { Git::SVN->new };
1013 if (!$gs) {
1014 fatal("Needed URL or usable git-svn --id in ",
1015 "the command-line\n", $usage);
1017 $url = $gs->{url};
1018 $svn_path = $gs->{path};
1020 unless (defined $_revision) {
1021 fatal("-r|--revision is a required argument\n", $usage);
1023 if (defined $_message && defined $_file) {
1024 fatal("Both --message/-m and --file/-F specified ",
1025 "for the commit message.\n",
1026 "I have no idea what you mean");
1028 if (defined $_file) {
1029 $_message = file_to_s($_file);
1030 } else {
1031 $_message ||= get_commit_entry($tb)->{log};
1033 my $ra ||= Git::SVN::Ra->new($url);
1034 my $r = $_revision;
1035 if ($r eq 'HEAD') {
1036 $r = $ra->get_latest_revnum;
1037 } elsif ($r !~ /^\d+$/) {
1038 die "revision argument: $r not understood by git-svn\n";
1040 my %ed_opts = ( r => $r,
1041 log => $_message,
1042 ra => $ra,
1043 tree_a => $ta,
1044 tree_b => $tb,
1045 editor_cb => sub { print "Committed r$_[0]\n" },
1046 svn_path => $svn_path );
1047 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
1048 print "No changes\n$ta == $tb\n";
1052 sub escape_uri_only {
1053 my ($uri) = @_;
1054 my @tmp;
1055 foreach (split m{/}, $uri) {
1056 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
1057 push @tmp, $_;
1059 join('/', @tmp);
1062 sub escape_url {
1063 my ($url) = @_;
1064 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
1065 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
1066 $url = "$scheme://$domain$uri";
1068 $url;
1071 sub cmd_info {
1072 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
1073 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
1074 if (exists $_[1]) {
1075 die "Too many arguments specified\n";
1078 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
1080 if (!$file_type && !$diff_status) {
1081 print STDERR "svn: '$path' is not under version control\n";
1082 exit 1;
1085 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1086 unless ($gs) {
1087 die "Unable to determine upstream SVN information from ",
1088 "working tree history\n";
1091 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
1092 $path = "." if $path eq "";
1094 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
1096 if ($_url) {
1097 print escape_url($full_url), "\n";
1098 return;
1101 my $result = "Path: $path\n";
1102 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
1103 $result .= "URL: " . escape_url($full_url) . "\n";
1105 eval {
1106 my $repos_root = $gs->repos_root;
1107 Git::SVN::remove_username($repos_root);
1108 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
1110 if ($@) {
1111 $result .= "Repository Root: (offline)\n";
1113 ::_req_svn();
1114 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
1115 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
1116 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
1118 $result .= "Node Kind: " .
1119 ($file_type eq "dir" ? "directory" : "file") . "\n";
1121 my $schedule = $diff_status eq "A"
1122 ? "add"
1123 : ($diff_status eq "D" ? "delete" : "normal");
1124 $result .= "Schedule: $schedule\n";
1126 if ($diff_status eq "A") {
1127 print $result, "\n";
1128 return;
1131 my ($lc_author, $lc_rev, $lc_date_utc);
1132 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1133 my $log = command_output_pipe(@args);
1134 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1135 while (<$log>) {
1136 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1137 $lc_author = $1;
1138 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1139 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1140 (undef, $lc_rev, undef) = ::extract_metadata($1);
1143 close $log;
1145 Git::SVN::Log::set_local_timezone();
1147 $result .= "Last Changed Author: $lc_author\n";
1148 $result .= "Last Changed Rev: $lc_rev\n";
1149 $result .= "Last Changed Date: " .
1150 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1152 if ($file_type ne "dir") {
1153 my $text_last_updated_date =
1154 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1155 $result .=
1156 "Text Last Updated: " .
1157 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1158 "\n";
1159 my $checksum;
1160 if ($diff_status eq "D") {
1161 my ($fh, $ctx) =
1162 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1163 if ($file_type eq "link") {
1164 my $file_name = <$fh>;
1165 $checksum = md5sum("link $file_name");
1166 } else {
1167 $checksum = md5sum($fh);
1169 command_close_pipe($fh, $ctx);
1170 } elsif ($file_type eq "link") {
1171 my $file_name =
1172 command(qw(cat-file blob), "HEAD:$path");
1173 $checksum =
1174 md5sum("link " . $file_name);
1175 } else {
1176 open FILE, "<", $path or die $!;
1177 $checksum = md5sum(\*FILE);
1178 close FILE or die $!;
1180 $result .= "Checksum: " . $checksum . "\n";
1183 print $result, "\n";
1186 sub cmd_reset {
1187 my $target = shift || $_revision or die "SVN revision required\n";
1188 $target = $1 if $target =~ /^r(\d+)$/;
1189 $target =~ /^\d+$/ or die "Numeric SVN revision expected\n";
1190 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
1191 unless ($gs) {
1192 die "Unable to determine upstream SVN information from ".
1193 "history\n";
1195 my ($r, $c) = $gs->find_rev_before($target, not $_fetch_parent);
1196 die "Cannot find SVN revision $target\n" unless defined($c);
1197 $gs->rev_map_set($r, $c, 'reset', $uuid);
1198 print "r$r = $c ($gs->{ref_id})\n";
1201 sub cmd_gc {
1202 if (!$can_compress) {
1203 warn "Compress::Zlib could not be found; unhandled.log " .
1204 "files will not be compressed.\n";
1206 find({ wanted => \&gc_directory, no_chdir => 1}, "$ENV{GIT_DIR}/svn");
1209 ########################### utility functions #########################
1211 sub rebase_cmd {
1212 my @cmd = qw/rebase/;
1213 push @cmd, '-v' if $_verbose;
1214 push @cmd, qw/--merge/ if $_merge;
1215 push @cmd, "--strategy=$_strategy" if $_strategy;
1216 @cmd;
1219 sub post_fetch_checkout {
1220 return if $_no_checkout;
1221 my $gs = $Git::SVN::_head or return;
1222 return if verify_ref('refs/heads/master^0');
1224 # look for "trunk" ref if it exists
1225 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
1226 my $fetch = $remote->{fetch};
1227 if ($fetch) {
1228 foreach my $p (keys %$fetch) {
1229 basename($fetch->{$p}) eq 'trunk' or next;
1230 $gs = Git::SVN->new($fetch->{$p}, $gs->{repo_id}, $p);
1231 last;
1235 my $valid_head = verify_ref('HEAD^0');
1236 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1237 return if ($valid_head || !verify_ref('HEAD^0'));
1239 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1240 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1241 return if -f $index;
1243 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1244 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1245 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1246 print STDERR "Checked out HEAD:\n ",
1247 $gs->full_url, " r", $gs->last_rev, "\n";
1248 $gs->mkemptydirs($gs->last_rev);
1251 sub complete_svn_url {
1252 my ($url, $path) = @_;
1253 $path =~ s#/+$##;
1254 if ($path !~ m#^[a-z\+]+://#) {
1255 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1256 fatal("E: '$path' is not a complete URL ",
1257 "and a separate URL is not specified");
1259 return ($url, $path);
1261 return ($path, '');
1264 sub complete_url_ls_init {
1265 my ($ra, $repo_path, $switch, $pfx) = @_;
1266 unless ($repo_path) {
1267 print STDERR "W: $switch not specified\n";
1268 return;
1270 $repo_path =~ s#/+$##;
1271 if ($repo_path =~ m#^[a-z\+]+://#) {
1272 $ra = Git::SVN::Ra->new($repo_path);
1273 $repo_path = '';
1274 } else {
1275 $repo_path =~ s#^/+##;
1276 unless ($ra) {
1277 fatal("E: '$repo_path' is not a complete URL ",
1278 "and a separate URL is not specified");
1281 my $url = $ra->{url};
1282 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1283 my $k = "svn-remote.$gs->{repo_id}.url";
1284 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1285 if ($orig_url && ($orig_url ne $gs->{url})) {
1286 die "$k already set: $orig_url\n",
1287 "wanted to set to: $gs->{url}\n";
1289 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1290 my $remote_path = "$gs->{path}/$repo_path";
1291 $remote_path =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1292 $remote_path =~ s#/+#/#g;
1293 $remote_path =~ s#^/##g;
1294 $remote_path .= "/*" if $remote_path !~ /\*/;
1295 my ($n) = ($switch =~ /^--(\w+)/);
1296 if (length $pfx && $pfx !~ m#/$#) {
1297 die "--prefix='$pfx' must have a trailing slash '/'\n";
1299 command_noisy('config',
1300 '--add',
1301 "svn-remote.$gs->{repo_id}.$n",
1302 "$remote_path:refs/remotes/$pfx*" .
1303 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1306 sub verify_ref {
1307 my ($ref) = @_;
1308 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1309 { STDERR => 0 }); };
1312 sub get_tree_from_treeish {
1313 my ($treeish) = @_;
1314 # $treeish can be a symbolic ref, too:
1315 my $type = command_oneline(qw/cat-file -t/, $treeish);
1316 my $expected;
1317 while ($type eq 'tag') {
1318 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1320 if ($type eq 'commit') {
1321 $expected = (grep /^tree /, command(qw/cat-file commit/,
1322 $treeish))[0];
1323 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1324 die "Unable to get tree from $treeish\n" unless $expected;
1325 } elsif ($type eq 'tree') {
1326 $expected = $treeish;
1327 } else {
1328 die "$treeish is a $type, expected tree, tag or commit\n";
1330 return $expected;
1333 sub get_commit_entry {
1334 my ($treeish) = shift;
1335 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1336 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1337 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1338 open my $log_fh, '>', $commit_editmsg or croak $!;
1340 my $type = command_oneline(qw/cat-file -t/, $treeish);
1341 if ($type eq 'commit' || $type eq 'tag') {
1342 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1343 $type, $treeish);
1344 my $in_msg = 0;
1345 my $author;
1346 my $saw_from = 0;
1347 my $msgbuf = "";
1348 while (<$msg_fh>) {
1349 if (!$in_msg) {
1350 $in_msg = 1 if (/^\s*$/);
1351 $author = $1 if (/^author (.*>)/);
1352 } elsif (/^git-svn-id: /) {
1353 # skip this for now, we regenerate the
1354 # correct one on re-fetch anyways
1355 # TODO: set *:merge properties or like...
1356 } else {
1357 if (/^From:/ || /^Signed-off-by:/) {
1358 $saw_from = 1;
1360 $msgbuf .= $_;
1363 $msgbuf =~ s/\s+$//s;
1364 if ($Git::SVN::_add_author_from && defined($author)
1365 && !$saw_from) {
1366 $msgbuf .= "\n\nFrom: $author";
1368 print $log_fh $msgbuf or croak $!;
1369 command_close_pipe($msg_fh, $ctx);
1371 close $log_fh or croak $!;
1373 if ($_edit || ($type eq 'tree')) {
1374 chomp(my $editor = command_oneline(qw(var GIT_EDITOR)));
1375 system('sh', '-c', $editor.' "$@"', $editor, $commit_editmsg);
1377 rename $commit_editmsg, $commit_msg or croak $!;
1379 require Encode;
1380 # SVN requires messages to be UTF-8 when entering the repo
1381 local $/;
1382 open $log_fh, '<', $commit_msg or croak $!;
1383 binmode $log_fh;
1384 chomp($log_entry{log} = <$log_fh>);
1386 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1387 my $msg = $log_entry{log};
1389 eval { $msg = Encode::decode($enc, $msg, 1) };
1390 if ($@) {
1391 die "Could not decode as $enc:\n", $msg,
1392 "\nPerhaps you need to set i18n.commitencoding\n";
1395 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1396 die "Could not encode as UTF-8:\n$msg\n" if $@;
1398 $log_entry{log} = $msg;
1400 close $log_fh or croak $!;
1402 unlink $commit_msg;
1403 \%log_entry;
1406 sub s_to_file {
1407 my ($str, $file, $mode) = @_;
1408 open my $fd,'>',$file or croak $!;
1409 print $fd $str,"\n" or croak $!;
1410 close $fd or croak $!;
1411 chmod ($mode &~ umask, $file) if (defined $mode);
1414 sub file_to_s {
1415 my $file = shift;
1416 open my $fd,'<',$file or croak "$!: file: $file\n";
1417 local $/;
1418 my $ret = <$fd>;
1419 close $fd or croak $!;
1420 $ret =~ s/\s*$//s;
1421 return $ret;
1424 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1425 sub load_authors {
1426 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1427 my $log = $cmd eq 'log';
1428 while (<$authors>) {
1429 chomp;
1430 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1431 my ($user, $name, $email) = ($1, $2, $3);
1432 if ($log) {
1433 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1434 } else {
1435 $users{$user} = [$name, $email];
1438 close $authors or croak $!;
1441 # convert GetOpt::Long specs for use by git-config
1442 sub read_git_config {
1443 my $opts = shift;
1444 my @config_only;
1445 foreach my $o (keys %$opts) {
1446 # if we have mixedCase and a long option-only, then
1447 # it's a config-only variable that we don't need for
1448 # the command-line.
1449 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1450 my $v = $opts->{$o};
1451 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1452 $key =~ s/-//g;
1453 my $arg = 'git config';
1454 $arg .= ' --int' if ($o =~ /[:=]i$/);
1455 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1456 if (ref $v eq 'ARRAY') {
1457 chomp(my @tmp = `$arg --get-all svn.$key`);
1458 @$v = @tmp if @tmp;
1459 } else {
1460 chomp(my $tmp = `$arg --get svn.$key`);
1461 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1462 $$v = $tmp;
1466 delete @$opts{@config_only} if @config_only;
1469 sub extract_metadata {
1470 my $id = shift or return (undef, undef, undef);
1471 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1472 \s([a-f\d\-]+)$/ix);
1473 if (!defined $rev || !$uuid || !$url) {
1474 # some of the original repositories I made had
1475 # identifiers like this:
1476 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/i);
1478 return ($url, $rev, $uuid);
1481 sub cmt_metadata {
1482 return extract_metadata((grep(/^git-svn-id: /,
1483 command(qw/cat-file commit/, shift)))[-1]);
1486 sub cmt_sha2rev_batch {
1487 my %s2r;
1488 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1489 my $list = shift;
1491 foreach my $sha (@{$list}) {
1492 my $first = 1;
1493 my $size = 0;
1494 print $out $sha, "\n";
1496 while (my $line = <$in>) {
1497 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1498 last;
1499 } elsif ($first &&
1500 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1501 $first = 0;
1502 $size = $1;
1503 next;
1504 } elsif ($line =~ /^(git-svn-id: )/) {
1505 my (undef, $rev, undef) =
1506 extract_metadata($line);
1507 $s2r{$sha} = $rev;
1510 $size -= length($line);
1511 last if ($size == 0);
1515 command_close_bidi_pipe($pid, $in, $out, $ctx);
1517 return \%s2r;
1520 sub working_head_info {
1521 my ($head, $refs) = @_;
1522 my @args = qw/log --no-color --no-decorate --first-parent
1523 --pretty=medium/;
1524 my ($fh, $ctx) = command_output_pipe(@args, $head);
1525 my $hash;
1526 my %max;
1527 while (<$fh>) {
1528 if ( m{^commit ($::sha1)$} ) {
1529 unshift @$refs, $hash if $hash and $refs;
1530 $hash = $1;
1531 next;
1533 next unless s{^\s*(git-svn-id:)}{$1};
1534 my ($url, $rev, $uuid) = extract_metadata($_);
1535 if (defined $url && defined $rev) {
1536 next if $max{$url} and $max{$url} < $rev;
1537 if (my $gs = Git::SVN->find_by_url($url)) {
1538 my $c = $gs->rev_map_get($rev, $uuid);
1539 if ($c && $c eq $hash) {
1540 close $fh; # break the pipe
1541 return ($url, $rev, $uuid, $gs);
1542 } else {
1543 $max{$url} ||= $gs->rev_map_max;
1548 command_close_pipe($fh, $ctx);
1549 (undef, undef, undef, undef);
1552 sub read_commit_parents {
1553 my ($parents, $c) = @_;
1554 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1555 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1556 @{$parents->{$c}} = split(/ /, $p);
1559 sub linearize_history {
1560 my ($gs, $refs) = @_;
1561 my %parents;
1562 foreach my $c (@$refs) {
1563 read_commit_parents(\%parents, $c);
1566 my @linear_refs;
1567 my %skip = ();
1568 my $last_svn_commit = $gs->last_commit;
1569 foreach my $c (reverse @$refs) {
1570 next if $c eq $last_svn_commit;
1571 last if $skip{$c};
1573 unshift @linear_refs, $c;
1574 $skip{$c} = 1;
1576 # we only want the first parent to diff against for linear
1577 # history, we save the rest to inject when we finalize the
1578 # svn commit
1579 my $fp_a = verify_ref("$c~1");
1580 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1581 if (!$fp_a || !$fp_b) {
1582 die "Commit $c\n",
1583 "has no parent commit, and therefore ",
1584 "nothing to diff against.\n",
1585 "You should be working from a repository ",
1586 "originally created by git-svn\n";
1588 if ($fp_a ne $fp_b) {
1589 die "$c~1 = $fp_a, however parsing commit $c ",
1590 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1593 foreach my $p (@{$parents{$c}}) {
1594 $skip{$p} = 1;
1597 (\@linear_refs, \%parents);
1600 sub find_file_type_and_diff_status {
1601 my ($path) = @_;
1602 return ('dir', '') if $path eq '';
1604 my $diff_output =
1605 command_oneline(qw(diff --cached --name-status --), $path) || "";
1606 my $diff_status = (split(' ', $diff_output))[0] || "";
1608 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1610 return (undef, undef) if !$diff_status && !$ls_tree;
1612 if ($diff_status eq "A") {
1613 return ("link", $diff_status) if -l $path;
1614 return ("dir", $diff_status) if -d $path;
1615 return ("file", $diff_status);
1618 my $mode = (split(' ', $ls_tree))[0] || "";
1620 return ("link", $diff_status) if $mode eq "120000";
1621 return ("dir", $diff_status) if $mode eq "040000";
1622 return ("file", $diff_status);
1625 sub md5sum {
1626 my $arg = shift;
1627 my $ref = ref $arg;
1628 my $md5 = Digest::MD5->new();
1629 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1630 $md5->addfile($arg) or croak $!;
1631 } elsif ($ref eq 'SCALAR') {
1632 $md5->add($$arg) or croak $!;
1633 } elsif (!$ref) {
1634 $md5->add($arg) or croak $!;
1635 } else {
1636 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1638 return $md5->hexdigest();
1641 sub gc_directory {
1642 if ($can_compress && -f $_ && basename($_) eq "unhandled.log") {
1643 my $out_filename = $_ . ".gz";
1644 open my $in_fh, "<", $_ or die "Unable to open $_: $!\n";
1645 binmode $in_fh;
1646 my $gz = Compress::Zlib::gzopen($out_filename, "ab") or
1647 die "Unable to open $out_filename: $!\n";
1649 my $res;
1650 while ($res = sysread($in_fh, my $str, 1024)) {
1651 $gz->gzwrite($str) or
1652 die "Unable to write: ".$gz->gzerror()."!\n";
1654 unlink $_ or die "unlink $File::Find::name: $!\n";
1655 } elsif (-f $_ && basename($_) eq "index") {
1656 unlink $_ or die "unlink $_: $!\n";
1660 package Git::SVN;
1661 use strict;
1662 use warnings;
1663 use Fcntl qw/:DEFAULT :seek/;
1664 use constant rev_map_fmt => 'NH40';
1665 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1666 $_repack $_repack_flags $_use_svm_props $_head
1667 $_use_svnsync_props $no_reuse_existing $_minimize_url
1668 $_use_log_author $_add_author_from $_localtime/;
1669 use Carp qw/croak/;
1670 use File::Path qw/mkpath/;
1671 use File::Copy qw/copy/;
1672 use IPC::Open3;
1673 use Memoize; # core since 5.8.0, Jul 2002
1674 use Memoize::Storable;
1676 my ($_gc_nr, $_gc_period);
1678 # properties that we do not log:
1679 my %SKIP_PROP;
1680 BEGIN {
1681 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1682 svn:special svn:executable
1683 svn:entry:committed-rev
1684 svn:entry:last-author
1685 svn:entry:uuid
1686 svn:entry:committed-date/;
1688 # some options are read globally, but can be overridden locally
1689 # per [svn-remote "..."] section. Command-line options will *NOT*
1690 # override options set in an [svn-remote "..."] section
1691 no strict 'refs';
1692 for my $option (qw/follow_parent no_metadata use_svm_props
1693 use_svnsync_props/) {
1694 my $key = $option;
1695 $key =~ tr/_//d;
1696 my $prop = "-$option";
1697 *$option = sub {
1698 my ($self) = @_;
1699 return $self->{$prop} if exists $self->{$prop};
1700 my $k = "svn-remote.$self->{repo_id}.$key";
1701 eval { command_oneline(qw/config --get/, $k) };
1702 if ($@) {
1703 $self->{$prop} = ${"Git::SVN::_$option"};
1704 } else {
1705 my $v = command_oneline(qw/config --bool/,$k);
1706 $self->{$prop} = $v eq 'false' ? 0 : 1;
1708 return $self->{$prop};
1714 my (%LOCKFILES, %INDEX_FILES);
1715 END {
1716 unlink keys %LOCKFILES if %LOCKFILES;
1717 unlink keys %INDEX_FILES if %INDEX_FILES;
1720 sub resolve_local_globs {
1721 my ($url, $fetch, $glob_spec) = @_;
1722 return unless defined $glob_spec;
1723 my $ref = $glob_spec->{ref};
1724 my $path = $glob_spec->{path};
1725 foreach (command(qw#for-each-ref --format=%(refname) refs/#)) {
1726 next unless m#^$ref->{regex}$#;
1727 my $p = $1;
1728 my $pathname = desanitize_refname($path->full_path($p));
1729 my $refname = desanitize_refname($ref->full_path($p));
1730 if (my $existing = $fetch->{$pathname}) {
1731 if ($existing ne $refname) {
1732 die "Refspec conflict:\n",
1733 "existing: $existing\n",
1734 " globbed: $refname\n";
1736 my $u = (::cmt_metadata("$refname"))[0];
1737 $u =~ s!^\Q$url\E(/|$)!! or die
1738 "$refname: '$url' not found in '$u'\n";
1739 if ($pathname ne $u) {
1740 warn "W: Refspec glob conflict ",
1741 "(ref: $refname):\n",
1742 "expected path: $pathname\n",
1743 " real path: $u\n",
1744 "Continuing ahead with $u\n";
1745 next;
1747 } else {
1748 $fetch->{$pathname} = $refname;
1753 sub parse_revision_argument {
1754 my ($base, $head) = @_;
1755 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1756 return ($base, $head);
1758 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1759 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1760 return ($head, $head) if ($::_revision eq 'HEAD');
1761 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1762 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1763 die "revision argument: $::_revision not understood by git-svn\n";
1766 sub fetch_all {
1767 my ($repo_id, $remotes) = @_;
1768 if (ref $repo_id) {
1769 my $gs = $repo_id;
1770 $repo_id = undef;
1771 $repo_id = $gs->{repo_id};
1773 $remotes ||= read_all_remotes();
1774 my $remote = $remotes->{$repo_id} or
1775 die "[svn-remote \"$repo_id\"] unknown\n";
1776 my $fetch = $remote->{fetch};
1777 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1778 my (@gs, @globs);
1779 my $ra = Git::SVN::Ra->new($url);
1780 my $uuid = $ra->get_uuid;
1781 my $head = $ra->get_latest_revnum;
1783 # ignore errors, $head revision may not even exist anymore
1784 eval { $ra->get_log("", $head, 0, 1, 0, 1, sub { $head = $_[1] }) };
1785 warn "W: $@\n" if $@;
1787 my $base = defined $fetch ? $head : 0;
1789 # read the max revs for wildcard expansion (branches/*, tags/*)
1790 foreach my $t (qw/branches tags/) {
1791 defined $remote->{$t} or next;
1792 push @globs, @{$remote->{$t}};
1794 my $max_rev = eval { tmp_config(qw/--int --get/,
1795 "svn-remote.$repo_id.${t}-maxRev") };
1796 if (defined $max_rev && ($max_rev < $base)) {
1797 $base = $max_rev;
1798 } elsif (!defined $max_rev) {
1799 $base = 0;
1803 if ($fetch) {
1804 foreach my $p (sort keys %$fetch) {
1805 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1806 my $lr = $gs->rev_map_max;
1807 if (defined $lr) {
1808 $base = $lr if ($lr < $base);
1810 push @gs, $gs;
1814 ($base, $head) = parse_revision_argument($base, $head);
1815 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1818 sub read_all_remotes {
1819 my $r = {};
1820 my $use_svm_props = eval { command_oneline(qw/config --bool
1821 svn.useSvmProps/) };
1822 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1823 my $svn_refspec = qr{\s*(.*?)\s*:\s*(.+?)\s*};
1824 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1825 if (m!^(.+)\.fetch=$svn_refspec$!) {
1826 my ($remote, $local_ref, $remote_ref) = ($1, $2, $3);
1827 die("svn-remote.$remote: remote ref '$remote_ref' "
1828 . "must start with 'refs/'\n")
1829 unless $remote_ref =~ m{^refs/};
1830 $local_ref = uri_decode($local_ref);
1831 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1832 $r->{$remote}->{svm} = {} if $use_svm_props;
1833 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1834 $r->{$1}->{svm} = {};
1835 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1836 $r->{$1}->{url} = $2;
1837 } elsif (m!^(.+)\.pushurl=\s*(.*)\s*$!) {
1838 $r->{$1}->{pushurl} = $2;
1839 } elsif (m!^(.+)\.(branches|tags)=$svn_refspec$!) {
1840 my ($remote, $t, $local_ref, $remote_ref) =
1841 ($1, $2, $3, $4);
1842 die("svn-remote.$remote: remote ref '$remote_ref' ($t) "
1843 . "must start with 'refs/'\n")
1844 unless $remote_ref =~ m{^refs/};
1845 $local_ref = uri_decode($local_ref);
1846 my $rs = {
1847 t => $t,
1848 remote => $remote,
1849 path => Git::SVN::GlobSpec->new($local_ref, 1),
1850 ref => Git::SVN::GlobSpec->new($remote_ref, 0) };
1851 if (length($rs->{ref}->{right}) != 0) {
1852 die "The '*' glob character must be the last ",
1853 "character of '$remote_ref'\n";
1855 push @{ $r->{$remote}->{$t} }, $rs;
1859 map {
1860 if (defined $r->{$_}->{svm}) {
1861 my $svm;
1862 eval {
1863 my $section = "svn-remote.$_";
1864 $svm = {
1865 source => tmp_config('--get',
1866 "$section.svm-source"),
1867 replace => tmp_config('--get',
1868 "$section.svm-replace"),
1871 $r->{$_}->{svm} = $svm;
1873 } keys %$r;
1878 sub init_vars {
1879 $_gc_nr = $_gc_period = 1000;
1880 if (defined $_repack || defined $_repack_flags) {
1881 warn "Repack options are obsolete; they have no effect.\n";
1885 sub verify_remotes_sanity {
1886 return unless -d $ENV{GIT_DIR};
1887 my %seen;
1888 foreach (command(qw/config -l/)) {
1889 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1890 if ($seen{$1}) {
1891 die "Remote ref refs/remote/$1 is tracked by",
1892 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1893 "Please resolve this ambiguity in ",
1894 "your git configuration file before ",
1895 "continuing\n";
1897 $seen{$1} = $_;
1902 sub find_existing_remote {
1903 my ($url, $remotes) = @_;
1904 return undef if $no_reuse_existing;
1905 my $existing;
1906 foreach my $repo_id (keys %$remotes) {
1907 my $u = $remotes->{$repo_id}->{url} or next;
1908 next if $u ne $url;
1909 $existing = $repo_id;
1910 last;
1912 $existing;
1915 sub init_remote_config {
1916 my ($self, $url, $no_write) = @_;
1917 $url =~ s!/+$!!; # strip trailing slash
1918 my $r = read_all_remotes();
1919 my $existing = find_existing_remote($url, $r);
1920 if ($existing) {
1921 unless ($no_write) {
1922 print STDERR "Using existing ",
1923 "[svn-remote \"$existing\"]\n";
1925 $self->{repo_id} = $existing;
1926 } elsif ($_minimize_url) {
1927 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1928 $existing = find_existing_remote($min_url, $r);
1929 if ($existing) {
1930 unless ($no_write) {
1931 print STDERR "Using existing ",
1932 "[svn-remote \"$existing\"]\n";
1934 $self->{repo_id} = $existing;
1936 if ($min_url ne $url) {
1937 unless ($no_write) {
1938 print STDERR "Using higher level of URL: ",
1939 "$url => $min_url\n";
1941 my $old_path = $self->{path};
1942 $self->{path} = $url;
1943 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1944 if (length $old_path) {
1945 $self->{path} .= "/$old_path";
1947 $url = $min_url;
1950 my $orig_url;
1951 if (!$existing) {
1952 # verify that we aren't overwriting anything:
1953 $orig_url = eval {
1954 command_oneline('config', '--get',
1955 "svn-remote.$self->{repo_id}.url")
1957 if ($orig_url && ($orig_url ne $url)) {
1958 die "svn-remote.$self->{repo_id}.url already set: ",
1959 "$orig_url\nwanted to set to: $url\n";
1962 my ($xrepo_id, $xpath) = find_ref($self->refname);
1963 if (!$no_write && defined $xpath) {
1964 die "svn-remote.$xrepo_id.fetch already set to track ",
1965 "$xpath:", $self->refname, "\n";
1967 unless ($no_write) {
1968 command_noisy('config',
1969 "svn-remote.$self->{repo_id}.url", $url);
1970 $self->{path} =~ s{^/}{};
1971 $self->{path} =~ s{%([0-9A-F]{2})}{chr hex($1)}ieg;
1972 command_noisy('config', '--add',
1973 "svn-remote.$self->{repo_id}.fetch",
1974 "$self->{path}:".$self->refname);
1976 $self->{url} = $url;
1979 sub find_by_url { # repos_root and, path are optional
1980 my ($class, $full_url, $repos_root, $path) = @_;
1982 return undef unless defined $full_url;
1983 remove_username($full_url);
1984 remove_username($repos_root) if defined $repos_root;
1985 my $remotes = read_all_remotes();
1986 if (defined $full_url && defined $repos_root && !defined $path) {
1987 $path = $full_url;
1988 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1990 foreach my $repo_id (keys %$remotes) {
1991 my $u = $remotes->{$repo_id}->{url} or next;
1992 remove_username($u);
1993 next if defined $repos_root && $repos_root ne $u;
1995 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1996 foreach my $t (qw/branches tags/) {
1997 foreach my $globspec (@{$remotes->{$repo_id}->{$t}}) {
1998 resolve_local_globs($u, $fetch, $globspec);
2001 my $p = $path;
2002 my $rwr = rewrite_root({repo_id => $repo_id});
2003 my $svm = $remotes->{$repo_id}->{svm}
2004 if defined $remotes->{$repo_id}->{svm};
2005 unless (defined $p) {
2006 $p = $full_url;
2007 my $z = $u;
2008 my $prefix = '';
2009 if ($rwr) {
2010 $z = $rwr;
2011 remove_username($z);
2012 } elsif (defined $svm) {
2013 $z = $svm->{source};
2014 $prefix = $svm->{replace};
2015 $prefix =~ s#^\Q$u\E(?:/|$)##;
2016 $prefix =~ s#/$##;
2018 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
2020 foreach my $f (keys %$fetch) {
2021 next if $f ne $p;
2022 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
2025 undef;
2028 sub init {
2029 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
2030 my $self = _new($class, $repo_id, $ref_id, $path);
2031 if (defined $url) {
2032 $self->init_remote_config($url, $no_write);
2034 $self;
2037 sub find_ref {
2038 my ($ref_id) = @_;
2039 foreach (command(qw/config -l/)) {
2040 next unless m!^svn-remote\.(.+)\.fetch=
2041 \s*(.*?)\s*:\s*(.+?)\s*$!x;
2042 my ($repo_id, $path, $ref) = ($1, $2, $3);
2043 if ($ref eq $ref_id) {
2044 $path = '' if ($path =~ m#^\./?#);
2045 return ($repo_id, $path);
2048 (undef, undef, undef);
2051 sub new {
2052 my ($class, $ref_id, $repo_id, $path) = @_;
2053 if (defined $ref_id && !defined $repo_id && !defined $path) {
2054 ($repo_id, $path) = find_ref($ref_id);
2055 if (!defined $repo_id) {
2056 die "Could not find a \"svn-remote.*.fetch\" key ",
2057 "in the repository configuration matching: ",
2058 "$ref_id\n";
2061 my $self = _new($class, $repo_id, $ref_id, $path);
2062 if (!defined $self->{path} || !length $self->{path}) {
2063 my $fetch = command_oneline('config', '--get',
2064 "svn-remote.$repo_id.fetch",
2065 ":$ref_id\$") or
2066 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
2067 "\":$ref_id\$\" in config\n";
2068 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
2070 $self->{path} =~ s{/+}{/}g;
2071 $self->{path} =~ s{\A/}{};
2072 $self->{path} =~ s{/\z}{};
2073 $self->{url} = command_oneline('config', '--get',
2074 "svn-remote.$repo_id.url") or
2075 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
2076 $self->{pushurl} = eval { command_oneline('config', '--get',
2077 "svn-remote.$repo_id.pushurl") };
2078 $self->rebuild;
2079 $self;
2082 sub refname {
2083 my ($refname) = $_[0]->{ref_id} ;
2085 # It cannot end with a slash /, we'll throw up on this because
2086 # SVN can't have directories with a slash in their name, either:
2087 if ($refname =~ m{/$}) {
2088 die "ref: '$refname' ends with a trailing slash, this is ",
2089 "not permitted by git nor Subversion\n";
2092 # It cannot have ASCII control character space, tilde ~, caret ^,
2093 # colon :, question-mark ?, asterisk *, space, or open bracket [
2094 # anywhere.
2096 # Additionally, % must be escaped because it is used for escaping
2097 # and we want our escaped refname to be reversible
2098 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
2100 # no slash-separated component can begin with a dot .
2101 # /.* becomes /%2E*
2102 $refname =~ s{/\.}{/%2E}g;
2104 # It cannot have two consecutive dots .. anywhere
2105 # .. becomes %2E%2E
2106 $refname =~ s{\.\.}{%2E%2E}g;
2108 # trailing dots and .lock are not allowed
2109 # .$ becomes %2E and .lock becomes %2Elock
2110 $refname =~ s{\.(?=$|lock$)}{%2E};
2112 # the sequence @{ is used to access the reflog
2113 # @{ becomes %40{
2114 $refname =~ s{\@\{}{%40\{}g;
2116 return $refname;
2119 sub desanitize_refname {
2120 my ($refname) = @_;
2121 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
2122 return $refname;
2125 sub svm_uuid {
2126 my ($self) = @_;
2127 return $self->{svm}->{uuid} if $self->svm;
2128 $self->ra;
2129 unless ($self->{svm}) {
2130 die "SVM UUID not cached, and reading remotely failed\n";
2132 $self->{svm}->{uuid};
2135 sub svm {
2136 my ($self) = @_;
2137 return $self->{svm} if $self->{svm};
2138 my $svm;
2139 # see if we have it in our config, first:
2140 eval {
2141 my $section = "svn-remote.$self->{repo_id}";
2142 $svm = {
2143 source => tmp_config('--get', "$section.svm-source"),
2144 uuid => tmp_config('--get', "$section.svm-uuid"),
2145 replace => tmp_config('--get', "$section.svm-replace"),
2148 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
2149 $self->{svm} = $svm;
2151 $self->{svm};
2154 sub _set_svm_vars {
2155 my ($self, $ra) = @_;
2156 return $ra if $self->svm;
2158 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
2159 "(svm:source, svm:uuid) ",
2160 "from the following URLs:\n" );
2161 sub read_svm_props {
2162 my ($self, $ra, $path, $r) = @_;
2163 my $props = ($ra->get_dir($path, $r))[2];
2164 my $src = $props->{'svm:source'};
2165 my $uuid = $props->{'svm:uuid'};
2166 return undef if (!$src || !$uuid);
2168 chomp($src, $uuid);
2170 $uuid =~ m{^[0-9a-f\-]{30,}$}i
2171 or die "doesn't look right - svm:uuid is '$uuid'\n";
2173 # the '!' is used to mark the repos_root!/relative/path
2174 $src =~ s{/?!/?}{/};
2175 $src =~ s{/+$}{}; # no trailing slashes please
2176 # username is of no interest
2177 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
2179 my $replace = $ra->{url};
2180 $replace .= "/$path" if length $path;
2182 my $section = "svn-remote.$self->{repo_id}";
2183 tmp_config("$section.svm-source", $src);
2184 tmp_config("$section.svm-replace", $replace);
2185 tmp_config("$section.svm-uuid", $uuid);
2186 $self->{svm} = {
2187 source => $src,
2188 uuid => $uuid,
2189 replace => $replace
2193 my $r = $ra->get_latest_revnum;
2194 my $path = $self->{path};
2195 my %tried;
2196 while (length $path) {
2197 unless ($tried{"$self->{url}/$path"}) {
2198 return $ra if $self->read_svm_props($ra, $path, $r);
2199 $tried{"$self->{url}/$path"} = 1;
2201 $path =~ s#/?[^/]+$##;
2203 die "Path: '$path' should be ''\n" if $path ne '';
2204 return $ra if $self->read_svm_props($ra, $path, $r);
2205 $tried{"$self->{url}/$path"} = 1;
2207 if ($ra->{repos_root} eq $self->{url}) {
2208 die @err, (map { " $_\n" } keys %tried), "\n";
2211 # nope, make sure we're connected to the repository root:
2212 my $ok;
2213 my @tried_b;
2214 $path = $ra->{svn_path};
2215 $ra = Git::SVN::Ra->new($ra->{repos_root});
2216 while (length $path) {
2217 unless ($tried{"$ra->{url}/$path"}) {
2218 $ok = $self->read_svm_props($ra, $path, $r);
2219 last if $ok;
2220 $tried{"$ra->{url}/$path"} = 1;
2222 $path =~ s#/?[^/]+$##;
2224 die "Path: '$path' should be ''\n" if $path ne '';
2225 $ok ||= $self->read_svm_props($ra, $path, $r);
2226 $tried{"$ra->{url}/$path"} = 1;
2227 if (!$ok) {
2228 die @err, (map { " $_\n" } keys %tried), "\n";
2230 Git::SVN::Ra->new($self->{url});
2233 sub svnsync {
2234 my ($self) = @_;
2235 return $self->{svnsync} if $self->{svnsync};
2237 if ($self->no_metadata) {
2238 die "Can't have both 'noMetadata' and ",
2239 "'useSvnsyncProps' options set!\n";
2241 if ($self->rewrite_root) {
2242 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2243 "options set!\n";
2245 if ($self->rewrite_uuid) {
2246 die "Can't have both 'useSvnsyncProps' and 'rewriteUUID' ",
2247 "options set!\n";
2250 my $svnsync;
2251 # see if we have it in our config, first:
2252 eval {
2253 my $section = "svn-remote.$self->{repo_id}";
2255 my $url = tmp_config('--get', "$section.svnsync-url");
2256 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2257 die "doesn't look right - svn:sync-from-url is '$url'\n";
2259 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2260 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2261 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2263 $svnsync = { url => $url, uuid => $uuid }
2265 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2266 return $self->{svnsync} = $svnsync;
2269 my $err = "useSvnsyncProps set, but failed to read " .
2270 "svnsync property: svn:sync-from-";
2271 my $rp = $self->ra->rev_proplist(0);
2273 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2274 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2275 die "doesn't look right - svn:sync-from-url is '$url'\n";
2277 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2278 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}i) or
2279 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2281 my $section = "svn-remote.$self->{repo_id}";
2282 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2283 tmp_config('--add', "$section.svnsync-url", $url);
2284 return $self->{svnsync} = { url => $url, uuid => $uuid };
2287 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2288 # remote lookup (useful for 'git svn log').
2289 sub ra_uuid {
2290 my ($self) = @_;
2291 unless ($self->{ra_uuid}) {
2292 my $key = "svn-remote.$self->{repo_id}.uuid";
2293 my $uuid = eval { tmp_config('--get', $key) };
2294 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/i) {
2295 $self->{ra_uuid} = $uuid;
2296 } else {
2297 die "ra_uuid called without URL\n" unless $self->{url};
2298 $self->{ra_uuid} = $self->ra->get_uuid;
2299 tmp_config('--add', $key, $self->{ra_uuid});
2302 $self->{ra_uuid};
2305 sub _set_repos_root {
2306 my ($self, $repos_root) = @_;
2307 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2308 $repos_root ||= $self->ra->{repos_root};
2309 tmp_config($k, $repos_root);
2310 $repos_root;
2313 sub repos_root {
2314 my ($self) = @_;
2315 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2316 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2319 sub ra {
2320 my ($self) = shift;
2321 my $ra = Git::SVN::Ra->new($self->{url});
2322 $self->_set_repos_root($ra->{repos_root});
2323 if ($self->use_svm_props && !$self->{svm}) {
2324 if ($self->no_metadata) {
2325 die "Can't have both 'noMetadata' and ",
2326 "'useSvmProps' options set!\n";
2327 } elsif ($self->use_svnsync_props) {
2328 die "Can't have both 'useSvnsyncProps' and ",
2329 "'useSvmProps' options set!\n";
2331 $ra = $self->_set_svm_vars($ra);
2332 $self->{-want_revprops} = 1;
2334 $ra;
2337 # prop_walk(PATH, REV, SUB)
2338 # -------------------------
2339 # Recursively traverse PATH at revision REV and invoke SUB for each
2340 # directory that contains a SVN property. SUB will be invoked as
2341 # follows: &SUB(gs, path, props); where `gs' is this instance of
2342 # Git::SVN, `path' the path to the directory where the properties
2343 # `props' were found. The `path' will be relative to point of checkout,
2344 # that is, if url://repo/trunk is the current Git branch, and that
2345 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2346 # as `path' (note the trailing `/').
2347 sub prop_walk {
2348 my ($self, $path, $rev, $sub) = @_;
2350 $path =~ s#^/##;
2351 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2352 $path =~ s#^/*#/#g;
2353 my $p = $path;
2354 # Strip the irrelevant part of the path.
2355 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2356 # Ensure the path is terminated by a `/'.
2357 $p =~ s#/*$#/#;
2359 # The properties contain all the internal SVN stuff nobody
2360 # (usually) cares about.
2361 my $interesting_props = 0;
2362 foreach (keys %{$props}) {
2363 # If it doesn't start with `svn:', it must be a
2364 # user-defined property.
2365 ++$interesting_props and next if $_ !~ /^svn:/;
2366 # FIXME: Fragile, if SVN adds new public properties,
2367 # this needs to be updated.
2368 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2369 |eol-style|mime-type
2370 |externals|needs-lock)$/x;
2372 &$sub($self, $p, $props) if $interesting_props;
2374 foreach (sort keys %$dirent) {
2375 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2376 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2380 sub last_rev { ($_[0]->last_rev_commit)[0] }
2381 sub last_commit { ($_[0]->last_rev_commit)[1] }
2383 # returns the newest SVN revision number and newest commit SHA1
2384 sub last_rev_commit {
2385 my ($self) = @_;
2386 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2387 return ($self->{last_rev}, $self->{last_commit});
2389 my $c = ::verify_ref($self->refname.'^0');
2390 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2391 my $rev = (::cmt_metadata($c))[1];
2392 if (defined $rev) {
2393 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2394 return ($rev, $c);
2397 my $map_path = $self->map_path;
2398 unless (-e $map_path) {
2399 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2400 return (undef, undef);
2402 my ($rev, $commit) = $self->rev_map_max(1);
2403 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2404 return ($rev, $commit);
2407 sub get_fetch_range {
2408 my ($self, $min, $max) = @_;
2409 $max ||= $self->ra->get_latest_revnum;
2410 $min ||= $self->rev_map_max;
2411 (++$min, $max);
2414 sub tmp_config {
2415 my (@args) = @_;
2416 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2417 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2418 if (! -f $config && -f $old_def_config) {
2419 rename $old_def_config, $config or
2420 die "Failed rename $old_def_config => $config: $!\n";
2422 my $old_config = $ENV{GIT_CONFIG};
2423 $ENV{GIT_CONFIG} = $config;
2424 $@ = undef;
2425 my @ret = eval {
2426 unless (-f $config) {
2427 mkfile($config);
2428 open my $fh, '>', $config or
2429 die "Can't open $config: $!\n";
2430 print $fh "; This file is used internally by ",
2431 "git-svn\n" or die
2432 "Couldn't write to $config: $!\n";
2433 print $fh "; You should not have to edit it\n" or
2434 die "Couldn't write to $config: $!\n";
2435 close $fh or die "Couldn't close $config: $!\n";
2437 command('config', @args);
2439 my $err = $@;
2440 if (defined $old_config) {
2441 $ENV{GIT_CONFIG} = $old_config;
2442 } else {
2443 delete $ENV{GIT_CONFIG};
2445 die $err if $err;
2446 wantarray ? @ret : $ret[0];
2449 sub tmp_index_do {
2450 my ($self, $sub) = @_;
2451 my $old_index = $ENV{GIT_INDEX_FILE};
2452 $ENV{GIT_INDEX_FILE} = $self->{index};
2453 $@ = undef;
2454 my @ret = eval {
2455 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2456 mkpath([$dir]) unless -d $dir;
2457 &$sub;
2459 my $err = $@;
2460 if (defined $old_index) {
2461 $ENV{GIT_INDEX_FILE} = $old_index;
2462 } else {
2463 delete $ENV{GIT_INDEX_FILE};
2465 die $err if $err;
2466 wantarray ? @ret : $ret[0];
2469 sub assert_index_clean {
2470 my ($self, $treeish) = @_;
2472 $self->tmp_index_do(sub {
2473 command_noisy('read-tree', $treeish) unless -e $self->{index};
2474 my $x = command_oneline('write-tree');
2475 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2476 /^tree ($::sha1)/mo);
2477 return if $y eq $x;
2479 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2480 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2481 command_noisy('read-tree', $treeish);
2482 $x = command_oneline('write-tree');
2483 if ($y ne $x) {
2484 ::fatal "trees ($treeish) $y != $x\n",
2485 "Something is seriously wrong...";
2490 sub get_commit_parents {
2491 my ($self, $log_entry) = @_;
2492 my (%seen, @ret, @tmp);
2493 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2494 if (my $ip = $self->{inject_parents}) {
2495 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2496 push @tmp, $commit;
2499 if (my $cur = ::verify_ref($self->refname.'^0')) {
2500 push @tmp, $cur;
2502 if (my $ipd = $self->{inject_parents_dcommit}) {
2503 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2504 push @tmp, @$commit;
2507 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2508 while (my $p = shift @tmp) {
2509 next if $seen{$p};
2510 $seen{$p} = 1;
2511 push @ret, $p;
2513 @ret;
2516 sub rewrite_root {
2517 my ($self) = @_;
2518 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2519 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2520 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2521 if ($rwr) {
2522 $rwr =~ s#/+$##;
2523 if ($rwr !~ m#^[a-z\+]+://#) {
2524 die "$rwr is not a valid URL (key: $k)\n";
2527 $self->{-rewrite_root} = $rwr;
2530 sub rewrite_uuid {
2531 my ($self) = @_;
2532 return $self->{-rewrite_uuid} if exists $self->{-rewrite_uuid};
2533 my $k = "svn-remote.$self->{repo_id}.rewriteUUID";
2534 my $rwid = eval { command_oneline(qw/config --get/, $k) };
2535 if ($rwid) {
2536 $rwid =~ s#/+$##;
2537 if ($rwid !~ m#^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$#) {
2538 die "$rwid is not a valid UUID (key: $k)\n";
2541 $self->{-rewrite_uuid} = $rwid;
2544 sub metadata_url {
2545 my ($self) = @_;
2546 ($self->rewrite_root || $self->{url}) .
2547 (length $self->{path} ? '/' . $self->{path} : '');
2550 sub full_url {
2551 my ($self) = @_;
2552 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2555 sub full_pushurl {
2556 my ($self) = @_;
2557 if ($self->{pushurl}) {
2558 return $self->{pushurl} . (length $self->{path} ? '/' .
2559 $self->{path} : '');
2560 } else {
2561 return $self->full_url;
2565 sub set_commit_header_env {
2566 my ($log_entry) = @_;
2567 my %env;
2568 foreach my $ned (qw/NAME EMAIL DATE/) {
2569 foreach my $ac (qw/AUTHOR COMMITTER/) {
2570 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2574 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2575 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2576 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2578 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2579 ? $log_entry->{commit_name}
2580 : $log_entry->{name};
2581 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2582 ? $log_entry->{commit_email}
2583 : $log_entry->{email};
2584 \%env;
2587 sub restore_commit_header_env {
2588 my ($env) = @_;
2589 foreach my $ned (qw/NAME EMAIL DATE/) {
2590 foreach my $ac (qw/AUTHOR COMMITTER/) {
2591 my $k = "GIT_${ac}_${ned}";
2592 if (defined $env->{$k}) {
2593 $ENV{$k} = $env->{$k};
2594 } else {
2595 delete $ENV{$k};
2601 sub gc {
2602 command_noisy('gc', '--auto');
2605 sub do_git_commit {
2606 my ($self, $log_entry) = @_;
2607 my $lr = $self->last_rev;
2608 if (defined $lr && $lr >= $log_entry->{revision}) {
2609 die "Last fetched revision of ", $self->refname,
2610 " was r$lr, but we are about to fetch: ",
2611 "r$log_entry->{revision}!\n";
2613 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2614 croak "$log_entry->{revision} = $c already exists! ",
2615 "Why are we refetching it?\n";
2617 my $old_env = set_commit_header_env($log_entry);
2618 my $tree = $log_entry->{tree};
2619 if (!defined $tree) {
2620 $tree = $self->tmp_index_do(sub {
2621 command_oneline('write-tree') });
2623 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2625 my @exec = ('git', 'commit-tree', $tree);
2626 foreach ($self->get_commit_parents($log_entry)) {
2627 push @exec, '-p', $_;
2629 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2630 or croak $!;
2631 binmode $msg_fh;
2633 # we always get UTF-8 from SVN, but we may want our commits in
2634 # a different encoding.
2635 if (my $enc = Git::config('i18n.commitencoding')) {
2636 require Encode;
2637 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2639 print $msg_fh $log_entry->{log} or croak $!;
2640 restore_commit_header_env($old_env);
2641 unless ($self->no_metadata) {
2642 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2643 or croak $!;
2645 $msg_fh->flush == 0 or croak $!;
2646 close $msg_fh or croak $!;
2647 chomp(my $commit = do { local $/; <$out_fh> });
2648 close $out_fh or croak $!;
2649 waitpid $pid, 0;
2650 croak $? if $?;
2651 if ($commit !~ /^$::sha1$/o) {
2652 die "Failed to commit, invalid sha1: $commit\n";
2655 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2657 $self->{last_rev} = $log_entry->{revision};
2658 $self->{last_commit} = $commit;
2659 print "r$log_entry->{revision}" unless $::_q > 1;
2660 if (defined $log_entry->{svm_revision}) {
2661 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2662 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2663 0, $self->svm_uuid);
2665 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2666 if (--$_gc_nr == 0) {
2667 $_gc_nr = $_gc_period;
2668 gc();
2670 return $commit;
2673 sub match_paths {
2674 my ($self, $paths, $r) = @_;
2675 return 1 if $self->{path} eq '';
2676 if (my $path = $paths->{"/$self->{path}"}) {
2677 return ($path->{action} eq 'D') ? 0 : 1;
2679 $self->{path_regex} ||= qr/^\/\Q$self->{path}\E\//;
2680 if (grep /$self->{path_regex}/, keys %$paths) {
2681 return 1;
2683 my $c = '';
2684 foreach (split m#/#, $self->{path}) {
2685 $c .= "/$_";
2686 next unless ($paths->{$c} &&
2687 ($paths->{$c}->{action} =~ /^[AR]$/));
2688 if ($self->ra->check_path($self->{path}, $r) ==
2689 $SVN::Node::dir) {
2690 return 1;
2693 return 0;
2696 sub find_parent_branch {
2697 my ($self, $paths, $rev) = @_;
2698 return undef unless $self->follow_parent;
2699 unless (defined $paths) {
2700 my $err_handler = $SVN::Error::handler;
2701 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2702 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1,
2703 sub { $paths = $_[0] });
2704 $SVN::Error::handler = $err_handler;
2706 return undef unless defined $paths;
2708 # look for a parent from another branch:
2709 my @b_path_components = split m#/#, $self->{path};
2710 my @a_path_components;
2711 my $i;
2712 while (@b_path_components) {
2713 $i = $paths->{'/'.join('/', @b_path_components)};
2714 last if $i && defined $i->{copyfrom_path};
2715 unshift(@a_path_components, pop(@b_path_components));
2717 return undef unless defined $i && defined $i->{copyfrom_path};
2718 my $branch_from = $i->{copyfrom_path};
2719 if (@a_path_components) {
2720 print STDERR "branch_from: $branch_from => ";
2721 $branch_from .= '/'.join('/', @a_path_components);
2722 print STDERR $branch_from, "\n";
2724 my $r = $i->{copyfrom_rev};
2725 my $repos_root = $self->ra->{repos_root};
2726 my $url = $self->ra->{url};
2727 my $new_url = $url . $branch_from;
2728 print STDERR "Found possible branch point: ",
2729 "$new_url => ", $self->full_url, ", $r\n"
2730 unless $::_q > 1;
2731 $branch_from =~ s#^/##;
2732 my $gs = $self->other_gs($new_url, $url,
2733 $branch_from, $r, $self->{ref_id});
2734 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2736 my ($base, $head);
2737 if (!defined $r0 || !defined $parent) {
2738 ($base, $head) = parse_revision_argument(0, $r);
2739 } else {
2740 if ($r0 < $r) {
2741 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2742 0, 1, sub { $base = $_[1] - 1 });
2745 if (defined $base && $base <= $r) {
2746 $gs->fetch($base, $r);
2748 ($r0, $parent) = $gs->find_rev_before($r, 1);
2750 if (defined $r0 && defined $parent) {
2751 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n"
2752 unless $::_q > 1;
2753 my $ed;
2754 if ($self->ra->can_do_switch) {
2755 $self->assert_index_clean($parent);
2756 print STDERR "Following parent with do_switch\n"
2757 unless $::_q > 1;
2758 # do_switch works with svn/trunk >= r22312, but that
2759 # is not included with SVN 1.4.3 (the latest version
2760 # at the moment), so we can't rely on it
2761 $self->{last_rev} = $r0;
2762 $self->{last_commit} = $parent;
2763 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2764 $gs->ra->gs_do_switch($r0, $rev, $gs,
2765 $self->full_url, $ed)
2766 or die "SVN connection failed somewhere...\n";
2767 } elsif ($self->ra->trees_match($new_url, $r0,
2768 $self->full_url, $rev)) {
2769 print STDERR "Trees match:\n",
2770 " $new_url\@$r0\n",
2771 " ${\$self->full_url}\@$rev\n",
2772 "Following parent with no changes\n"
2773 unless $::_q > 1;
2774 $self->tmp_index_do(sub {
2775 command_noisy('read-tree', $parent);
2777 $self->{last_commit} = $parent;
2778 } else {
2779 print STDERR "Following parent with do_update\n"
2780 unless $::_q > 1;
2781 $ed = SVN::Git::Fetcher->new($self);
2782 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2783 or die "SVN connection failed somewhere...\n";
2785 print STDERR "Successfully followed parent\n" unless $::_q > 1;
2786 return $self->make_log_entry($rev, [$parent], $ed);
2788 return undef;
2791 sub do_fetch {
2792 my ($self, $paths, $rev) = @_;
2793 my $ed;
2794 my ($last_rev, @parents);
2795 if (my $lc = $self->last_commit) {
2796 # we can have a branch that was deleted, then re-added
2797 # under the same name but copied from another path, in
2798 # which case we'll have multiple parents (we don't
2799 # want to break the original ref, nor lose copypath info):
2800 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2801 push @{$log_entry->{parents}}, $lc;
2802 return $log_entry;
2804 $ed = SVN::Git::Fetcher->new($self);
2805 $last_rev = $self->{last_rev};
2806 $ed->{c} = $lc;
2807 @parents = ($lc);
2808 } else {
2809 $last_rev = $rev;
2810 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2811 return $log_entry;
2813 $ed = SVN::Git::Fetcher->new($self);
2815 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2816 die "SVN connection failed somewhere...\n";
2818 $self->make_log_entry($rev, \@parents, $ed);
2821 sub mkemptydirs {
2822 my ($self, $r) = @_;
2824 sub scan {
2825 my ($r, $empty_dirs, $line) = @_;
2826 if (defined $r && $line =~ /^r(\d+)$/) {
2827 return 0 if $1 > $r;
2828 } elsif ($line =~ /^ \+empty_dir: (.+)$/) {
2829 $empty_dirs->{$1} = 1;
2830 } elsif ($line =~ /^ \-empty_dir: (.+)$/) {
2831 my @d = grep {m[^\Q$1\E(/|$)]} (keys %$empty_dirs);
2832 delete @$empty_dirs{@d};
2834 1; # continue
2837 my %empty_dirs = ();
2838 my $gz_file = "$self->{dir}/unhandled.log.gz";
2839 if (-f $gz_file) {
2840 if (!$can_compress) {
2841 warn "Compress::Zlib could not be found; ",
2842 "empty directories in $gz_file will not be read\n";
2843 } else {
2844 my $gz = Compress::Zlib::gzopen($gz_file, "rb") or
2845 die "Unable to open $gz_file: $!\n";
2846 my $line;
2847 while ($gz->gzreadline($line) > 0) {
2848 scan($r, \%empty_dirs, $line) or last;
2850 $gz->gzclose;
2854 if (open my $fh, '<', "$self->{dir}/unhandled.log") {
2855 binmode $fh or croak "binmode: $!";
2856 while (<$fh>) {
2857 scan($r, \%empty_dirs, $_) or last;
2859 close $fh;
2862 my $strip = qr/\A\Q$self->{path}\E(?:\/|$)/;
2863 foreach my $d (sort keys %empty_dirs) {
2864 $d = uri_decode($d);
2865 $d =~ s/$strip//;
2866 next unless length($d);
2867 next if -d $d;
2868 if (-e $d) {
2869 warn "$d exists but is not a directory\n";
2870 } else {
2871 print "creating empty directory: $d\n";
2872 mkpath([$d]);
2877 sub get_untracked {
2878 my ($self, $ed) = @_;
2879 my @out;
2880 my $h = $ed->{empty};
2881 foreach (sort keys %$h) {
2882 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2883 push @out, " $act: " . uri_encode($_);
2884 warn "W: $act: $_\n";
2886 foreach my $t (qw/dir_prop file_prop/) {
2887 $h = $ed->{$t} or next;
2888 foreach my $path (sort keys %$h) {
2889 my $ppath = $path eq '' ? '.' : $path;
2890 foreach my $prop (sort keys %{$h->{$path}}) {
2891 next if $SKIP_PROP{$prop};
2892 my $v = $h->{$path}->{$prop};
2893 my $t_ppath_prop = "$t: " .
2894 uri_encode($ppath) . ' ' .
2895 uri_encode($prop);
2896 if (defined $v) {
2897 push @out, " +$t_ppath_prop " .
2898 uri_encode($v);
2899 } else {
2900 push @out, " -$t_ppath_prop";
2905 foreach my $t (qw/absent_file absent_directory/) {
2906 $h = $ed->{$t} or next;
2907 foreach my $parent (sort keys %$h) {
2908 foreach my $path (sort @{$h->{$parent}}) {
2909 push @out, " $t: " .
2910 uri_encode("$parent/$path");
2911 warn "W: $t: $parent/$path ",
2912 "Insufficient permissions?\n";
2916 \@out;
2919 # parse_svn_date(DATE)
2920 # --------------------
2921 # Given a date (in UTC) from Subversion, return a string in the format
2922 # "<TZ Offset> <local date/time>" that Git will use.
2924 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2925 # is true we'll convert it to the local timezone instead.
2926 sub parse_svn_date {
2927 my $date = shift || return '+0000 1970-01-01 00:00:00';
2928 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2929 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2930 croak "Unable to parse date: $date\n";
2931 my $parsed_date; # Set next.
2933 if ($Git::SVN::_localtime) {
2934 # Translate the Subversion datetime to an epoch time.
2935 # Begin by switching ourselves to $date's timezone, UTC.
2936 my $old_env_TZ = $ENV{TZ};
2937 $ENV{TZ} = 'UTC';
2939 my $epoch_in_UTC =
2940 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2942 # Determine our local timezone (including DST) at the
2943 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2944 # value of TZ, if any, at the time we were run.
2945 if (defined $Git::SVN::Log::TZ) {
2946 $ENV{TZ} = $Git::SVN::Log::TZ;
2947 } else {
2948 delete $ENV{TZ};
2951 my $our_TZ =
2952 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2954 # This converts $epoch_in_UTC into our local timezone.
2955 my ($sec, $min, $hour, $mday, $mon, $year,
2956 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2958 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2959 $our_TZ, $year + 1900, $mon + 1,
2960 $mday, $hour, $min, $sec);
2962 # Reset us to the timezone in effect when we entered
2963 # this routine.
2964 if (defined $old_env_TZ) {
2965 $ENV{TZ} = $old_env_TZ;
2966 } else {
2967 delete $ENV{TZ};
2969 } else {
2970 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2973 return $parsed_date;
2976 sub other_gs {
2977 my ($self, $new_url, $url,
2978 $branch_from, $r, $old_ref_id) = @_;
2979 my $gs = Git::SVN->find_by_url($new_url, $url, $branch_from);
2980 unless ($gs) {
2981 my $ref_id = $old_ref_id;
2982 $ref_id =~ s/\@\d+-*$//;
2983 $ref_id .= "\@$r";
2984 # just grow a tail if we're not unique enough :x
2985 $ref_id .= '-' while find_ref($ref_id);
2986 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2987 if ($u =~ s#^\Q$url\E(/|$)##) {
2988 $p = $u;
2989 $u = $url;
2990 $repo_id = $self->{repo_id};
2992 while (1) {
2993 # It is possible to tag two different subdirectories at
2994 # the same revision. If the url for an existing ref
2995 # does not match, we must either find a ref with a
2996 # matching url or create a new ref by growing a tail.
2997 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2998 my (undef, $max_commit) = $gs->rev_map_max(1);
2999 last if (!$max_commit);
3000 my ($url) = ::cmt_metadata($max_commit);
3001 last if ($url eq $gs->full_url);
3002 $ref_id .= '-';
3004 print STDERR "Initializing parent: $ref_id\n" unless $::_q > 1;
3009 sub call_authors_prog {
3010 my ($orig_author) = @_;
3011 $orig_author = command_oneline('rev-parse', '--sq-quote', $orig_author);
3012 my $author = `$::_authors_prog $orig_author`;
3013 if ($? != 0) {
3014 die "$::_authors_prog failed with exit code $?\n"
3016 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
3017 my ($name, $email) = ($1, $2);
3018 $email = undef if length $2 == 0;
3019 return [$name, $email];
3020 } else {
3021 die "Author: $orig_author: $::_authors_prog returned "
3022 . "invalid author format: $author\n";
3026 sub check_author {
3027 my ($author) = @_;
3028 if (!defined $author || length $author == 0) {
3029 $author = '(no author)';
3031 if (!defined $::users{$author}) {
3032 if (defined $::_authors_prog) {
3033 $::users{$author} = call_authors_prog($author);
3034 } elsif (defined $::_authors) {
3035 die "Author: $author not defined in $::_authors file\n";
3038 $author;
3041 sub find_extra_svk_parents {
3042 my ($self, $ed, $tickets, $parents) = @_;
3043 # aha! svk:merge property changed...
3044 my @tickets = split "\n", $tickets;
3045 my @known_parents;
3046 for my $ticket ( @tickets ) {
3047 my ($uuid, $path, $rev) = split /:/, $ticket;
3048 if ( $uuid eq $self->ra_uuid ) {
3049 my $url = $self->{url};
3050 my $repos_root = $url;
3051 my $branch_from = $path;
3052 $branch_from =~ s{^/}{};
3053 my $gs = $self->other_gs($repos_root."/".$branch_from,
3054 $url,
3055 $branch_from,
3056 $rev,
3057 $self->{ref_id});
3058 if ( my $commit = $gs->rev_map_get($rev, $uuid) ) {
3059 # wahey! we found it, but it might be
3060 # an old one (!)
3061 push @known_parents, [ $rev, $commit ];
3065 # Ordering matters; highest-numbered commit merge tickets
3066 # first, as they may account for later merge ticket additions
3067 # or changes.
3068 @known_parents = map {$_->[1]} sort {$b->[0] <=> $a->[0]} @known_parents;
3069 for my $parent ( @known_parents ) {
3070 my @cmd = ('rev-list', $parent, map { "^$_" } @$parents );
3071 my ($msg_fh, $ctx) = command_output_pipe(@cmd);
3072 my $new;
3073 while ( <$msg_fh> ) {
3074 $new=1;last;
3076 command_close_pipe($msg_fh, $ctx);
3077 if ( $new ) {
3078 print STDERR
3079 "Found merge parent (svk:merge ticket): $parent\n";
3080 push @$parents, $parent;
3085 sub lookup_svn_merge {
3086 my $uuid = shift;
3087 my $url = shift;
3088 my $merge = shift;
3090 my ($source, $revs) = split ":", $merge;
3091 my $path = $source;
3092 $path =~ s{^/}{};
3093 my $gs = Git::SVN->find_by_url($url.$source, $url, $path);
3094 if ( !$gs ) {
3095 warn "Couldn't find revmap for $url$source\n";
3096 return;
3098 my @ranges = split ",", $revs;
3099 my ($tip, $tip_commit);
3100 my @merged_commit_ranges;
3101 # find the tip
3102 for my $range ( @ranges ) {
3103 my ($bottom, $top) = split "-", $range;
3104 $top ||= $bottom;
3105 my $bottom_commit = $gs->find_rev_after( $bottom, 1, $top );
3106 my $top_commit = $gs->find_rev_before( $top, 1, $bottom );
3108 unless ($top_commit and $bottom_commit) {
3109 warn "W:unknown path/rev in svn:mergeinfo "
3110 ."dirprop: $source:$range\n";
3111 next;
3114 push @merged_commit_ranges,
3115 "$bottom_commit^..$top_commit";
3117 if ( !defined $tip or $top > $tip ) {
3118 $tip = $top;
3119 $tip_commit = $top_commit;
3122 return ($tip_commit, @merged_commit_ranges);
3125 sub _rev_list {
3126 my ($msg_fh, $ctx) = command_output_pipe(
3127 "rev-list", @_,
3129 my @rv;
3130 while ( <$msg_fh> ) {
3131 chomp;
3132 push @rv, $_;
3134 command_close_pipe($msg_fh, $ctx);
3135 @rv;
3138 sub check_cherry_pick {
3139 my $base = shift;
3140 my $tip = shift;
3141 my $parents = shift;
3142 my @ranges = @_;
3143 my %commits = map { $_ => 1 }
3144 _rev_list("--no-merges", $tip, "--not", $base, @$parents);
3145 for my $range ( @ranges ) {
3146 delete @commits{_rev_list($range)};
3148 for my $commit (keys %commits) {
3149 if (has_no_changes($commit)) {
3150 delete $commits{$commit};
3153 return (keys %commits);
3156 sub has_no_changes {
3157 my $commit = shift;
3159 my @revs = split / /, command_oneline(
3160 qw(rev-list --parents -1 -m), $commit);
3162 # Commits with no parents, e.g. the start of a partial branch,
3163 # have changes by definition.
3164 return 1 if (@revs < 2);
3166 # Commits with multiple parents, e.g a merge, have no changes
3167 # by definition.
3168 return 0 if (@revs > 2);
3170 return (command_oneline("rev-parse", "$commit^{tree}") eq
3171 command_oneline("rev-parse", "$commit~1^{tree}"));
3174 # The GIT_DIR environment variable is not always set until after the command
3175 # line arguments are processed, so we can't memoize in a BEGIN block.
3177 my $memoized = 0;
3179 sub memoize_svn_mergeinfo_functions {
3180 return if $memoized;
3181 $memoized = 1;
3183 my $cache_path = "$ENV{GIT_DIR}/svn/.caches/";
3184 mkpath([$cache_path]) unless -d $cache_path;
3186 tie my %lookup_svn_merge_cache => 'Memoize::Storable',
3187 "$cache_path/lookup_svn_merge.db", 'nstore';
3188 memoize 'lookup_svn_merge',
3189 SCALAR_CACHE => 'FAULT',
3190 LIST_CACHE => ['HASH' => \%lookup_svn_merge_cache],
3193 tie my %check_cherry_pick_cache => 'Memoize::Storable',
3194 "$cache_path/check_cherry_pick.db", 'nstore';
3195 memoize 'check_cherry_pick',
3196 SCALAR_CACHE => 'FAULT',
3197 LIST_CACHE => ['HASH' => \%check_cherry_pick_cache],
3200 tie my %has_no_changes_cache => 'Memoize::Storable',
3201 "$cache_path/has_no_changes.db", 'nstore';
3202 memoize 'has_no_changes',
3203 SCALAR_CACHE => ['HASH' => \%has_no_changes_cache],
3204 LIST_CACHE => 'FAULT',
3208 sub unmemoize_svn_mergeinfo_functions {
3209 return if not $memoized;
3210 $memoized = 0;
3212 Memoize::unmemoize 'lookup_svn_merge';
3213 Memoize::unmemoize 'check_cherry_pick';
3214 Memoize::unmemoize 'has_no_changes';
3217 Memoize::memoize 'Git::SVN::repos_root';
3220 END {
3221 # Force cache writeout explicitly instead of waiting for
3222 # global destruction to avoid segfault in Storable:
3223 # http://rt.cpan.org/Public/Bug/Display.html?id=36087
3224 unmemoize_svn_mergeinfo_functions();
3227 sub parents_exclude {
3228 my $parents = shift;
3229 my @commits = @_;
3230 return unless @commits;
3232 my @excluded;
3233 my $excluded;
3234 do {
3235 my @cmd = ('rev-list', "-1", @commits, "--not", @$parents );
3236 $excluded = command_oneline(@cmd);
3237 if ( $excluded ) {
3238 my @new;
3239 my $found;
3240 for my $commit ( @commits ) {
3241 if ( $commit eq $excluded ) {
3242 push @excluded, $commit;
3243 $found++;
3244 last;
3246 else {
3247 push @new, $commit;
3250 die "saw commit '$excluded' in rev-list output, "
3251 ."but we didn't ask for that commit (wanted: @commits --not @$parents)"
3252 unless $found;
3253 @commits = @new;
3256 while ($excluded and @commits);
3258 return @excluded;
3262 # note: this function should only be called if the various dirprops
3263 # have actually changed
3264 sub find_extra_svn_parents {
3265 my ($self, $ed, $mergeinfo, $parents) = @_;
3266 # aha! svk:merge property changed...
3268 memoize_svn_mergeinfo_functions();
3270 # We first search for merged tips which are not in our
3271 # history. Then, we figure out which git revisions are in
3272 # that tip, but not this revision. If all of those revisions
3273 # are now marked as merge, we can add the tip as a parent.
3274 my @merges = split "\n", $mergeinfo;
3275 my @merge_tips;
3276 my $url = $self->{url};
3277 my $uuid = $self->ra_uuid;
3278 my %ranges;
3279 for my $merge ( @merges ) {
3280 my ($tip_commit, @ranges) =
3281 lookup_svn_merge( $uuid, $url, $merge );
3282 unless (!$tip_commit or
3283 grep { $_ eq $tip_commit } @$parents ) {
3284 push @merge_tips, $tip_commit;
3285 $ranges{$tip_commit} = \@ranges;
3286 } else {
3287 push @merge_tips, undef;
3291 my %excluded = map { $_ => 1 }
3292 parents_exclude($parents, grep { defined } @merge_tips);
3294 # check merge tips for new parents
3295 my @new_parents;
3296 for my $merge_tip ( @merge_tips ) {
3297 my $spec = shift @merges;
3298 next unless $merge_tip and $excluded{$merge_tip};
3300 my $ranges = $ranges{$merge_tip};
3302 # check out 'new' tips
3303 my $merge_base;
3304 eval {
3305 $merge_base = command_oneline(
3306 "merge-base",
3307 @$parents, $merge_tip,
3310 if ($@) {
3311 die "An error occurred during merge-base"
3312 unless $@->isa("Git::Error::Command");
3314 warn "W: Cannot find common ancestor between ".
3315 "@$parents and $merge_tip. Ignoring merge info.\n";
3316 next;
3319 # double check that there are no missing non-merge commits
3320 my (@incomplete) = check_cherry_pick(
3321 $merge_base, $merge_tip,
3322 $parents,
3323 @$ranges,
3326 if ( @incomplete ) {
3327 warn "W:svn cherry-pick ignored ($spec) - missing "
3328 .@incomplete." commit(s) (eg $incomplete[0])\n";
3329 } else {
3330 warn
3331 "Found merge parent (svn:mergeinfo prop): ",
3332 $merge_tip, "\n";
3333 push @new_parents, $merge_tip;
3337 # cater for merges which merge commits from multiple branches
3338 if ( @new_parents > 1 ) {
3339 for ( my $i = 0; $i <= $#new_parents; $i++ ) {
3340 for ( my $j = 0; $j <= $#new_parents; $j++ ) {
3341 next if $i == $j;
3342 next unless $new_parents[$i];
3343 next unless $new_parents[$j];
3344 my $revs = command_oneline(
3345 "rev-list", "-1",
3346 "$new_parents[$i]..$new_parents[$j]",
3348 if ( !$revs ) {
3349 undef($new_parents[$j]);
3354 push @$parents, grep { defined } @new_parents;
3357 sub make_log_entry {
3358 my ($self, $rev, $parents, $ed) = @_;
3359 my $untracked = $self->get_untracked($ed);
3361 my @parents = @$parents;
3362 my $ps = $ed->{path_strip} || "";
3363 for my $path ( grep { m/$ps/ } %{$ed->{dir_prop}} ) {
3364 my $props = $ed->{dir_prop}{$path};
3365 if ( $props->{"svk:merge"} ) {
3366 $self->find_extra_svk_parents
3367 ($ed, $props->{"svk:merge"}, \@parents);
3369 if ( $props->{"svn:mergeinfo"} ) {
3370 $self->find_extra_svn_parents
3371 ($ed,
3372 $props->{"svn:mergeinfo"},
3373 \@parents);
3377 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
3378 print $un "r$rev\n" or croak $!;
3379 print $un $_, "\n" foreach @$untracked;
3380 my %log_entry = ( parents => \@parents, revision => $rev,
3381 log => '');
3383 my $headrev;
3384 my $logged = delete $self->{logged_rev_props};
3385 if (!$logged || $self->{-want_revprops}) {
3386 my $rp = $self->ra->rev_proplist($rev);
3387 foreach (sort keys %$rp) {
3388 my $v = $rp->{$_};
3389 if (/^svn:(author|date|log)$/) {
3390 $log_entry{$1} = $v;
3391 } elsif ($_ eq 'svm:headrev') {
3392 $headrev = $v;
3393 } else {
3394 print $un " rev_prop: ", uri_encode($_), ' ',
3395 uri_encode($v), "\n";
3398 } else {
3399 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
3401 close $un or croak $!;
3403 $log_entry{date} = parse_svn_date($log_entry{date});
3404 $log_entry{log} .= "\n";
3405 my $author = $log_entry{author} = check_author($log_entry{author});
3406 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
3407 : ($author, undef);
3409 my ($commit_name, $commit_email) = ($name, $email);
3410 if ($_use_log_author) {
3411 my $name_field;
3412 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
3413 $name_field = $1;
3414 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
3415 $name_field = $1;
3417 if (!defined $name_field) {
3418 if (!defined $email) {
3419 $email = $name;
3421 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
3422 ($name, $email) = ($1, $2);
3423 } elsif ($name_field =~ /(.*)@/) {
3424 ($name, $email) = ($1, $name_field);
3425 } else {
3426 ($name, $email) = ($name_field, $name_field);
3429 if (defined $headrev && $self->use_svm_props) {
3430 if ($self->rewrite_root) {
3431 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
3432 "options set!\n";
3434 if ($self->rewrite_uuid) {
3435 die "Can't have both 'useSvmProps' and 'rewriteUUID' ",
3436 "options set!\n";
3438 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$}i;
3439 # we don't want "SVM: initializing mirror for junk" ...
3440 return undef if $r == 0;
3441 my $svm = $self->svm;
3442 if ($uuid ne $svm->{uuid}) {
3443 die "UUID mismatch on SVM path:\n",
3444 "expected: $svm->{uuid}\n",
3445 " got: $uuid\n";
3447 my $full_url = $self->full_url;
3448 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
3449 die "Failed to replace '$svm->{replace}' with ",
3450 "'$svm->{source}' in $full_url\n";
3451 # throw away username for storing in records
3452 remove_username($full_url);
3453 $log_entry{metadata} = "$full_url\@$r $uuid";
3454 $log_entry{svm_revision} = $r;
3455 $email ||= "$author\@$uuid";
3456 $commit_email ||= "$author\@$uuid";
3457 } elsif ($self->use_svnsync_props) {
3458 my $full_url = $self->svnsync->{url};
3459 $full_url .= "/$self->{path}" if length $self->{path};
3460 remove_username($full_url);
3461 my $uuid = $self->svnsync->{uuid};
3462 $log_entry{metadata} = "$full_url\@$rev $uuid";
3463 $email ||= "$author\@$uuid";
3464 $commit_email ||= "$author\@$uuid";
3465 } else {
3466 my $url = $self->metadata_url;
3467 remove_username($url);
3468 my $uuid = $self->rewrite_uuid || $self->ra->get_uuid;
3469 $log_entry{metadata} = "$url\@$rev " . $uuid;
3470 $email ||= "$author\@" . $uuid;
3471 $commit_email ||= "$author\@" . $uuid;
3473 $log_entry{name} = $name;
3474 $log_entry{email} = $email;
3475 $log_entry{commit_name} = $commit_name;
3476 $log_entry{commit_email} = $commit_email;
3477 \%log_entry;
3480 sub fetch {
3481 my ($self, $min_rev, $max_rev, @parents) = @_;
3482 my ($last_rev, $last_commit) = $self->last_rev_commit;
3483 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
3484 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
3487 sub set_tree_cb {
3488 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
3489 $self->{inject_parents} = { $rev => $tree };
3490 $self->fetch(undef, undef);
3493 sub set_tree {
3494 my ($self, $tree) = (shift, shift);
3495 my $log_entry = ::get_commit_entry($tree);
3496 unless ($self->{last_rev}) {
3497 ::fatal("Must have an existing revision to commit");
3499 my %ed_opts = ( r => $self->{last_rev},
3500 log => $log_entry->{log},
3501 ra => $self->ra,
3502 tree_a => $self->{last_commit},
3503 tree_b => $tree,
3504 editor_cb => sub {
3505 $self->set_tree_cb($log_entry, $tree, @_) },
3506 svn_path => $self->{path} );
3507 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
3508 print "No changes\nr$self->{last_rev} = $tree\n";
3512 sub rebuild_from_rev_db {
3513 my ($self, $path) = @_;
3514 my $r = -1;
3515 open my $fh, '<', $path or croak "open: $!";
3516 binmode $fh or croak "binmode: $!";
3517 while (<$fh>) {
3518 length($_) == 41 or croak "inconsistent size in ($_) != 41";
3519 chomp($_);
3520 ++$r;
3521 next if $_ eq ('0' x 40);
3522 $self->rev_map_set($r, $_);
3523 print "r$r = $_\n";
3525 close $fh or croak "close: $!";
3526 unlink $path or croak "unlink: $!";
3529 sub rebuild {
3530 my ($self) = @_;
3531 my $map_path = $self->map_path;
3532 my $partial = (-e $map_path && ! -z $map_path);
3533 return unless ::verify_ref($self->refname.'^0');
3534 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
3535 my $rev_db = $self->rev_db_path;
3536 $self->rebuild_from_rev_db($rev_db);
3537 if ($self->use_svm_props) {
3538 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
3539 $self->rebuild_from_rev_db($svm_rev_db);
3541 $self->unlink_rev_db_symlink;
3542 return;
3544 print "Rebuilding $map_path ...\n" if (!$partial);
3545 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
3546 (undef, undef));
3547 my ($log, $ctx) =
3548 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
3549 ($head ? "$head.." : "") . $self->refname,
3550 '--');
3551 my $metadata_url = $self->metadata_url;
3552 remove_username($metadata_url);
3553 my $svn_uuid = $self->rewrite_uuid || $self->ra_uuid;
3554 my $c;
3555 while (<$log>) {
3556 if ( m{^commit ($::sha1)$} ) {
3557 $c = $1;
3558 next;
3560 next unless s{^\s*(git-svn-id:)}{$1};
3561 my ($url, $rev, $uuid) = ::extract_metadata($_);
3562 remove_username($url);
3564 # ignore merges (from set-tree)
3565 next if (!defined $rev || !$uuid);
3567 # if we merged or otherwise started elsewhere, this is
3568 # how we break out of it
3569 if (($uuid ne $svn_uuid) ||
3570 ($metadata_url && $url && ($url ne $metadata_url))) {
3571 next;
3573 if ($partial && $head) {
3574 print "Partial-rebuilding $map_path ...\n";
3575 print "Currently at $base_rev = $head\n";
3576 $head = undef;
3579 $self->rev_map_set($rev, $c);
3580 print "r$rev = $c\n";
3582 command_close_pipe($log, $ctx);
3583 print "Done rebuilding $map_path\n" if (!$partial || !$head);
3584 my $rev_db_path = $self->rev_db_path;
3585 if (-f $self->rev_db_path) {
3586 unlink $self->rev_db_path or croak "unlink: $!";
3588 $self->unlink_rev_db_symlink;
3591 # rev_map:
3592 # Tie::File seems to be prone to offset errors if revisions get sparse,
3593 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
3594 # one of my favorite modules is out :< Next up would be one of the DBM
3595 # modules, but I'm not sure which is most portable...
3597 # This is the replacement for the rev_db format, which was too big
3598 # and inefficient for large repositories with a lot of sparse history
3599 # (mainly tags)
3601 # The format is this:
3602 # - 24 bytes for every record,
3603 # * 4 bytes for the integer representing an SVN revision number
3604 # * 20 bytes representing the sha1 of a git commit
3605 # - No empty padding records like the old format
3606 # (except the last record, which can be overwritten)
3607 # - new records are written append-only since SVN revision numbers
3608 # increase monotonically
3609 # - lookups on SVN revision number are done via a binary search
3610 # - Piping the file to xxd -c24 is a good way of dumping it for
3611 # viewing or editing (piped back through xxd -r), should the need
3612 # ever arise.
3613 # - The last record can be padding revision with an all-zero sha1
3614 # This is used to optimize fetch performance when using multiple
3615 # "fetch" directives in .git/config
3617 # These files are disposable unless noMetadata or useSvmProps is set
3619 sub _rev_map_set {
3620 my ($fh, $rev, $commit) = @_;
3622 binmode $fh or croak "binmode: $!";
3623 my $size = (stat($fh))[7];
3624 ($size % 24) == 0 or croak "inconsistent size: $size";
3626 my $wr_offset = 0;
3627 if ($size > 0) {
3628 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3629 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
3630 $read == 24 or croak "read only $read bytes (!= 24)";
3631 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
3632 if ($last_commit eq ('0' x40)) {
3633 if ($size >= 48) {
3634 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3635 $read = sysread($fh, $buf, 24) or
3636 croak "read: $!";
3637 $read == 24 or
3638 croak "read only $read bytes (!= 24)";
3639 ($last_rev, $last_commit) =
3640 unpack(rev_map_fmt, $buf);
3641 if ($last_commit eq ('0' x40)) {
3642 croak "inconsistent .rev_map\n";
3645 if ($last_rev >= $rev) {
3646 croak "last_rev is higher!: $last_rev >= $rev";
3648 $wr_offset = -24;
3651 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3652 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3653 croak "write: $!";
3656 sub _rev_map_reset {
3657 my ($fh, $rev, $commit) = @_;
3658 my $c = _rev_map_get($fh, $rev);
3659 $c eq $commit or die "_rev_map_reset(@_) commit $c does not match!\n";
3660 my $offset = sysseek($fh, 0, SEEK_CUR) or croak "seek: $!";
3661 truncate $fh, $offset or croak "truncate: $!";
3664 sub mkfile {
3665 my ($path) = @_;
3666 unless (-e $path) {
3667 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3668 mkpath([$dir]) unless -d $dir;
3669 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3670 close $fh or die "Couldn't close (create) $path: $!\n";
3674 sub rev_map_set {
3675 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3676 defined $commit or die "missing arg3\n";
3677 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3678 my $db = $self->map_path($uuid);
3679 my $db_lock = "$db.lock";
3680 my $sig;
3681 $update_ref ||= 0;
3682 if ($update_ref) {
3683 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3684 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3686 mkfile($db);
3688 $LOCKFILES{$db_lock} = 1;
3689 my $sync;
3690 # both of these options make our .rev_db file very, very important
3691 # and we can't afford to lose it because rebuild() won't work
3692 if ($self->use_svm_props || $self->no_metadata) {
3693 $sync = 1;
3694 copy($db, $db_lock) or die "rev_map_set(@_): ",
3695 "Failed to copy: ",
3696 "$db => $db_lock ($!)\n";
3697 } else {
3698 rename $db, $db_lock or die "rev_map_set(@_): ",
3699 "Failed to rename: ",
3700 "$db => $db_lock ($!)\n";
3703 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3704 or croak "Couldn't open $db_lock: $!\n";
3705 $update_ref eq 'reset' ? _rev_map_reset($fh, $rev, $commit) :
3706 _rev_map_set($fh, $rev, $commit);
3707 if ($sync) {
3708 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3709 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3711 close $fh or croak $!;
3712 if ($update_ref) {
3713 $_head = $self;
3714 my $note = "";
3715 $note = " ($update_ref)" if ($update_ref !~ /^\d*$/);
3716 command_noisy('update-ref', '-m', "r$rev$note",
3717 $self->refname, $commit);
3719 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3720 "$db_lock => $db ($!)\n";
3721 delete $LOCKFILES{$db_lock};
3722 if ($update_ref) {
3723 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3724 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3725 kill $sig, $$ if defined $sig;
3729 # If want_commit, this will return an array of (rev, commit) where
3730 # commit _must_ be a valid commit in the archive.
3731 # Otherwise, it'll return the max revision (whether or not the
3732 # commit is valid or just a 0x40 placeholder).
3733 sub rev_map_max {
3734 my ($self, $want_commit) = @_;
3735 $self->rebuild;
3736 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3737 $want_commit ? ($r, $c) : $r;
3740 sub rev_map_max_norebuild {
3741 my ($self, $want_commit) = @_;
3742 my $map_path = $self->map_path;
3743 stat $map_path or return $want_commit ? (0, undef) : 0;
3744 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3745 binmode $fh or croak "binmode: $!";
3746 my $size = (stat($fh))[7];
3747 ($size % 24) == 0 or croak "inconsistent size: $size";
3749 if ($size == 0) {
3750 close $fh or croak "close: $!";
3751 return $want_commit ? (0, undef) : 0;
3754 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3755 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3756 my ($r, $c) = unpack(rev_map_fmt, $buf);
3757 if ($want_commit && $c eq ('0' x40)) {
3758 if ($size < 48) {
3759 return $want_commit ? (0, undef) : 0;
3761 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3762 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3763 ($r, $c) = unpack(rev_map_fmt, $buf);
3764 if ($c eq ('0'x40)) {
3765 croak "Penultimate record is all-zeroes in $map_path";
3768 close $fh or croak "close: $!";
3769 $want_commit ? ($r, $c) : $r;
3772 sub rev_map_get {
3773 my ($self, $rev, $uuid) = @_;
3774 my $map_path = $self->map_path($uuid);
3775 return undef unless -e $map_path;
3777 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3778 my $c = _rev_map_get($fh, $rev);
3779 close($fh) or croak "close: $!";
3783 sub _rev_map_get {
3784 my ($fh, $rev) = @_;
3786 binmode $fh or croak "binmode: $!";
3787 my $size = (stat($fh))[7];
3788 ($size % 24) == 0 or croak "inconsistent size: $size";
3790 if ($size == 0) {
3791 return undef;
3794 my ($l, $u) = (0, $size - 24);
3795 my ($r, $c, $buf);
3797 while ($l <= $u) {
3798 my $i = int(($l/24 + $u/24) / 2) * 24;
3799 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3800 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3801 my ($r, $c) = unpack(rev_map_fmt, $buf);
3803 if ($r < $rev) {
3804 $l = $i + 24;
3805 } elsif ($r > $rev) {
3806 $u = $i - 24;
3807 } else { # $r == $rev
3808 return $c eq ('0' x 40) ? undef : $c;
3811 undef;
3814 # Finds the first svn revision that exists on (if $eq_ok is true) or
3815 # before $rev for the current branch. It will not search any lower
3816 # than $min_rev. Returns the git commit hash and svn revision number
3817 # if found, else (undef, undef).
3818 sub find_rev_before {
3819 my ($self, $rev, $eq_ok, $min_rev) = @_;
3820 --$rev unless $eq_ok;
3821 $min_rev ||= 1;
3822 my $max_rev = $self->rev_map_max;
3823 $rev = $max_rev if ($rev > $max_rev);
3824 while ($rev >= $min_rev) {
3825 if (my $c = $self->rev_map_get($rev)) {
3826 return ($rev, $c);
3828 --$rev;
3830 return (undef, undef);
3833 # Finds the first svn revision that exists on (if $eq_ok is true) or
3834 # after $rev for the current branch. It will not search any higher
3835 # than $max_rev. Returns the git commit hash and svn revision number
3836 # if found, else (undef, undef).
3837 sub find_rev_after {
3838 my ($self, $rev, $eq_ok, $max_rev) = @_;
3839 ++$rev unless $eq_ok;
3840 $max_rev ||= $self->rev_map_max;
3841 while ($rev <= $max_rev) {
3842 if (my $c = $self->rev_map_get($rev)) {
3843 return ($rev, $c);
3845 ++$rev;
3847 return (undef, undef);
3850 sub _new {
3851 my ($class, $repo_id, $ref_id, $path) = @_;
3852 unless (defined $repo_id && length $repo_id) {
3853 $repo_id = $Git::SVN::default_repo_id;
3855 unless (defined $ref_id && length $ref_id) {
3856 $_prefix = '' unless defined($_prefix);
3857 $_[2] = $ref_id =
3858 "refs/remotes/$_prefix$Git::SVN::default_ref_id";
3860 $_[1] = $repo_id;
3861 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3863 # Older repos imported by us used $GIT_DIR/svn/foo instead of
3864 # $GIT_DIR/svn/refs/remotes/foo when tracking refs/remotes/foo
3865 if ($ref_id =~ m{^refs/remotes/(.*)}) {
3866 my $old_dir = "$ENV{GIT_DIR}/svn/$1";
3867 if (-d $old_dir && ! -d $dir) {
3868 $dir = $old_dir;
3872 $_[3] = $path = '' unless (defined $path);
3873 mkpath([$dir]);
3874 bless {
3875 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3876 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3877 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3880 # for read-only access of old .rev_db formats
3881 sub unlink_rev_db_symlink {
3882 my ($self) = @_;
3883 my $link = $self->rev_db_path;
3884 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3885 if (-l $link) {
3886 unlink $link or croak "unlink: $link failed!";
3890 sub rev_db_path {
3891 my ($self, $uuid) = @_;
3892 my $db_path = $self->map_path($uuid);
3893 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3894 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3895 $db_path;
3898 # the new replacement for .rev_db
3899 sub map_path {
3900 my ($self, $uuid) = @_;
3901 $uuid ||= $self->ra_uuid;
3902 "$self->{map_root}.$uuid";
3905 sub uri_encode {
3906 my ($f) = @_;
3907 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3911 sub uri_decode {
3912 my ($f) = @_;
3913 $f =~ s#%([0-9a-fA-F]{2})#chr(hex($1))#eg;
3917 sub remove_username {
3918 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3921 package Git::SVN::Prompt;
3922 use strict;
3923 use warnings;
3924 require SVN::Core;
3925 use vars qw/$_no_auth_cache $_username/;
3927 sub simple {
3928 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3929 $may_save = undef if $_no_auth_cache;
3930 $default_username = $_username if defined $_username;
3931 if (defined $default_username && length $default_username) {
3932 if (defined $realm && length $realm) {
3933 print STDERR "Authentication realm: $realm\n";
3934 STDERR->flush;
3936 $cred->username($default_username);
3937 } else {
3938 username($cred, $realm, $may_save, $pool);
3940 $cred->password(_read_password("Password for '" .
3941 $cred->username . "': ", $realm));
3942 $cred->may_save($may_save);
3943 $SVN::_Core::SVN_NO_ERROR;
3946 sub ssl_server_trust {
3947 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3948 $may_save = undef if $_no_auth_cache;
3949 print STDERR "Error validating server certificate for '$realm':\n";
3951 no warnings 'once';
3952 # All variables SVN::Auth::SSL::* are used only once,
3953 # so we're shutting up Perl warnings about this.
3954 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3955 print STDERR " - The certificate is not issued ",
3956 "by a trusted authority. Use the\n",
3957 " fingerprint to validate ",
3958 "the certificate manually!\n";
3960 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3961 print STDERR " - The certificate hostname ",
3962 "does not match.\n";
3964 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3965 print STDERR " - The certificate is not yet valid.\n";
3967 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3968 print STDERR " - The certificate has expired.\n";
3970 if ($failures & $SVN::Auth::SSL::OTHER) {
3971 print STDERR " - The certificate has ",
3972 "an unknown error.\n";
3974 } # no warnings 'once'
3975 printf STDERR
3976 "Certificate information:\n".
3977 " - Hostname: %s\n".
3978 " - Valid: from %s until %s\n".
3979 " - Issuer: %s\n".
3980 " - Fingerprint: %s\n",
3981 map $cert_info->$_, qw(hostname valid_from valid_until
3982 issuer_dname fingerprint);
3983 my $choice;
3984 prompt:
3985 print STDERR $may_save ?
3986 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3987 "(R)eject or accept (t)emporarily? ";
3988 STDERR->flush;
3989 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3990 if ($choice =~ /^t$/i) {
3991 $cred->may_save(undef);
3992 } elsif ($choice =~ /^r$/i) {
3993 return -1;
3994 } elsif ($may_save && $choice =~ /^p$/i) {
3995 $cred->may_save($may_save);
3996 } else {
3997 goto prompt;
3999 $cred->accepted_failures($failures);
4000 $SVN::_Core::SVN_NO_ERROR;
4003 sub ssl_client_cert {
4004 my ($cred, $realm, $may_save, $pool) = @_;
4005 $may_save = undef if $_no_auth_cache;
4006 print STDERR "Client certificate filename: ";
4007 STDERR->flush;
4008 chomp(my $filename = <STDIN>);
4009 $cred->cert_file($filename);
4010 $cred->may_save($may_save);
4011 $SVN::_Core::SVN_NO_ERROR;
4014 sub ssl_client_cert_pw {
4015 my ($cred, $realm, $may_save, $pool) = @_;
4016 $may_save = undef if $_no_auth_cache;
4017 $cred->password(_read_password("Password: ", $realm));
4018 $cred->may_save($may_save);
4019 $SVN::_Core::SVN_NO_ERROR;
4022 sub username {
4023 my ($cred, $realm, $may_save, $pool) = @_;
4024 $may_save = undef if $_no_auth_cache;
4025 if (defined $realm && length $realm) {
4026 print STDERR "Authentication realm: $realm\n";
4028 my $username;
4029 if (defined $_username) {
4030 $username = $_username;
4031 } else {
4032 print STDERR "Username: ";
4033 STDERR->flush;
4034 chomp($username = <STDIN>);
4036 $cred->username($username);
4037 $cred->may_save($may_save);
4038 $SVN::_Core::SVN_NO_ERROR;
4041 sub _read_password {
4042 my ($prompt, $realm) = @_;
4043 my $password = '';
4044 if (exists $ENV{GIT_ASKPASS}) {
4045 open(PH, "-|", $ENV{GIT_ASKPASS}, $prompt);
4046 $password = <PH>;
4047 $password =~ s/[\012\015]//; # \n\r
4048 close(PH);
4049 } else {
4050 print STDERR $prompt;
4051 STDERR->flush;
4052 require Term::ReadKey;
4053 Term::ReadKey::ReadMode('noecho');
4054 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
4055 last if $key =~ /[\012\015]/; # \n\r
4056 $password .= $key;
4058 Term::ReadKey::ReadMode('restore');
4059 print STDERR "\n";
4060 STDERR->flush;
4062 $password;
4065 package SVN::Git::Fetcher;
4066 use vars qw/@ISA/;
4067 use strict;
4068 use warnings;
4069 use Carp qw/croak/;
4070 use IO::File qw//;
4071 use vars qw/$_ignore_regex/;
4073 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
4074 sub new {
4075 my ($class, $git_svn, $switch_path) = @_;
4076 my $self = SVN::Delta::Editor->new;
4077 bless $self, $class;
4078 if (exists $git_svn->{last_commit}) {
4079 $self->{c} = $git_svn->{last_commit};
4080 $self->{empty_symlinks} =
4081 _mark_empty_symlinks($git_svn, $switch_path);
4083 $self->{ignore_regex} = eval { command_oneline('config', '--get',
4084 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
4085 $self->{empty} = {};
4086 $self->{dir_prop} = {};
4087 $self->{file_prop} = {};
4088 $self->{absent_dir} = {};
4089 $self->{absent_file} = {};
4090 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
4091 $self->{pathnameencoding} = Git::config('svn.pathnameencoding');
4092 $self;
4095 # this uses the Ra object, so it must be called before do_{switch,update},
4096 # not inside them (when the Git::SVN::Fetcher object is passed) to
4097 # do_{switch,update}
4098 sub _mark_empty_symlinks {
4099 my ($git_svn, $switch_path) = @_;
4100 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
4101 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
4103 my %ret;
4104 my ($rev, $cmt) = $git_svn->last_rev_commit;
4105 return {} unless ($rev && $cmt);
4107 # allow the warning to be printed for each revision we fetch to
4108 # ensure the user sees it. The user can also disable the workaround
4109 # on the repository even while git svn is running and the next
4110 # revision fetched will skip this expensive function.
4111 my $printed_warning;
4112 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
4113 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
4114 local $/ = "\0";
4115 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
4116 $pfx .= '/' if length($pfx);
4117 while (<$ls>) {
4118 chomp;
4119 s/\A100644 blob $empty_blob\t//o or next;
4120 unless ($printed_warning) {
4121 print STDERR "Scanning for empty symlinks, ",
4122 "this may take a while if you have ",
4123 "many empty files\n",
4124 "You may disable this with `",
4125 "git config svn.brokenSymlinkWorkaround ",
4126 "false'.\n",
4127 "This may be done in a different ",
4128 "terminal without restarting ",
4129 "git svn\n";
4130 $printed_warning = 1;
4132 my $path = $_;
4133 my (undef, $props) =
4134 $git_svn->ra->get_file($pfx.$path, $rev, undef);
4135 if ($props->{'svn:special'}) {
4136 $ret{$path} = 1;
4139 command_close_pipe($ls, $ctx);
4140 \%ret;
4143 # returns true if a given path is inside a ".git" directory
4144 sub in_dot_git {
4145 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
4148 # return value: 0 -- don't ignore, 1 -- ignore
4149 sub is_path_ignored {
4150 my ($self, $path) = @_;
4151 return 1 if in_dot_git($path);
4152 return 1 if defined($self->{ignore_regex}) &&
4153 $path =~ m!$self->{ignore_regex}!;
4154 return 0 unless defined($_ignore_regex);
4155 return 1 if $path =~ m!$_ignore_regex!o;
4156 return 0;
4159 sub set_path_strip {
4160 my ($self, $path) = @_;
4161 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
4164 sub open_root {
4165 { path => '' };
4168 sub open_directory {
4169 my ($self, $path, $pb, $rev) = @_;
4170 { path => $path };
4173 sub git_path {
4174 my ($self, $path) = @_;
4175 if (my $enc = $self->{pathnameencoding}) {
4176 require Encode;
4177 Encode::from_to($path, 'UTF-8', $enc);
4179 if ($self->{path_strip}) {
4180 $path =~ s!$self->{path_strip}!! or
4181 die "Failed to strip path '$path' ($self->{path_strip})\n";
4183 $path;
4186 sub delete_entry {
4187 my ($self, $path, $rev, $pb) = @_;
4188 return undef if $self->is_path_ignored($path);
4190 my $gpath = $self->git_path($path);
4191 return undef if ($gpath eq '');
4193 # remove entire directories.
4194 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4195 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
4196 if ($tree) {
4197 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4198 -r --name-only -z/,
4199 $tree);
4200 local $/ = "\0";
4201 while (<$ls>) {
4202 chomp;
4203 my $rmpath = "$gpath/$_";
4204 $self->{gii}->remove($rmpath);
4205 print "\tD\t$rmpath\n" unless $::_q;
4207 print "\tD\t$gpath/\n" unless $::_q;
4208 command_close_pipe($ls, $ctx);
4209 } else {
4210 $self->{gii}->remove($gpath);
4211 print "\tD\t$gpath\n" unless $::_q;
4213 $self->{empty}->{$path} = 0;
4214 undef;
4217 sub open_file {
4218 my ($self, $path, $pb, $rev) = @_;
4219 my ($mode, $blob);
4221 goto out if $self->is_path_ignored($path);
4223 my $gpath = $self->git_path($path);
4224 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
4225 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
4226 unless (defined $mode && defined $blob) {
4227 die "$path was not found in commit $self->{c} (r$rev)\n";
4229 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
4230 $mode = '120000';
4232 out:
4233 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
4234 pool => SVN::Pool->new, action => 'M' };
4237 sub add_file {
4238 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
4239 my $mode;
4241 if (!$self->is_path_ignored($path)) {
4242 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4243 delete $self->{empty}->{$dir};
4244 $mode = '100644';
4246 { path => $path, mode_a => $mode, mode_b => $mode,
4247 pool => SVN::Pool->new, action => 'A' };
4250 sub add_directory {
4251 my ($self, $path, $cp_path, $cp_rev) = @_;
4252 goto out if $self->is_path_ignored($path);
4253 my $gpath = $self->git_path($path);
4254 if ($gpath eq '') {
4255 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
4256 -r --name-only -z/,
4257 $self->{c});
4258 local $/ = "\0";
4259 while (<$ls>) {
4260 chomp;
4261 $self->{gii}->remove($_);
4262 print "\tD\t$_\n" unless $::_q;
4264 command_close_pipe($ls, $ctx);
4265 $self->{empty}->{$path} = 0;
4267 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
4268 delete $self->{empty}->{$dir};
4269 $self->{empty}->{$path} = 1;
4270 out:
4271 { path => $path };
4274 sub change_dir_prop {
4275 my ($self, $db, $prop, $value) = @_;
4276 return undef if $self->is_path_ignored($db->{path});
4277 $self->{dir_prop}->{$db->{path}} ||= {};
4278 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
4279 undef;
4282 sub absent_directory {
4283 my ($self, $path, $pb) = @_;
4284 return undef if $self->is_path_ignored($path);
4285 $self->{absent_dir}->{$pb->{path}} ||= [];
4286 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
4287 undef;
4290 sub absent_file {
4291 my ($self, $path, $pb) = @_;
4292 return undef if $self->is_path_ignored($path);
4293 $self->{absent_file}->{$pb->{path}} ||= [];
4294 push @{$self->{absent_file}->{$pb->{path}}}, $path;
4295 undef;
4298 sub change_file_prop {
4299 my ($self, $fb, $prop, $value) = @_;
4300 return undef if $self->is_path_ignored($fb->{path});
4301 if ($prop eq 'svn:executable') {
4302 if ($fb->{mode_b} != 120000) {
4303 $fb->{mode_b} = defined $value ? 100755 : 100644;
4305 } elsif ($prop eq 'svn:special') {
4306 $fb->{mode_b} = defined $value ? 120000 : 100644;
4307 } else {
4308 $self->{file_prop}->{$fb->{path}} ||= {};
4309 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
4311 undef;
4314 sub apply_textdelta {
4315 my ($self, $fb, $exp) = @_;
4316 return undef if $self->is_path_ignored($fb->{path});
4317 my $fh = $::_repository->temp_acquire('svn_delta');
4318 # $fh gets auto-closed() by SVN::TxDelta::apply(),
4319 # (but $base does not,) so dup() it for reading in close_file
4320 open my $dup, '<&', $fh or croak $!;
4321 my $base = $::_repository->temp_acquire('git_blob');
4323 if ($fb->{blob}) {
4324 my ($base_is_link, $size);
4326 if ($fb->{mode_a} eq '120000' &&
4327 ! $self->{empty_symlinks}->{$fb->{path}}) {
4328 print $base 'link ' or die "print $!\n";
4329 $base_is_link = 1;
4331 retry:
4332 $size = $::_repository->cat_blob($fb->{blob}, $base);
4333 die "Failed to read object $fb->{blob}" if ($size < 0);
4335 if (defined $exp) {
4336 seek $base, 0, 0 or croak $!;
4337 my $got = ::md5sum($base);
4338 if ($got ne $exp) {
4339 my $err = "Checksum mismatch: ".
4340 "$fb->{path} $fb->{blob}\n" .
4341 "expected: $exp\n" .
4342 " got: $got\n";
4343 if ($base_is_link) {
4344 warn $err,
4345 "Retrying... (possibly ",
4346 "a bad symlink from SVN)\n";
4347 $::_repository->temp_reset($base);
4348 $base_is_link = 0;
4349 goto retry;
4351 die $err;
4355 seek $base, 0, 0 or croak $!;
4356 $fb->{fh} = $fh;
4357 $fb->{base} = $base;
4358 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
4361 sub close_file {
4362 my ($self, $fb, $exp) = @_;
4363 return undef if $self->is_path_ignored($fb->{path});
4365 my $hash;
4366 my $path = $self->git_path($fb->{path});
4367 if (my $fh = $fb->{fh}) {
4368 if (defined $exp) {
4369 seek($fh, 0, 0) or croak $!;
4370 my $got = ::md5sum($fh);
4371 if ($got ne $exp) {
4372 die "Checksum mismatch: $path\n",
4373 "expected: $exp\n got: $got\n";
4376 if ($fb->{mode_b} == 120000) {
4377 sysseek($fh, 0, 0) or croak $!;
4378 my $rd = sysread($fh, my $buf, 5);
4380 if (!defined $rd) {
4381 croak "sysread: $!\n";
4382 } elsif ($rd == 0) {
4383 warn "$path has mode 120000",
4384 " but it points to nothing\n",
4385 "converting to an empty file with mode",
4386 " 100644\n";
4387 $fb->{mode_b} = '100644';
4388 } elsif ($buf ne 'link ') {
4389 warn "$path has mode 120000",
4390 " but is not a link\n";
4391 } else {
4392 my $tmp_fh = $::_repository->temp_acquire(
4393 'svn_hash');
4394 my $res;
4395 while ($res = sysread($fh, my $str, 1024)) {
4396 my $out = syswrite($tmp_fh, $str, $res);
4397 defined($out) && $out == $res
4398 or croak("write ",
4399 Git::temp_path($tmp_fh),
4400 ": $!\n");
4402 defined $res or croak $!;
4404 ($fh, $tmp_fh) = ($tmp_fh, $fh);
4405 Git::temp_release($tmp_fh, 1);
4409 $hash = $::_repository->hash_and_insert_object(
4410 Git::temp_path($fh));
4411 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
4413 Git::temp_release($fb->{base}, 1);
4414 Git::temp_release($fh, 1);
4415 } else {
4416 $hash = $fb->{blob} or die "no blob information\n";
4418 $fb->{pool}->clear;
4419 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
4420 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
4421 undef;
4424 sub abort_edit {
4425 my $self = shift;
4426 $self->{nr} = $self->{gii}->{nr};
4427 delete $self->{gii};
4428 $self->SUPER::abort_edit(@_);
4431 sub close_edit {
4432 my $self = shift;
4433 $self->{git_commit_ok} = 1;
4434 $self->{nr} = $self->{gii}->{nr};
4435 delete $self->{gii};
4436 $self->SUPER::close_edit(@_);
4439 package SVN::Git::Editor;
4440 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
4441 use strict;
4442 use warnings;
4443 use Carp qw/croak/;
4444 use IO::File;
4446 sub new {
4447 my ($class, $opts) = @_;
4448 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
4449 die "$_ required!\n" unless (defined $opts->{$_});
4452 my $pool = SVN::Pool->new;
4453 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
4454 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
4455 $opts->{r}, $mods);
4457 # $opts->{ra} functions should not be used after this:
4458 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
4459 $opts->{editor_cb}, $pool);
4460 my $self = SVN::Delta::Editor->new(@ce, $pool);
4461 bless $self, $class;
4462 foreach (qw/svn_path r tree_a tree_b/) {
4463 $self->{$_} = $opts->{$_};
4465 $self->{url} = $opts->{ra}->{url};
4466 $self->{mods} = $mods;
4467 $self->{types} = $types;
4468 $self->{pool} = $pool;
4469 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
4470 $self->{rm} = { };
4471 $self->{path_prefix} = length $self->{svn_path} ?
4472 "$self->{svn_path}/" : '';
4473 $self->{config} = $opts->{config};
4474 $self->{mergeinfo} = $opts->{mergeinfo};
4475 return $self;
4478 sub generate_diff {
4479 my ($tree_a, $tree_b) = @_;
4480 my @diff_tree = qw(diff-tree -z -r);
4481 if ($_cp_similarity) {
4482 push @diff_tree, "-C$_cp_similarity";
4483 } else {
4484 push @diff_tree, '-C';
4486 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
4487 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
4488 push @diff_tree, $tree_a, $tree_b;
4489 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
4490 local $/ = "\0";
4491 my $state = 'meta';
4492 my @mods;
4493 while (<$diff_fh>) {
4494 chomp $_; # this gets rid of the trailing "\0"
4495 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
4496 ($::sha1)\s($::sha1)\s
4497 ([MTCRAD])\d*$/xo) {
4498 push @mods, { mode_a => $1, mode_b => $2,
4499 sha1_a => $3, sha1_b => $4,
4500 chg => $5 };
4501 if ($5 =~ /^(?:C|R)$/) {
4502 $state = 'file_a';
4503 } else {
4504 $state = 'file_b';
4506 } elsif ($state eq 'file_a') {
4507 my $x = $mods[$#mods] or croak "Empty array\n";
4508 if ($x->{chg} !~ /^(?:C|R)$/) {
4509 croak "Error parsing $_, $x->{chg}\n";
4511 $x->{file_a} = $_;
4512 $state = 'file_b';
4513 } elsif ($state eq 'file_b') {
4514 my $x = $mods[$#mods] or croak "Empty array\n";
4515 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
4516 croak "Error parsing $_, $x->{chg}\n";
4518 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
4519 croak "Error parsing $_, $x->{chg}\n";
4521 $x->{file_b} = $_;
4522 $state = 'meta';
4523 } else {
4524 croak "Error parsing $_\n";
4527 command_close_pipe($diff_fh, $ctx);
4528 \@mods;
4531 sub check_diff_paths {
4532 my ($ra, $pfx, $rev, $mods) = @_;
4533 my %types;
4534 $pfx .= '/' if length $pfx;
4536 sub type_diff_paths {
4537 my ($ra, $types, $path, $rev) = @_;
4538 my @p = split m#/+#, $path;
4539 my $c = shift @p;
4540 unless (defined $types->{$c}) {
4541 $types->{$c} = $ra->check_path($c, $rev);
4543 while (@p) {
4544 $c .= '/' . shift @p;
4545 next if defined $types->{$c};
4546 $types->{$c} = $ra->check_path($c, $rev);
4550 foreach my $m (@$mods) {
4551 foreach my $f (qw/file_a file_b/) {
4552 next unless defined $m->{$f};
4553 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
4554 if (length $pfx.$dir && ! defined $types{$dir}) {
4555 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
4559 \%types;
4562 sub split_path {
4563 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
4566 sub repo_path {
4567 my ($self, $path) = @_;
4568 if (my $enc = $self->{pathnameencoding}) {
4569 require Encode;
4570 Encode::from_to($path, $enc, 'UTF-8');
4572 $self->{path_prefix}.(defined $path ? $path : '');
4575 sub url_path {
4576 my ($self, $path) = @_;
4577 if ($self->{url} =~ m#^https?://#) {
4578 $path =~ s!([^~a-zA-Z0-9_./-])!uc sprintf("%%%02x",ord($1))!eg;
4580 $self->{url} . '/' . $self->repo_path($path);
4583 sub rmdirs {
4584 my ($self) = @_;
4585 my $rm = $self->{rm};
4586 delete $rm->{''}; # we never delete the url we're tracking
4587 return unless %$rm;
4589 foreach (keys %$rm) {
4590 my @d = split m#/#, $_;
4591 my $c = shift @d;
4592 $rm->{$c} = 1;
4593 while (@d) {
4594 $c .= '/' . shift @d;
4595 $rm->{$c} = 1;
4598 delete $rm->{$self->{svn_path}};
4599 delete $rm->{''}; # we never delete the url we're tracking
4600 return unless %$rm;
4602 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
4603 $self->{tree_b});
4604 local $/ = "\0";
4605 while (<$fh>) {
4606 chomp;
4607 my @dn = split m#/#, $_;
4608 while (pop @dn) {
4609 delete $rm->{join '/', @dn};
4611 unless (%$rm) {
4612 close $fh;
4613 return;
4616 command_close_pipe($fh, $ctx);
4618 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
4619 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
4620 $self->close_directory($bat->{$d}, $p);
4621 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
4622 print "\tD+\t$d/\n" unless $::_q;
4623 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
4624 delete $bat->{$d};
4628 sub open_or_add_dir {
4629 my ($self, $full_path, $baton) = @_;
4630 my $t = $self->{types}->{$full_path};
4631 if (!defined $t) {
4632 die "$full_path not known in r$self->{r} or we have a bug!\n";
4635 no warnings 'once';
4636 # SVN::Node::none and SVN::Node::file are used only once,
4637 # so we're shutting up Perl's warnings about them.
4638 if ($t == $SVN::Node::none) {
4639 return $self->add_directory($full_path, $baton,
4640 undef, -1, $self->{pool});
4641 } elsif ($t == $SVN::Node::dir) {
4642 return $self->open_directory($full_path, $baton,
4643 $self->{r}, $self->{pool});
4644 } # no warnings 'once'
4645 print STDERR "$full_path already exists in repository at ",
4646 "r$self->{r} and it is not a directory (",
4647 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
4648 } # no warnings 'once'
4649 exit 1;
4652 sub ensure_path {
4653 my ($self, $path) = @_;
4654 my $bat = $self->{bat};
4655 my $repo_path = $self->repo_path($path);
4656 return $bat->{''} unless (length $repo_path);
4657 my @p = split m#/+#, $repo_path;
4658 my $c = shift @p;
4659 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
4660 while (@p) {
4661 my $c0 = $c;
4662 $c .= '/' . shift @p;
4663 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
4665 return $bat->{$c};
4668 # Subroutine to convert a globbing pattern to a regular expression.
4669 # From perl cookbook.
4670 sub glob2pat {
4671 my $globstr = shift;
4672 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
4673 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
4674 return '^' . $globstr . '$';
4677 sub check_autoprop {
4678 my ($self, $pattern, $properties, $file, $fbat) = @_;
4679 # Convert the globbing pattern to a regular expression.
4680 my $regex = glob2pat($pattern);
4681 # Check if the pattern matches the file name.
4682 if($file =~ m/($regex)/) {
4683 # Parse the list of properties to set.
4684 my @props = split(/;/, $properties);
4685 foreach my $prop (@props) {
4686 # Parse 'name=value' syntax and set the property.
4687 if ($prop =~ /([^=]+)=(.*)/) {
4688 my ($n,$v) = ($1,$2);
4689 for ($n, $v) {
4690 s/^\s+//; s/\s+$//;
4692 $self->change_file_prop($fbat, $n, $v);
4698 sub apply_autoprops {
4699 my ($self, $file, $fbat) = @_;
4700 my $conf_t = ${$self->{config}}{'config'};
4701 no warnings 'once';
4702 # Check [miscellany]/enable-auto-props in svn configuration.
4703 if (SVN::_Core::svn_config_get_bool(
4704 $conf_t,
4705 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4706 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4707 0)) {
4708 # Auto-props are enabled. Enumerate them to look for matches.
4709 my $callback = sub {
4710 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4712 SVN::_Core::svn_config_enumerate(
4713 $conf_t,
4714 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4715 $callback);
4719 sub A {
4720 my ($self, $m) = @_;
4721 my ($dir, $file) = split_path($m->{file_b});
4722 my $pbat = $self->ensure_path($dir);
4723 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4724 undef, -1);
4725 print "\tA\t$m->{file_b}\n" unless $::_q;
4726 $self->apply_autoprops($file, $fbat);
4727 $self->chg_file($fbat, $m);
4728 $self->close_file($fbat,undef,$self->{pool});
4731 sub C {
4732 my ($self, $m) = @_;
4733 my ($dir, $file) = split_path($m->{file_b});
4734 my $pbat = $self->ensure_path($dir);
4735 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4736 $self->url_path($m->{file_a}), $self->{r});
4737 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4738 $self->chg_file($fbat, $m);
4739 $self->close_file($fbat,undef,$self->{pool});
4742 sub delete_entry {
4743 my ($self, $path, $pbat) = @_;
4744 my $rpath = $self->repo_path($path);
4745 my ($dir, $file) = split_path($rpath);
4746 $self->{rm}->{$dir} = 1;
4747 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4750 sub R {
4751 my ($self, $m) = @_;
4752 my ($dir, $file) = split_path($m->{file_b});
4753 my $pbat = $self->ensure_path($dir);
4754 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4755 $self->url_path($m->{file_a}), $self->{r});
4756 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4757 $self->apply_autoprops($file, $fbat);
4758 $self->chg_file($fbat, $m);
4759 $self->close_file($fbat,undef,$self->{pool});
4761 ($dir, $file) = split_path($m->{file_a});
4762 $pbat = $self->ensure_path($dir);
4763 $self->delete_entry($m->{file_a}, $pbat);
4766 sub M {
4767 my ($self, $m) = @_;
4768 my ($dir, $file) = split_path($m->{file_b});
4769 my $pbat = $self->ensure_path($dir);
4770 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4771 $pbat,$self->{r},$self->{pool});
4772 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4773 $self->chg_file($fbat, $m);
4774 $self->close_file($fbat,undef,$self->{pool});
4777 sub T { shift->M(@_) }
4779 sub change_file_prop {
4780 my ($self, $fbat, $pname, $pval) = @_;
4781 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4784 sub change_dir_prop {
4785 my ($self, $pbat, $pname, $pval) = @_;
4786 $self->SUPER::change_dir_prop($pbat, $pname, $pval, $self->{pool});
4789 sub _chg_file_get_blob ($$$$) {
4790 my ($self, $fbat, $m, $which) = @_;
4791 my $fh = $::_repository->temp_acquire("git_blob_$which");
4792 if ($m->{"mode_$which"} =~ /^120/) {
4793 print $fh 'link ' or croak $!;
4794 $self->change_file_prop($fbat,'svn:special','*');
4795 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4796 $self->change_file_prop($fbat,'svn:special',undef);
4798 my $blob = $m->{"sha1_$which"};
4799 return ($fh,) if ($blob =~ /^0{40}$/);
4800 my $size = $::_repository->cat_blob($blob, $fh);
4801 croak "Failed to read object $blob" if ($size < 0);
4802 $fh->flush == 0 or croak $!;
4803 seek $fh, 0, 0 or croak $!;
4805 my $exp = ::md5sum($fh);
4806 seek $fh, 0, 0 or croak $!;
4807 return ($fh, $exp);
4810 sub chg_file {
4811 my ($self, $fbat, $m) = @_;
4812 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4813 $self->change_file_prop($fbat,'svn:executable','*');
4814 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4815 $self->change_file_prop($fbat,'svn:executable',undef);
4817 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4818 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4819 my $pool = SVN::Pool->new;
4820 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4821 if (-s $fh_a) {
4822 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4823 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4824 if (defined $res) {
4825 die "Unexpected result from send_txstream: $res\n",
4826 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4828 } else {
4829 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4830 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4831 if ($got ne $exp_b);
4833 Git::temp_release($fh_b, 1);
4834 Git::temp_release($fh_a, 1);
4835 $pool->clear;
4838 sub D {
4839 my ($self, $m) = @_;
4840 my ($dir, $file) = split_path($m->{file_b});
4841 my $pbat = $self->ensure_path($dir);
4842 print "\tD\t$m->{file_b}\n" unless $::_q;
4843 $self->delete_entry($m->{file_b}, $pbat);
4846 sub close_edit {
4847 my ($self) = @_;
4848 my ($p,$bat) = ($self->{pool}, $self->{bat});
4849 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4850 next if $_ eq '';
4851 $self->close_directory($bat->{$_}, $p);
4853 $self->close_directory($bat->{''}, $p);
4854 $self->SUPER::close_edit($p);
4855 $p->clear;
4858 sub abort_edit {
4859 my ($self) = @_;
4860 $self->SUPER::abort_edit($self->{pool});
4863 sub DESTROY {
4864 my $self = shift;
4865 $self->SUPER::DESTROY(@_);
4866 $self->{pool}->clear;
4869 # this drives the editor
4870 sub apply_diff {
4871 my ($self) = @_;
4872 my $mods = $self->{mods};
4873 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4874 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4875 my $f = $m->{chg};
4876 if (defined $o{$f}) {
4877 $self->$f($m);
4878 } else {
4879 fatal("Invalid change type: $f");
4883 if (defined($self->{mergeinfo})) {
4884 $self->change_dir_prop($self->{bat}{''}, "svn:mergeinfo",
4885 $self->{mergeinfo});
4887 $self->rmdirs if $_rmdir;
4888 if (@$mods == 0) {
4889 $self->abort_edit;
4890 } else {
4891 $self->close_edit;
4893 return scalar @$mods;
4896 package Git::SVN::Ra;
4897 use vars qw/@ISA $config_dir $_log_window_size/;
4898 use strict;
4899 use warnings;
4900 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4902 BEGIN {
4903 # enforce temporary pool usage for some simple functions
4904 no strict 'refs';
4905 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4906 get_file/) {
4907 my $SUPER = "SUPER::$f";
4908 *$f = sub {
4909 my $self = shift;
4910 my $pool = SVN::Pool->new;
4911 my @ret = $self->$SUPER(@_,$pool);
4912 $pool->clear;
4913 wantarray ? @ret : $ret[0];
4918 sub _auth_providers () {
4920 SVN::Client::get_simple_provider(),
4921 SVN::Client::get_ssl_server_trust_file_provider(),
4922 SVN::Client::get_simple_prompt_provider(
4923 \&Git::SVN::Prompt::simple, 2),
4924 SVN::Client::get_ssl_client_cert_file_provider(),
4925 SVN::Client::get_ssl_client_cert_prompt_provider(
4926 \&Git::SVN::Prompt::ssl_client_cert, 2),
4927 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4928 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4929 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4930 SVN::Client::get_username_provider(),
4931 SVN::Client::get_ssl_server_trust_prompt_provider(
4932 \&Git::SVN::Prompt::ssl_server_trust),
4933 SVN::Client::get_username_prompt_provider(
4934 \&Git::SVN::Prompt::username, 2)
4938 sub escape_uri_only {
4939 my ($uri) = @_;
4940 my @tmp;
4941 foreach (split m{/}, $uri) {
4942 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4943 push @tmp, $_;
4945 join('/', @tmp);
4948 sub escape_url {
4949 my ($url) = @_;
4950 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4951 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4952 $url = "$scheme://$domain$uri";
4954 $url;
4957 sub new {
4958 my ($class, $url) = @_;
4959 $url =~ s!/+$!!;
4960 return $RA if ($RA && $RA->{url} eq $url);
4962 ::_req_svn();
4964 SVN::_Core::svn_config_ensure($config_dir, undef);
4965 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4966 my $config = SVN::Core::config_get_config($config_dir);
4967 $RA = undef;
4968 my $dont_store_passwords = 1;
4969 my $conf_t = ${$config}{'config'};
4971 no warnings 'once';
4972 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4973 # produces warnings that variables are used only once.
4974 # I had not found the better way to shut them up, so
4975 # the warnings of type 'once' are disabled in this block.
4976 if (SVN::_Core::svn_config_get_bool($conf_t,
4977 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4978 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4979 1) == 0) {
4980 SVN::_Core::svn_auth_set_parameter($baton,
4981 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4982 bless (\$dont_store_passwords, "_p_void"));
4984 if (SVN::_Core::svn_config_get_bool($conf_t,
4985 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4986 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4987 1) == 0) {
4988 $Git::SVN::Prompt::_no_auth_cache = 1;
4990 } # no warnings 'once'
4991 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4992 config => $config,
4993 pool => SVN::Pool->new,
4994 auth_provider_callbacks => $callbacks);
4995 $self->{url} = $url;
4996 $self->{svn_path} = $url;
4997 $self->{repos_root} = $self->get_repos_root;
4998 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4999 $self->{cache} = { check_path => { r => 0, data => {} },
5000 get_dir => { r => 0, data => {} } };
5001 $RA = bless $self, $class;
5004 sub check_path {
5005 my ($self, $path, $r) = @_;
5006 my $cache = $self->{cache}->{check_path};
5007 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
5008 return $cache->{data}->{$path};
5010 my $pool = SVN::Pool->new;
5011 my $t = $self->SUPER::check_path($path, $r, $pool);
5012 $pool->clear;
5013 if ($r != $cache->{r}) {
5014 %{$cache->{data}} = ();
5015 $cache->{r} = $r;
5017 $cache->{data}->{$path} = $t;
5020 sub get_dir {
5021 my ($self, $dir, $r) = @_;
5022 my $cache = $self->{cache}->{get_dir};
5023 if ($r == $cache->{r}) {
5024 if (my $x = $cache->{data}->{$dir}) {
5025 return wantarray ? @$x : $x->[0];
5028 my $pool = SVN::Pool->new;
5029 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
5030 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
5031 $pool->clear;
5032 if ($r != $cache->{r}) {
5033 %{$cache->{data}} = ();
5034 $cache->{r} = $r;
5036 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
5037 wantarray ? (\%dirents, $r, $props) : \%dirents;
5040 sub DESTROY {
5041 # do not call the real DESTROY since we store ourselves in $RA
5044 # get_log(paths, start, end, limit,
5045 # discover_changed_paths, strict_node_history, receiver)
5046 sub get_log {
5047 my ($self, @args) = @_;
5048 my $pool = SVN::Pool->new;
5050 # svn_log_changed_path_t objects passed to get_log are likely to be
5051 # overwritten even if only the refs are copied to an external variable,
5052 # so we should dup the structures in their entirety. Using an
5053 # externally passed pool (instead of our temporary and quickly cleared
5054 # pool in Git::SVN::Ra) does not help matters at all...
5055 my $receiver = pop @args;
5056 my $prefix = "/".$self->{svn_path};
5057 $prefix =~ s#/+($)##;
5058 my $prefix_regex = qr#^\Q$prefix\E#;
5059 push(@args, sub {
5060 my ($paths) = $_[0];
5061 return &$receiver(@_) unless $paths;
5062 $_[0] = ();
5063 foreach my $p (keys %$paths) {
5064 my $i = $paths->{$p};
5065 # Make path relative to our url, not repos_root
5066 $p =~ s/$prefix_regex//;
5067 my %s = map { $_ => $i->$_; }
5068 qw/copyfrom_path copyfrom_rev action/;
5069 if ($s{'copyfrom_path'}) {
5070 $s{'copyfrom_path'} =~ s/$prefix_regex//;
5072 $_[0]{$p} = \%s;
5074 &$receiver(@_);
5078 # the limit parameter was not supported in SVN 1.1.x, so we
5079 # drop it. Therefore, the receiver callback passed to it
5080 # is made aware of this limitation by being wrapped if
5081 # the limit passed to is being wrapped.
5082 if ($SVN::Core::VERSION le '1.2.0') {
5083 my $limit = splice(@args, 3, 1);
5084 if ($limit > 0) {
5085 my $receiver = pop @args;
5086 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
5089 my $ret = $self->SUPER::get_log(@args, $pool);
5090 $pool->clear;
5091 $ret;
5094 sub trees_match {
5095 my ($self, $url1, $rev1, $url2, $rev2) = @_;
5096 my $ctx = SVN::Client->new(auth => _auth_providers);
5097 my $out = IO::File->new_tmpfile;
5099 # older SVN (1.1.x) doesn't take $pool as the last parameter for
5100 # $ctx->diff(), so we'll create a default one
5101 my $pool = SVN::Pool->new_default_sub;
5103 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
5104 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
5105 $out->flush;
5106 my $ret = (($out->stat)[7] == 0);
5107 close $out or croak $!;
5109 $ret;
5112 sub get_commit_editor {
5113 my ($self, $log, $cb, $pool) = @_;
5114 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
5115 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
5118 sub gs_do_update {
5119 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
5120 my $new = ($rev_a == $rev_b);
5121 my $path = $gs->{path};
5123 if ($new && -e $gs->{index}) {
5124 unlink $gs->{index} or die
5125 "Couldn't unlink index: $gs->{index}: $!\n";
5127 my $pool = SVN::Pool->new;
5128 $editor->set_path_strip($path);
5129 my (@pc) = split m#/#, $path;
5130 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
5131 1, $editor, $pool);
5132 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5134 # Since we can't rely on svn_ra_reparent being available, we'll
5135 # just have to do some magic with set_path to make it so
5136 # we only want a partial path.
5137 my $sp = '';
5138 my $final = join('/', @pc);
5139 while (@pc) {
5140 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
5141 $sp .= '/' if length $sp;
5142 $sp .= shift @pc;
5144 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
5146 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
5148 $reporter->finish_report($pool);
5149 $pool->clear;
5150 $editor->{git_commit_ok};
5153 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
5154 # svn_ra_reparent didn't work before 1.4)
5155 sub gs_do_switch {
5156 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
5157 my $path = $gs->{path};
5158 my $pool = SVN::Pool->new;
5160 my $full_url = $self->{url};
5161 my $old_url = $full_url;
5162 $full_url .= '/' . $path if length $path;
5163 my ($ra, $reparented);
5165 if ($old_url =~ m#^svn(\+ssh)?://# ||
5166 ($full_url =~ m#^https?://# &&
5167 escape_url($full_url) ne $full_url)) {
5168 $_[0] = undef;
5169 $self = undef;
5170 $RA = undef;
5171 $ra = Git::SVN::Ra->new($full_url);
5172 $ra_invalid = 1;
5173 } elsif ($old_url ne $full_url) {
5174 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
5175 $self->{url} = $full_url;
5176 $reparented = 1;
5179 $ra ||= $self;
5180 $url_b = escape_url($url_b);
5181 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
5182 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
5183 $reporter->set_path('', $rev_a, 0, @lock, $pool);
5184 $reporter->finish_report($pool);
5186 if ($reparented) {
5187 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
5188 $self->{url} = $old_url;
5191 $pool->clear;
5192 $editor->{git_commit_ok};
5195 sub longest_common_path {
5196 my ($gsv, $globs) = @_;
5197 my %common;
5198 my $common_max = scalar @$gsv;
5200 foreach my $gs (@$gsv) {
5201 my @tmp = split m#/#, $gs->{path};
5202 my $p = '';
5203 foreach (@tmp) {
5204 $p .= length($p) ? "/$_" : $_;
5205 $common{$p} ||= 0;
5206 $common{$p}++;
5209 $globs ||= [];
5210 $common_max += scalar @$globs;
5211 foreach my $glob (@$globs) {
5212 my @tmp = split m#/#, $glob->{path}->{left};
5213 my $p = '';
5214 foreach (@tmp) {
5215 $p .= length($p) ? "/$_" : $_;
5216 $common{$p} ||= 0;
5217 $common{$p}++;
5221 my $longest_path = '';
5222 foreach (sort {length $b <=> length $a} keys %common) {
5223 if ($common{$_} == $common_max) {
5224 $longest_path = $_;
5225 last;
5228 $longest_path;
5231 sub gs_fetch_loop_common {
5232 my ($self, $base, $head, $gsv, $globs) = @_;
5233 return if ($base > $head);
5234 my $inc = $_log_window_size;
5235 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
5236 my $longest_path = longest_common_path($gsv, $globs);
5237 my $ra_url = $self->{url};
5238 my $find_trailing_edge;
5239 while (1) {
5240 my %revs;
5241 my $err;
5242 my $err_handler = $SVN::Error::handler;
5243 $SVN::Error::handler = sub {
5244 ($err) = @_;
5245 skip_unknown_revs($err);
5247 sub _cb {
5248 my ($paths, $r, $author, $date, $log) = @_;
5249 [ $paths,
5250 { author => $author, date => $date, log => $log } ];
5252 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
5253 sub { $revs{$_[1]} = _cb(@_) });
5254 if ($err) {
5255 print "Checked through r$max\r";
5256 } else {
5257 $find_trailing_edge = 1;
5259 if ($err and $find_trailing_edge) {
5260 print STDERR "Path '$longest_path' ",
5261 "was probably deleted:\n",
5262 $err->expanded_message,
5263 "\nWill attempt to follow ",
5264 "revisions r$min .. r$max ",
5265 "committed before the deletion\n";
5266 my $hi = $max;
5267 while (--$hi >= $min) {
5268 my $ok;
5269 $self->get_log([$longest_path], $min, $hi,
5270 0, 1, 1, sub {
5271 $ok = $_[1];
5272 $revs{$_[1]} = _cb(@_) });
5273 if ($ok) {
5274 print STDERR "r$min .. r$ok OK\n";
5275 last;
5278 $find_trailing_edge = 0;
5280 $SVN::Error::handler = $err_handler;
5282 my %exists = map { $_->{path} => $_ } @$gsv;
5283 foreach my $r (sort {$a <=> $b} keys %revs) {
5284 my ($paths, $logged) = @{$revs{$r}};
5286 foreach my $gs ($self->match_globs(\%exists, $paths,
5287 $globs, $r)) {
5288 if ($gs->rev_map_max >= $r) {
5289 next;
5291 next unless $gs->match_paths($paths, $r);
5292 $gs->{logged_rev_props} = $logged;
5293 if (my $last_commit = $gs->last_commit) {
5294 $gs->assert_index_clean($last_commit);
5296 my $log_entry = $gs->do_fetch($paths, $r);
5297 if ($log_entry) {
5298 $gs->do_git_commit($log_entry);
5300 $INDEX_FILES{$gs->{index}} = 1;
5302 foreach my $g (@$globs) {
5303 my $k = "svn-remote.$g->{remote}." .
5304 "$g->{t}-maxRev";
5305 Git::SVN::tmp_config($k, $r);
5307 if ($ra_invalid) {
5308 $_[0] = undef;
5309 $self = undef;
5310 $RA = undef;
5311 $self = Git::SVN::Ra->new($ra_url);
5312 $ra_invalid = undef;
5315 # pre-fill the .rev_db since it'll eventually get filled in
5316 # with '0' x40 if something new gets committed
5317 foreach my $gs (@$gsv) {
5318 next if $gs->rev_map_max >= $max;
5319 next if defined $gs->rev_map_get($max);
5320 $gs->rev_map_set($max, 0 x40);
5322 foreach my $g (@$globs) {
5323 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
5324 Git::SVN::tmp_config($k, $max);
5326 last if $max >= $head;
5327 $min = $max + 1;
5328 $max += $inc;
5329 $max = $head if ($max > $head);
5331 Git::SVN::gc();
5334 sub get_dir_globbed {
5335 my ($self, $left, $depth, $r) = @_;
5337 my @x = eval { $self->get_dir($left, $r) };
5338 return unless scalar @x == 3;
5339 my $dirents = $x[0];
5340 my @finalents;
5341 foreach my $de (keys %$dirents) {
5342 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
5343 if ($depth > 1) {
5344 my @args = ("$left/$de", $depth - 1, $r);
5345 foreach my $dir ($self->get_dir_globbed(@args)) {
5346 push @finalents, "$de/$dir";
5348 } else {
5349 push @finalents, $de;
5352 @finalents;
5355 sub match_globs {
5356 my ($self, $exists, $paths, $globs, $r) = @_;
5358 sub get_dir_check {
5359 my ($self, $exists, $g, $r) = @_;
5361 my @dirs = $self->get_dir_globbed($g->{path}->{left},
5362 $g->{path}->{depth},
5363 $r);
5365 foreach my $de (@dirs) {
5366 my $p = $g->{path}->full_path($de);
5367 next if $exists->{$p};
5368 next if (length $g->{path}->{right} &&
5369 ($self->check_path($p, $r) !=
5370 $SVN::Node::dir));
5371 next unless $p =~ /$g->{path}->{regex}/;
5372 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
5373 $g->{ref}->full_path($de), 1);
5376 foreach my $g (@$globs) {
5377 if (my $path = $paths->{"/$g->{path}->{left}"}) {
5378 if ($path->{action} =~ /^[AR]$/) {
5379 get_dir_check($self, $exists, $g, $r);
5382 foreach (keys %$paths) {
5383 if (/$g->{path}->{left_regex}/ &&
5384 !/$g->{path}->{regex}/) {
5385 next if $paths->{$_}->{action} !~ /^[AR]$/;
5386 get_dir_check($self, $exists, $g, $r);
5388 next unless /$g->{path}->{regex}/;
5389 my $p = $1;
5390 my $pathname = $g->{path}->full_path($p);
5391 next if $exists->{$pathname};
5392 next if ($self->check_path($pathname, $r) !=
5393 $SVN::Node::dir);
5394 $exists->{$pathname} = Git::SVN->init(
5395 $self->{url}, $pathname, undef,
5396 $g->{ref}->full_path($p), 1);
5398 my $c = '';
5399 foreach (split m#/#, $g->{path}->{left}) {
5400 $c .= "/$_";
5401 next unless ($paths->{$c} &&
5402 ($paths->{$c}->{action} =~ /^[AR]$/));
5403 get_dir_check($self, $exists, $g, $r);
5406 values %$exists;
5409 sub minimize_url {
5410 my ($self) = @_;
5411 return $self->{url} if ($self->{url} eq $self->{repos_root});
5412 my $url = $self->{repos_root};
5413 my @components = split(m!/!, $self->{svn_path});
5414 my $c = '';
5415 do {
5416 $url .= "/$c" if length $c;
5417 eval {
5418 my $ra = (ref $self)->new($url);
5419 my $latest = $ra->get_latest_revnum;
5420 $ra->get_log("", $latest, 0, 1, 0, 1, sub {});
5422 } while ($@ && ($c = shift @components));
5423 $url;
5426 sub can_do_switch {
5427 my $self = shift;
5428 unless (defined $can_do_switch) {
5429 my $pool = SVN::Pool->new;
5430 my $rep = eval {
5431 $self->do_switch(1, '', 0, $self->{url},
5432 SVN::Delta::Editor->new, $pool);
5434 if ($@) {
5435 $can_do_switch = 0;
5436 } else {
5437 $rep->abort_report($pool);
5438 $can_do_switch = 1;
5440 $pool->clear;
5442 $can_do_switch;
5445 sub skip_unknown_revs {
5446 my ($err) = @_;
5447 my $errno = $err->apr_err();
5448 # Maybe the branch we're tracking didn't
5449 # exist when the repo started, so it's
5450 # not an error if it doesn't, just continue
5452 # Wonderfully consistent library, eh?
5453 # 160013 - svn:// and file://
5454 # 175002 - http(s)://
5455 # 175007 - http(s):// (this repo required authorization, too...)
5456 # More codes may be discovered later...
5457 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
5458 my $err_key = $err->expanded_message;
5459 # revision numbers change every time, filter them out
5460 $err_key =~ s/\d+/\0/g;
5461 $err_key = "$errno\0$err_key";
5462 unless ($ignored_err{$err_key}) {
5463 warn "W: Ignoring error from SVN, path probably ",
5464 "does not exist: ($errno): ",
5465 $err->expanded_message,"\n";
5466 warn "W: Do not be alarmed at the above message ",
5467 "git-svn is just searching aggressively for ",
5468 "old history.\n",
5469 "This may take a while on large repositories\n";
5470 $ignored_err{$err_key} = 1;
5472 return;
5474 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
5477 package Git::SVN::Log;
5478 use strict;
5479 use warnings;
5480 use POSIX qw/strftime/;
5481 use Time::Local;
5482 use constant commit_log_separator => ('-' x 72) . "\n";
5483 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
5484 %rusers $show_commit $incremental/;
5485 my $l_fmt;
5487 sub cmt_showable {
5488 my ($c) = @_;
5489 return 1 if defined $c->{r};
5491 # big commit message got truncated by the 16k pretty buffer in rev-list
5492 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
5493 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
5494 @{$c->{l}} = ();
5495 my @log = command(qw/cat-file commit/, $c->{c});
5497 # shift off the headers
5498 shift @log while ($log[0] ne '');
5499 shift @log;
5501 # TODO: make $c->{l} not have a trailing newline in the future
5502 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
5504 (undef, $c->{r}, undef) = ::extract_metadata(
5505 (grep(/^git-svn-id: /, @log))[-1]);
5507 return defined $c->{r};
5510 sub log_use_color {
5511 return $color || Git->repository->get_colorbool('color.diff');
5514 sub git_svn_log_cmd {
5515 my ($r_min, $r_max, @args) = @_;
5516 my $head = 'HEAD';
5517 my (@files, @log_opts);
5518 foreach my $x (@args) {
5519 if ($x eq '--' || @files) {
5520 push @files, $x;
5521 } else {
5522 if (::verify_ref("$x^0")) {
5523 $head = $x;
5524 } else {
5525 push @log_opts, $x;
5530 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
5531 $gs ||= Git::SVN->_new;
5532 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
5533 $gs->refname);
5534 push @cmd, '-r' unless $non_recursive;
5535 push @cmd, qw/--raw --name-status/ if $verbose;
5536 push @cmd, '--color' if log_use_color();
5537 push @cmd, @log_opts;
5538 if (defined $r_max && $r_max == $r_min) {
5539 push @cmd, '--max-count=1';
5540 if (my $c = $gs->rev_map_get($r_max)) {
5541 push @cmd, $c;
5543 } elsif (defined $r_max) {
5544 if ($r_max < $r_min) {
5545 ($r_min, $r_max) = ($r_max, $r_min);
5547 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
5548 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
5549 # If there are no commits in the range, both $c_max and $c_min
5550 # will be undefined. If there is at least 1 commit in the
5551 # range, both will be defined.
5552 return () if !defined $c_min || !defined $c_max;
5553 if ($c_min eq $c_max) {
5554 push @cmd, '--max-count=1', $c_min;
5555 } else {
5556 push @cmd, '--boundary', "$c_min..$c_max";
5559 return (@cmd, @files);
5562 # adapted from pager.c
5563 sub config_pager {
5564 if (! -t *STDOUT) {
5565 $ENV{GIT_PAGER_IN_USE} = 'false';
5566 $pager = undef;
5567 return;
5569 chomp($pager = command_oneline(qw(var GIT_PAGER)));
5570 if ($pager eq 'cat') {
5571 $pager = undef;
5573 $ENV{GIT_PAGER_IN_USE} = defined($pager);
5576 sub run_pager {
5577 return unless defined $pager;
5578 pipe my ($rfd, $wfd) or return;
5579 defined(my $pid = fork) or ::fatal "Can't fork: $!";
5580 if (!$pid) {
5581 open STDOUT, '>&', $wfd or
5582 ::fatal "Can't redirect to stdout: $!";
5583 return;
5585 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
5586 $ENV{LESS} ||= 'FRSX';
5587 exec $pager or ::fatal "Can't run pager: $! ($pager)";
5590 sub format_svn_date {
5591 # some systmes don't handle or mishandle %z, so be creative.
5592 my $t = shift || time;
5593 my $gm = timelocal(gmtime($t));
5594 my $sign = qw( + + - )[ $t <=> $gm ];
5595 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
5596 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
5599 sub parse_git_date {
5600 my ($t, $tz) = @_;
5601 # Date::Parse isn't in the standard Perl distro :(
5602 if ($tz =~ s/^\+//) {
5603 $t += tz_to_s_offset($tz);
5604 } elsif ($tz =~ s/^\-//) {
5605 $t -= tz_to_s_offset($tz);
5607 return $t;
5610 sub set_local_timezone {
5611 if (defined $TZ) {
5612 $ENV{TZ} = $TZ;
5613 } else {
5614 delete $ENV{TZ};
5618 sub tz_to_s_offset {
5619 my ($tz) = @_;
5620 $tz =~ s/(\d\d)$//;
5621 return ($1 * 60) + ($tz * 3600);
5624 sub get_author_info {
5625 my ($dest, $author, $t, $tz) = @_;
5626 $author =~ s/(?:^\s*|\s*$)//g;
5627 $dest->{a_raw} = $author;
5628 my $au;
5629 if ($::_authors) {
5630 $au = $rusers{$author} || undef;
5632 if (!$au) {
5633 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
5635 $dest->{t} = $t;
5636 $dest->{tz} = $tz;
5637 $dest->{a} = $au;
5638 $dest->{t_utc} = parse_git_date($t, $tz);
5641 sub process_commit {
5642 my ($c, $r_min, $r_max, $defer) = @_;
5643 if (defined $r_min && defined $r_max) {
5644 if ($r_min == $c->{r} && $r_min == $r_max) {
5645 show_commit($c);
5646 return 0;
5648 return 1 if $r_min == $r_max;
5649 if ($r_min < $r_max) {
5650 # we need to reverse the print order
5651 return 0 if (defined $limit && --$limit < 0);
5652 push @$defer, $c;
5653 return 1;
5655 if ($r_min != $r_max) {
5656 return 1 if ($r_min < $c->{r});
5657 return 1 if ($r_max > $c->{r});
5660 return 0 if (defined $limit && --$limit < 0);
5661 show_commit($c);
5662 return 1;
5665 sub show_commit {
5666 my $c = shift;
5667 if ($oneline) {
5668 my $x = "\n";
5669 if (my $l = $c->{l}) {
5670 while ($l->[0] =~ /^\s*$/) { shift @$l }
5671 $x = $l->[0];
5673 $l_fmt ||= 'A' . length($c->{r});
5674 print 'r',pack($l_fmt, $c->{r}),' | ';
5675 print "$c->{c} | " if $show_commit;
5676 print $x;
5677 } else {
5678 show_commit_normal($c);
5682 sub show_commit_changed_paths {
5683 my ($c) = @_;
5684 return unless $c->{changed};
5685 print "Changed paths:\n", @{$c->{changed}};
5688 sub show_commit_normal {
5689 my ($c) = @_;
5690 print commit_log_separator, "r$c->{r} | ";
5691 print "$c->{c} | " if $show_commit;
5692 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
5693 my $nr_line = 0;
5695 if (my $l = $c->{l}) {
5696 while ($l->[$#$l] eq "\n" && $#$l > 0
5697 && $l->[($#$l - 1)] eq "\n") {
5698 pop @$l;
5700 $nr_line = scalar @$l;
5701 if (!$nr_line) {
5702 print "1 line\n\n\n";
5703 } else {
5704 if ($nr_line == 1) {
5705 $nr_line = '1 line';
5706 } else {
5707 $nr_line .= ' lines';
5709 print $nr_line, "\n";
5710 show_commit_changed_paths($c);
5711 print "\n";
5712 print $_ foreach @$l;
5714 } else {
5715 print "1 line\n";
5716 show_commit_changed_paths($c);
5717 print "\n";
5720 foreach my $x (qw/raw stat diff/) {
5721 if ($c->{$x}) {
5722 print "\n";
5723 print $_ foreach @{$c->{$x}}
5728 sub cmd_show_log {
5729 my (@args) = @_;
5730 my ($r_min, $r_max);
5731 my $r_last = -1; # prevent dupes
5732 set_local_timezone();
5733 if (defined $::_revision) {
5734 if ($::_revision =~ /^(\d+):(\d+)$/) {
5735 ($r_min, $r_max) = ($1, $2);
5736 } elsif ($::_revision =~ /^\d+$/) {
5737 $r_min = $r_max = $::_revision;
5738 } else {
5739 ::fatal "-r$::_revision is not supported, use ",
5740 "standard 'git log' arguments instead";
5744 config_pager();
5745 @args = git_svn_log_cmd($r_min, $r_max, @args);
5746 if (!@args) {
5747 print commit_log_separator unless $incremental || $oneline;
5748 return;
5750 my $log = command_output_pipe(@args);
5751 run_pager();
5752 my (@k, $c, $d, $stat);
5753 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5754 while (<$log>) {
5755 if (/^${esc_color}commit (- )?($::sha1_short)/o) {
5756 my $cmt = $1;
5757 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5758 $r_last = $c->{r};
5759 process_commit($c, $r_min, $r_max, \@k) or
5760 goto out;
5762 $d = undef;
5763 $c = { c => $cmt };
5764 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5765 get_author_info($c, $1, $2, $3);
5766 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5767 # ignore
5768 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5769 push @{$c->{raw}}, $_;
5770 } elsif (/^${esc_color}[ACRMDT]\t/) {
5771 # we could add $SVN->{svn_path} here, but that requires
5772 # remote access at the moment (repo_path_split)...
5773 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5774 push @{$c->{changed}}, $_;
5775 } elsif (/^${esc_color}diff /o) {
5776 $d = 1;
5777 push @{$c->{diff}}, $_;
5778 } elsif ($d) {
5779 push @{$c->{diff}}, $_;
5780 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5781 $esc_color*[\+\-]*$esc_color$/x) {
5782 $stat = 1;
5783 push @{$c->{stat}}, $_;
5784 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5785 push @{$c->{stat}}, $_;
5786 $stat = undef;
5787 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5788 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5789 } elsif (s/^${esc_color} //o) {
5790 push @{$c->{l}}, $_;
5793 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5794 $r_last = $c->{r};
5795 process_commit($c, $r_min, $r_max, \@k);
5797 if (@k) {
5798 ($r_min, $r_max) = ($r_max, $r_min);
5799 process_commit($_, $r_min, $r_max) foreach reverse @k;
5801 out:
5802 close $log;
5803 print commit_log_separator unless $incremental || $oneline;
5806 sub cmd_blame {
5807 my $path = pop;
5809 config_pager();
5810 run_pager();
5812 my ($fh, $ctx, $rev);
5814 if ($_git_format) {
5815 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5816 while (my $line = <$fh>) {
5817 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5818 # Uncommitted edits show up as a rev ID of
5819 # all zeros, which we can't look up with
5820 # cmt_metadata
5821 if ($1 !~ /^0+$/) {
5822 (undef, $rev, undef) =
5823 ::cmt_metadata($1);
5824 $rev = '0' if (!$rev);
5825 } else {
5826 $rev = '0';
5828 $rev = sprintf('%-10s', $rev);
5829 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5831 print $line;
5833 } else {
5834 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5835 '--', $path);
5836 my ($sha1);
5837 my %authors;
5838 my @buffer;
5839 my %dsha; #distinct sha keys
5841 while (my $line = <$fh>) {
5842 push @buffer, $line;
5843 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5844 $dsha{$1} = 1;
5848 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5850 foreach my $line (@buffer) {
5851 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5852 $rev = $s2r->{$1};
5853 $rev = '0' if (!$rev)
5855 elsif ($line =~ /^author (.*)/) {
5856 $authors{$rev} = $1;
5857 $authors{$rev} =~ s/\s/_/g;
5859 elsif ($line =~ /^\t(.*)$/) {
5860 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5864 command_close_pipe($fh, $ctx);
5867 package Git::SVN::Migration;
5868 # these version numbers do NOT correspond to actual version numbers
5869 # of git nor git-svn. They are just relative.
5871 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5873 # v1 layout: .git/$id/info/url, refs/remotes/$id
5875 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5877 # v3 layout: .git/svn/$id, refs/remotes/$id
5878 # - info/url may remain for backwards compatibility
5879 # - this is what we migrate up to this layout automatically,
5880 # - this will be used by git svn init on single branches
5881 # v3.1 layout (auto migrated):
5882 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5883 # for backwards compatibility
5885 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5886 # - this is only created for newly multi-init-ed
5887 # repositories. Similar in spirit to the
5888 # --use-separate-remotes option in git-clone (now default)
5889 # - we do not automatically migrate to this (following
5890 # the example set by core git)
5892 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5893 # - newer, more-efficient format that uses 24-bytes per record
5894 # with no filler space.
5895 # - use xxd -c24 < .rev_map.$UUID to view and debug
5896 # - This is a one-way migration, repositories updated to the
5897 # new format will not be able to use old git-svn without
5898 # rebuilding the .rev_db. Rebuilding the rev_db is not
5899 # possible if noMetadata or useSvmProps are set; but should
5900 # be no problem for users that use the (sensible) defaults.
5901 use strict;
5902 use warnings;
5903 use Carp qw/croak/;
5904 use File::Path qw/mkpath/;
5905 use File::Basename qw/dirname basename/;
5906 use vars qw/$_minimize/;
5908 sub migrate_from_v0 {
5909 my $git_dir = $ENV{GIT_DIR};
5910 return undef unless -d $git_dir;
5911 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5912 my $migrated = 0;
5913 while (<$fh>) {
5914 chomp;
5915 my ($id, $orig_ref) = ($_, $_);
5916 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5917 next unless -f "$git_dir/$id/info/url";
5918 my $new_ref = "refs/remotes/$id";
5919 if (::verify_ref("$new_ref^0")) {
5920 print STDERR "W: $orig_ref is probably an old ",
5921 "branch used by an ancient version of ",
5922 "git-svn.\n",
5923 "However, $new_ref also exists.\n",
5924 "We will not be able ",
5925 "to use this branch until this ",
5926 "ambiguity is resolved.\n";
5927 next;
5929 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5930 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5931 command_noisy('update-ref', $new_ref, $orig_ref);
5932 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5933 $migrated++;
5935 command_close_pipe($fh, $ctx);
5936 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5937 $migrated;
5940 sub migrate_from_v1 {
5941 my $git_dir = $ENV{GIT_DIR};
5942 my $migrated = 0;
5943 return $migrated unless -d $git_dir;
5944 my $svn_dir = "$git_dir/svn";
5946 # just in case somebody used 'svn' as their $id at some point...
5947 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5949 print STDERR "Migrating from a git-svn v1 layout...\n";
5950 mkpath([$svn_dir]);
5951 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5952 "$svn_dir\n\t(required for this version ",
5953 "($::VERSION) of git-svn) does not exist.\n";
5954 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5955 while (<$fh>) {
5956 my $x = $_;
5957 next unless $x =~ s#^refs/remotes/##;
5958 chomp $x;
5959 next unless -f "$git_dir/$x/info/url";
5960 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5961 next unless $u;
5962 my $dn = dirname("$git_dir/svn/$x");
5963 mkpath([$dn]) unless -d $dn;
5964 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5965 mkpath(["$git_dir/svn/svn"]);
5966 print STDERR " - $git_dir/$x/info => ",
5967 "$git_dir/svn/$x/info\n";
5968 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5969 croak "$!: $x";
5970 # don't worry too much about these, they probably
5971 # don't exist with repos this old (save for index,
5972 # and we can easily regenerate that)
5973 foreach my $f (qw/unhandled.log index .rev_db/) {
5974 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5976 } else {
5977 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5978 rename "$git_dir/$x", "$git_dir/svn/$x" or
5979 croak "$!: $x";
5981 $migrated++;
5983 command_close_pipe($fh, $ctx);
5984 print STDERR "Done migrating from a git-svn v1 layout\n";
5985 $migrated;
5988 sub read_old_urls {
5989 my ($l_map, $pfx, $path) = @_;
5990 my @dir;
5991 foreach (<$path/*>) {
5992 if (-r "$_/info/url") {
5993 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5994 my $ref_id = $pfx . basename $_;
5995 my $url = ::file_to_s("$_/info/url");
5996 $l_map->{$ref_id} = $url;
5997 } elsif (-d $_) {
5998 push @dir, $_;
6001 foreach (@dir) {
6002 my $x = $_;
6003 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
6004 read_old_urls($l_map, $x, $_);
6008 sub migrate_from_v2 {
6009 my @cfg = command(qw/config -l/);
6010 return if grep /^svn-remote\..+\.url=/, @cfg;
6011 my %l_map;
6012 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
6013 my $migrated = 0;
6015 foreach my $ref_id (sort keys %l_map) {
6016 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
6017 if ($@) {
6018 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
6020 $migrated++;
6022 $migrated;
6025 sub minimize_connections {
6026 my $r = Git::SVN::read_all_remotes();
6027 my $new_urls = {};
6028 my $root_repos = {};
6029 foreach my $repo_id (keys %$r) {
6030 my $url = $r->{$repo_id}->{url} or next;
6031 my $fetch = $r->{$repo_id}->{fetch} or next;
6032 my $ra = Git::SVN::Ra->new($url);
6034 # skip existing cases where we already connect to the root
6035 if (($ra->{url} eq $ra->{repos_root}) ||
6036 ($ra->{repos_root} eq $repo_id)) {
6037 $root_repos->{$ra->{url}} = $repo_id;
6038 next;
6041 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
6042 my $root_path = $ra->{url};
6043 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
6044 foreach my $path (keys %$fetch) {
6045 my $ref_id = $fetch->{$path};
6046 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
6048 # make sure we can read when connecting to
6049 # a higher level of a repository
6050 my ($last_rev, undef) = $gs->last_rev_commit;
6051 if (!defined $last_rev) {
6052 $last_rev = eval {
6053 $root_ra->get_latest_revnum;
6055 next if $@;
6057 my $new = $root_path;
6058 $new .= length $path ? "/$path" : '';
6059 eval {
6060 $root_ra->get_log([$new], $last_rev, $last_rev,
6061 0, 0, 1, sub { });
6063 next if $@;
6064 $new_urls->{$ra->{repos_root}}->{$new} =
6065 { ref_id => $ref_id,
6066 old_repo_id => $repo_id,
6067 old_path => $path };
6071 my @emptied;
6072 foreach my $url (keys %$new_urls) {
6073 # see if we can re-use an existing [svn-remote "repo_id"]
6074 # instead of creating a(n ugly) new section:
6075 my $repo_id = $root_repos->{$url} || $url;
6077 my $fetch = $new_urls->{$url};
6078 foreach my $path (keys %$fetch) {
6079 my $x = $fetch->{$path};
6080 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
6081 my $pfx = "svn-remote.$x->{old_repo_id}";
6083 my $old_fetch = quotemeta("$x->{old_path}:".
6084 "$x->{ref_id}");
6085 command_noisy(qw/config --unset/,
6086 "$pfx.fetch", '^'. $old_fetch . '$');
6087 delete $r->{$x->{old_repo_id}}->
6088 {fetch}->{$x->{old_path}};
6089 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
6090 command_noisy(qw/config --unset/,
6091 "$pfx.url");
6092 push @emptied, $x->{old_repo_id}
6096 if (@emptied) {
6097 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
6098 print STDERR <<EOF;
6099 The following [svn-remote] sections in your config file ($file) are empty
6100 and can be safely removed:
6102 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
6106 sub migration_check {
6107 migrate_from_v0();
6108 migrate_from_v1();
6109 migrate_from_v2();
6110 minimize_connections() if $_minimize;
6113 package Git::IndexInfo;
6114 use strict;
6115 use warnings;
6116 use Git qw/command_input_pipe command_close_pipe/;
6118 sub new {
6119 my ($class) = @_;
6120 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
6121 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
6124 sub remove {
6125 my ($self, $path) = @_;
6126 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
6127 return ++$self->{nr};
6129 undef;
6132 sub update {
6133 my ($self, $mode, $hash, $path) = @_;
6134 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
6135 return ++$self->{nr};
6137 undef;
6140 sub DESTROY {
6141 my ($self) = @_;
6142 command_close_pipe($self->{gui}, $self->{ctx});
6145 package Git::SVN::GlobSpec;
6146 use strict;
6147 use warnings;
6149 sub new {
6150 my ($class, $glob, $pattern_ok) = @_;
6151 my $re = $glob;
6152 $re =~ s!/+$!!g; # no need for trailing slashes
6153 my (@left, @right, @patterns);
6154 my $state = "left";
6155 my $die_msg = "Only one set of wildcard directories " .
6156 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
6157 for my $part (split(m|/|, $glob)) {
6158 if ($part =~ /\*/ && $part ne "*") {
6159 die "Invalid pattern in '$glob': $part\n";
6160 } elsif ($pattern_ok && $part =~ /[{}]/ &&
6161 $part !~ /^\{[^{}]+\}/) {
6162 die "Invalid pattern in '$glob': $part\n";
6164 if ($part eq "*") {
6165 die $die_msg if $state eq "right";
6166 $state = "pattern";
6167 push(@patterns, "[^/]*");
6168 } elsif ($pattern_ok && $part =~ /^\{(.*)\}$/) {
6169 die $die_msg if $state eq "right";
6170 $state = "pattern";
6171 my $p = quotemeta($1);
6172 $p =~ s/\\,/|/g;
6173 push(@patterns, "(?:$p)");
6174 } else {
6175 if ($state eq "left") {
6176 push(@left, $part);
6177 } else {
6178 push(@right, $part);
6179 $state = "right";
6183 my $depth = @patterns;
6184 if ($depth == 0) {
6185 die "One '*' is needed in glob: '$glob'\n";
6187 my $left = join('/', @left);
6188 my $right = join('/', @right);
6189 $re = join('/', @patterns);
6190 $re = join('\/',
6191 grep(length, quotemeta($left), "($re)", quotemeta($right)));
6192 my $left_re = qr/^\/\Q$left\E(\/|$)/;
6193 bless { left => $left, right => $right, left_regex => $left_re,
6194 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
6197 sub full_path {
6198 my ($self, $path) = @_;
6199 return (length $self->{left} ? "$self->{left}/" : '') .
6200 $path . (length $self->{right} ? "/$self->{right}" : '');
6203 __END__
6205 Data structures:
6208 $remotes = { # returned by read_all_remotes()
6209 'svn' => {
6210 # svn-remote.svn.url=https://svn.musicpd.org
6211 url => 'https://svn.musicpd.org',
6212 # svn-remote.svn.fetch=mpd/trunk:trunk
6213 fetch => {
6214 'mpd/trunk' => 'trunk',
6216 # svn-remote.svn.tags=mpd/tags/*:tags/*
6217 tags => {
6218 path => {
6219 left => 'mpd/tags',
6220 right => '',
6221 regex => qr!mpd/tags/([^/]+)$!,
6222 glob => 'tags/*',
6224 ref => {
6225 left => 'tags',
6226 right => '',
6227 regex => qr!tags/([^/]+)$!,
6228 glob => 'tags/*',
6234 $log_entry hashref as returned by libsvn_log_entry()
6236 log => 'whitespace-formatted log entry
6237 ', # trailing newline is preserved
6238 revision => '8', # integer
6239 date => '2004-02-24T17:01:44.108345Z', # commit date
6240 author => 'committer name'
6244 # this is generated by generate_diff();
6245 @mods = array of diff-index line hashes, each element represents one line
6246 of diff-index output
6248 diff-index line ($m hash)
6250 mode_a => first column of diff-index output, no leading ':',
6251 mode_b => second column of diff-index output,
6252 sha1_b => sha1sum of the final blob,
6253 chg => change type [MCRADT],
6254 file_a => original file name of a file (iff chg is 'C' or 'R')
6255 file_b => new/current file name of a file (any chg)
6259 # retval of read_url_paths{,_all}();
6260 $l_map = {
6261 # repository root url
6262 'https://svn.musicpd.org' => {
6263 # repository path # GIT_SVN_ID
6264 'mpd/trunk' => 'trunk',
6265 'mpd/tags/0.11.5' => 'tags/0.11.5',
6269 Notes:
6270 I don't trust the each() function on unless I created %hash myself
6271 because the internal iterator may not have started at base.