git-svn: let 'dcommit $rev' work on $rev instead of HEAD
[git/dkf.git] / git-svn.perl
blob33fe34cbacfab18ccb0b2fbd53052e90f45e95a9
1 #!/usr/bin/env perl
2 # Copyright (C) 2006, Eric Wong <normalperson@yhbt.net>
3 # License: GPL v2 or later
4 use warnings;
5 use strict;
6 use vars qw/ $AUTHOR $VERSION
7 $sha1 $sha1_short $_revision $_repository
8 $_q $_authors $_authors_prog %users/;
9 $AUTHOR = 'Eric Wong <normalperson@yhbt.net>';
10 $VERSION = '@@GIT_VERSION@@';
12 # From which subdir have we been invoked?
13 my $cmd_dir_prefix = eval {
14 command_oneline([qw/rev-parse --show-prefix/], STDERR => 0)
15 } || '';
17 my $git_dir_user_set = 1 if defined $ENV{GIT_DIR};
18 $ENV{GIT_DIR} ||= '.git';
19 $Git::SVN::default_repo_id = 'svn';
20 $Git::SVN::default_ref_id = $ENV{GIT_SVN_ID} || 'git-svn';
21 $Git::SVN::Ra::_log_window_size = 100;
23 $Git::SVN::Log::TZ = $ENV{TZ};
24 $ENV{TZ} = 'UTC';
25 $| = 1; # unbuffer STDOUT
27 sub fatal (@) { print STDERR "@_\n"; exit 1 }
28 require SVN::Core; # use()-ing this causes segfaults for me... *shrug*
29 require SVN::Ra;
30 require SVN::Delta;
31 if ($SVN::Core::VERSION lt '1.1.0') {
32 fatal "Need SVN::Core 1.1.0 or better (got $SVN::Core::VERSION)";
34 push @Git::SVN::Ra::ISA, 'SVN::Ra';
35 push @SVN::Git::Editor::ISA, 'SVN::Delta::Editor';
36 push @SVN::Git::Fetcher::ISA, 'SVN::Delta::Editor';
37 use Carp qw/croak/;
38 use Digest::MD5;
39 use IO::File qw//;
40 use File::Basename qw/dirname basename/;
41 use File::Path qw/mkpath/;
42 use File::Spec;
43 use Getopt::Long qw/:config gnu_getopt no_ignore_case auto_abbrev/;
44 use IPC::Open3;
45 use Git;
47 BEGIN {
48 # import functions from Git into our packages, en masse
49 no strict 'refs';
50 foreach (qw/command command_oneline command_noisy command_output_pipe
51 command_input_pipe command_close_pipe
52 command_bidi_pipe command_close_bidi_pipe/) {
53 for my $package ( qw(SVN::Git::Editor SVN::Git::Fetcher
54 Git::SVN::Migration Git::SVN::Log Git::SVN),
55 __PACKAGE__) {
56 *{"${package}::$_"} = \&{"Git::$_"};
61 my ($SVN);
63 $sha1 = qr/[a-f\d]{40}/;
64 $sha1_short = qr/[a-f\d]{4,40}/;
65 my ($_stdin, $_help, $_edit,
66 $_message, $_file,
67 $_template, $_shared,
68 $_version, $_fetch_all, $_no_rebase, $_fetch_parent,
69 $_merge, $_strategy, $_dry_run, $_local,
70 $_prefix, $_no_checkout, $_url, $_verbose,
71 $_git_format, $_commit_url, $_tag);
72 $Git::SVN::_follow_parent = 1;
73 $_q ||= 0;
74 my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username,
75 'config-dir=s' => \$Git::SVN::Ra::config_dir,
76 'no-auth-cache' => \$Git::SVN::Prompt::_no_auth_cache,
77 'ignore-paths=s' => \$SVN::Git::Fetcher::_ignore_regex );
78 my %fc_opts = ( 'follow-parent|follow!' => \$Git::SVN::_follow_parent,
79 'authors-file|A=s' => \$_authors,
80 'authors-prog=s' => \$_authors_prog,
81 'repack:i' => \$Git::SVN::_repack,
82 'noMetadata' => \$Git::SVN::_no_metadata,
83 'useSvmProps' => \$Git::SVN::_use_svm_props,
84 'useSvnsyncProps' => \$Git::SVN::_use_svnsync_props,
85 'log-window-size=i' => \$Git::SVN::Ra::_log_window_size,
86 'no-checkout' => \$_no_checkout,
87 'quiet|q+' => \$_q,
88 'repack-flags|repack-args|repack-opts=s' =>
89 \$Git::SVN::_repack_flags,
90 'use-log-author' => \$Git::SVN::_use_log_author,
91 'add-author-from' => \$Git::SVN::_add_author_from,
92 'localtime' => \$Git::SVN::_localtime,
93 %remote_opts );
95 my ($_trunk, $_tags, $_branches, $_stdlayout);
96 my %icv;
97 my %init_opts = ( 'template=s' => \$_template, 'shared:s' => \$_shared,
98 'trunk|T=s' => \$_trunk, 'tags|t=s' => \$_tags,
99 'branches|b=s' => \$_branches, 'prefix=s' => \$_prefix,
100 'stdlayout|s' => \$_stdlayout,
101 'minimize-url|m' => \$Git::SVN::_minimize_url,
102 'no-metadata' => sub { $icv{noMetadata} = 1 },
103 'use-svm-props' => sub { $icv{useSvmProps} = 1 },
104 'use-svnsync-props' => sub { $icv{useSvnsyncProps} = 1 },
105 'rewrite-root=s' => sub { $icv{rewriteRoot} = $_[1] },
106 %remote_opts );
107 my %cmt_opts = ( 'edit|e' => \$_edit,
108 'rmdir' => \$SVN::Git::Editor::_rmdir,
109 'find-copies-harder' => \$SVN::Git::Editor::_find_copies_harder,
110 'l=i' => \$SVN::Git::Editor::_rename_limit,
111 'copy-similarity|C=i'=> \$SVN::Git::Editor::_cp_similarity
114 my %cmd = (
115 fetch => [ \&cmd_fetch, "Download new revisions from SVN",
116 { 'revision|r=s' => \$_revision,
117 'fetch-all|all' => \$_fetch_all,
118 'parent|p' => \$_fetch_parent,
119 %fc_opts } ],
120 clone => [ \&cmd_clone, "Initialize and fetch revisions",
121 { 'revision|r=s' => \$_revision,
122 %fc_opts, %init_opts } ],
123 init => [ \&cmd_init, "Initialize a repo for tracking" .
124 " (requires URL argument)",
125 \%init_opts ],
126 'multi-init' => [ \&cmd_multi_init,
127 "Deprecated alias for ".
128 "'$0 init -T<trunk> -b<branches> -t<tags>'",
129 \%init_opts ],
130 dcommit => [ \&cmd_dcommit,
131 'Commit several diffs to merge with upstream',
132 { 'merge|m|M' => \$_merge,
133 'strategy|s=s' => \$_strategy,
134 'verbose|v' => \$_verbose,
135 'dry-run|n' => \$_dry_run,
136 'fetch-all|all' => \$_fetch_all,
137 'commit-url=s' => \$_commit_url,
138 'revision|r=i' => \$_revision,
139 'no-rebase' => \$_no_rebase,
140 %cmt_opts, %fc_opts } ],
141 branch => [ \&cmd_branch,
142 'Create a branch in the SVN repository',
143 { 'message|m=s' => \$_message,
144 'dry-run|n' => \$_dry_run,
145 'tag|t' => \$_tag } ],
146 tag => [ sub { $_tag = 1; cmd_branch(@_) },
147 'Create a tag in the SVN repository',
148 { 'message|m=s' => \$_message,
149 'dry-run|n' => \$_dry_run } ],
150 'set-tree' => [ \&cmd_set_tree,
151 "Set an SVN repository to a git tree-ish",
152 { 'stdin' => \$_stdin, %cmt_opts, %fc_opts, } ],
153 'create-ignore' => [ \&cmd_create_ignore,
154 'Create a .gitignore per svn:ignore',
155 { 'revision|r=i' => \$_revision
156 } ],
157 'propget' => [ \&cmd_propget,
158 'Print the value of a property on a file or directory',
159 { 'revision|r=i' => \$_revision } ],
160 'proplist' => [ \&cmd_proplist,
161 'List all properties of a file or directory',
162 { 'revision|r=i' => \$_revision } ],
163 'show-ignore' => [ \&cmd_show_ignore, "Show svn:ignore listings",
164 { 'revision|r=i' => \$_revision
165 } ],
166 'show-externals' => [ \&cmd_show_externals, "Show svn:externals listings",
167 { 'revision|r=i' => \$_revision
168 } ],
169 'multi-fetch' => [ \&cmd_multi_fetch,
170 "Deprecated alias for $0 fetch --all",
171 { 'revision|r=s' => \$_revision, %fc_opts } ],
172 'migrate' => [ sub { },
173 # no-op, we automatically run this anyways,
174 'Migrate configuration/metadata/layout from
175 previous versions of git-svn',
176 { 'minimize' => \$Git::SVN::Migration::_minimize,
177 %remote_opts } ],
178 'log' => [ \&Git::SVN::Log::cmd_show_log, 'Show commit logs',
179 { 'limit=i' => \$Git::SVN::Log::limit,
180 'revision|r=s' => \$_revision,
181 'verbose|v' => \$Git::SVN::Log::verbose,
182 'incremental' => \$Git::SVN::Log::incremental,
183 'oneline' => \$Git::SVN::Log::oneline,
184 'show-commit' => \$Git::SVN::Log::show_commit,
185 'non-recursive' => \$Git::SVN::Log::non_recursive,
186 'authors-file|A=s' => \$_authors,
187 'color' => \$Git::SVN::Log::color,
188 'pager=s' => \$Git::SVN::Log::pager
189 } ],
190 'find-rev' => [ \&cmd_find_rev,
191 "Translate between SVN revision numbers and tree-ish",
192 {} ],
193 'rebase' => [ \&cmd_rebase, "Fetch and rebase your working directory",
194 { 'merge|m|M' => \$_merge,
195 'verbose|v' => \$_verbose,
196 'strategy|s=s' => \$_strategy,
197 'local|l' => \$_local,
198 'fetch-all|all' => \$_fetch_all,
199 'dry-run|n' => \$_dry_run,
200 %fc_opts } ],
201 'commit-diff' => [ \&cmd_commit_diff,
202 'Commit a diff between two trees',
203 { 'message|m=s' => \$_message,
204 'file|F=s' => \$_file,
205 'revision|r=s' => \$_revision,
206 %cmt_opts } ],
207 'info' => [ \&cmd_info,
208 "Show info about the latest SVN revision
209 on the current branch",
210 { 'url' => \$_url, } ],
211 'blame' => [ \&Git::SVN::Log::cmd_blame,
212 "Show what revision and author last modified each line of a file",
213 { 'git-format' => \$_git_format } ],
216 my $cmd;
217 for (my $i = 0; $i < @ARGV; $i++) {
218 if (defined $cmd{$ARGV[$i]}) {
219 $cmd = $ARGV[$i];
220 splice @ARGV, $i, 1;
221 last;
225 # make sure we're always running at the top-level working directory
226 unless ($cmd && $cmd =~ /(?:clone|init|multi-init)$/) {
227 unless (-d $ENV{GIT_DIR}) {
228 if ($git_dir_user_set) {
229 die "GIT_DIR=$ENV{GIT_DIR} explicitly set, ",
230 "but it is not a directory\n";
232 my $git_dir = delete $ENV{GIT_DIR};
233 my $cdup = undef;
234 git_cmd_try {
235 $cdup = command_oneline(qw/rev-parse --show-cdup/);
236 $git_dir = '.' unless ($cdup);
237 chomp $cdup if ($cdup);
238 $cdup = "." unless ($cdup && length $cdup);
239 } "Already at toplevel, but $git_dir not found\n";
240 chdir $cdup or die "Unable to chdir up to '$cdup'\n";
241 unless (-d $git_dir) {
242 die "$git_dir still not found after going to ",
243 "'$cdup'\n";
245 $ENV{GIT_DIR} = $git_dir;
247 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
250 my %opts = %{$cmd{$cmd}->[2]} if (defined $cmd);
252 read_repo_config(\%opts);
253 if ($cmd && ($cmd eq 'log' || $cmd eq 'blame')) {
254 Getopt::Long::Configure('pass_through');
256 my $rv = GetOptions(%opts, 'help|H|h' => \$_help, 'version|V' => \$_version,
257 'minimize-connections' => \$Git::SVN::Migration::_minimize,
258 'id|i=s' => \$Git::SVN::default_ref_id,
259 'svn-remote|remote|R=s' => sub {
260 $Git::SVN::no_reuse_existing = 1;
261 $Git::SVN::default_repo_id = $_[1] });
262 exit 1 if (!$rv && $cmd && $cmd ne 'log');
264 usage(0) if $_help;
265 version() if $_version;
266 usage(1) unless defined $cmd;
267 load_authors() if $_authors;
268 if (defined $_authors_prog) {
269 $_authors_prog = "'" . File::Spec->rel2abs($_authors_prog) . "'";
272 unless ($cmd =~ /^(?:clone|init|multi-init|commit-diff)$/) {
273 Git::SVN::Migration::migration_check();
275 Git::SVN::init_vars();
276 eval {
277 Git::SVN::verify_remotes_sanity();
278 $cmd{$cmd}->[0]->(@ARGV);
280 fatal $@ if $@;
281 post_fetch_checkout();
282 exit 0;
284 ####################### primary functions ######################
285 sub usage {
286 my $exit = shift || 0;
287 my $fd = $exit ? \*STDERR : \*STDOUT;
288 print $fd <<"";
289 git-svn - bidirectional operations between a single Subversion tree and git
290 Usage: git svn <command> [options] [arguments]\n
292 print $fd "Available commands:\n" unless $cmd;
294 foreach (sort keys %cmd) {
295 next if $cmd && $cmd ne $_;
296 next if /^multi-/; # don't show deprecated commands
297 print $fd ' ',pack('A17',$_),$cmd{$_}->[1],"\n";
298 foreach (sort keys %{$cmd{$_}->[2]}) {
299 # mixed-case options are for .git/config only
300 next if /[A-Z]/ && /^[a-z]+$/i;
301 # prints out arguments as they should be passed:
302 my $x = s#[:=]s$## ? '<arg>' : s#[:=]i$## ? '<num>' : '';
303 print $fd ' ' x 21, join(', ', map { length $_ > 1 ?
304 "--$_" : "-$_" }
305 split /\|/,$_)," $x\n";
308 print $fd <<"";
309 \nGIT_SVN_ID may be set in the environment or via the --id/-i switch to an
310 arbitrary identifier if you're tracking multiple SVN branches/repositories in
311 one git repository and want to keep them separate. See git-svn(1) for more
312 information.
314 exit $exit;
317 sub version {
318 print "git-svn version $VERSION (svn $SVN::Core::VERSION)\n";
319 exit 0;
322 sub do_git_init_db {
323 unless (-d $ENV{GIT_DIR}) {
324 my @init_db = ('init');
325 push @init_db, "--template=$_template" if defined $_template;
326 if (defined $_shared) {
327 if ($_shared =~ /[a-z]/) {
328 push @init_db, "--shared=$_shared";
329 } else {
330 push @init_db, "--shared";
333 command_noisy(@init_db);
334 $_repository = Git->repository(Repository => ".git");
336 command_noisy('config', 'core.autocrlf', 'false');
337 my $set;
338 my $pfx = "svn-remote.$Git::SVN::default_repo_id";
339 foreach my $i (keys %icv) {
340 die "'$set' and '$i' cannot both be set\n" if $set;
341 next unless defined $icv{$i};
342 command_noisy('config', "$pfx.$i", $icv{$i});
343 $set = $i;
345 my $ignore_regex = \$SVN::Git::Fetcher::_ignore_regex;
346 command_noisy('config', "$pfx.ignore-paths", $$ignore_regex)
347 if defined $$ignore_regex;
350 sub init_subdir {
351 my $repo_path = shift or return;
352 mkpath([$repo_path]) unless -d $repo_path;
353 chdir $repo_path or die "Couldn't chdir to $repo_path: $!\n";
354 $ENV{GIT_DIR} = '.git';
355 $_repository = Git->repository(Repository => $ENV{GIT_DIR});
358 sub cmd_clone {
359 my ($url, $path) = @_;
360 if (!defined $path &&
361 (defined $_trunk || defined $_branches || defined $_tags ||
362 defined $_stdlayout) &&
363 $url !~ m#^[a-z\+]+://#) {
364 $path = $url;
366 $path = basename($url) if !defined $path || !length $path;
367 cmd_init($url, $path);
368 Git::SVN::fetch_all($Git::SVN::default_repo_id);
369 command_oneline('config', 'svn.authorsfile', $_authors) if $_authors;
372 sub cmd_init {
373 if (defined $_stdlayout) {
374 $_trunk = 'trunk' if (!defined $_trunk);
375 $_tags = 'tags' if (!defined $_tags);
376 $_branches = 'branches' if (!defined $_branches);
378 if (defined $_trunk || defined $_branches || defined $_tags) {
379 return cmd_multi_init(@_);
381 my $url = shift or die "SVN repository location required ",
382 "as a command-line argument\n";
383 init_subdir(@_);
384 do_git_init_db();
386 Git::SVN->init($url);
389 sub cmd_fetch {
390 if (grep /^\d+=./, @_) {
391 die "'<rev>=<commit>' fetch arguments are ",
392 "no longer supported.\n";
394 my ($remote) = @_;
395 if (@_ > 1) {
396 die "Usage: $0 fetch [--all] [--parent] [svn-remote]\n";
398 if ($_fetch_parent) {
399 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
400 unless ($gs) {
401 die "Unable to determine upstream SVN information from ",
402 "working tree history\n";
404 # just fetch, don't checkout.
405 $_no_checkout = 'true';
406 $_fetch_all ? $gs->fetch_all : $gs->fetch;
407 } elsif ($_fetch_all) {
408 cmd_multi_fetch();
409 } else {
410 $remote ||= $Git::SVN::default_repo_id;
411 Git::SVN::fetch_all($remote, Git::SVN::read_all_remotes());
415 sub cmd_set_tree {
416 my (@commits) = @_;
417 if ($_stdin || !@commits) {
418 print "Reading from stdin...\n";
419 @commits = ();
420 while (<STDIN>) {
421 if (/\b($sha1_short)\b/o) {
422 unshift @commits, $1;
426 my @revs;
427 foreach my $c (@commits) {
428 my @tmp = command('rev-parse',$c);
429 if (scalar @tmp == 1) {
430 push @revs, $tmp[0];
431 } elsif (scalar @tmp > 1) {
432 push @revs, reverse(command('rev-list',@tmp));
433 } else {
434 fatal "Failed to rev-parse $c";
437 my $gs = Git::SVN->new;
438 my ($r_last, $cmt_last) = $gs->last_rev_commit;
439 $gs->fetch;
440 if (defined $gs->{last_rev} && $r_last != $gs->{last_rev}) {
441 fatal "There are new revisions that were fetched ",
442 "and need to be merged (or acknowledged) ",
443 "before committing.\nlast rev: $r_last\n",
444 " current: $gs->{last_rev}";
446 $gs->set_tree($_) foreach @revs;
447 print "Done committing ",scalar @revs," revisions to SVN\n";
448 unlink $gs->{index};
451 sub cmd_dcommit {
452 my $head = shift;
453 git_cmd_try { command_oneline(qw/diff-index --quiet HEAD/) }
454 'Cannot dcommit with a dirty index. Commit your changes first, '
455 . "or stash them with `git stash'.\n";
456 $head ||= 'HEAD';
458 my $old_head;
459 if ($head ne 'HEAD') {
460 $old_head = eval {
461 command_oneline([qw/symbolic-ref -q HEAD/])
463 if ($old_head) {
464 $old_head =~ s{^refs/heads/}{};
465 } else {
466 $old_head = eval { command_oneline(qw/rev-parse HEAD/) };
468 command(['checkout', $head], STDERR => 0);
471 my @refs;
472 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD', \@refs);
473 unless ($gs) {
474 die "Unable to determine upstream SVN information from ",
475 "$head history.\nPerhaps the repository is empty.";
478 if (defined $_commit_url) {
479 $url = $_commit_url;
480 } else {
481 $url = eval { command_oneline('config', '--get',
482 "svn-remote.$gs->{repo_id}.commiturl") };
483 if (!$url) {
484 $url = $gs->full_url
488 my $last_rev = $_revision if defined $_revision;
489 if ($url) {
490 print "Committing to $url ...\n";
492 my ($linear_refs, $parents) = linearize_history($gs, \@refs);
493 if ($_no_rebase && scalar(@$linear_refs) > 1) {
494 warn "Attempting to commit more than one change while ",
495 "--no-rebase is enabled.\n",
496 "If these changes depend on each other, re-running ",
497 "without --no-rebase may be required."
499 my $expect_url = $url;
500 Git::SVN::remove_username($expect_url);
501 while (1) {
502 my $d = shift @$linear_refs or last;
503 unless (defined $last_rev) {
504 (undef, $last_rev, undef) = cmt_metadata("$d~1");
505 unless (defined $last_rev) {
506 fatal "Unable to extract revision information ",
507 "from commit $d~1";
510 if ($_dry_run) {
511 print "diff-tree $d~1 $d\n";
512 } else {
513 my $cmt_rev;
514 my %ed_opts = ( r => $last_rev,
515 log => get_commit_entry($d)->{log},
516 ra => Git::SVN::Ra->new($url),
517 config => SVN::Core::config_get_config(
518 $Git::SVN::Ra::config_dir
520 tree_a => "$d~1",
521 tree_b => $d,
522 editor_cb => sub {
523 print "Committed r$_[0]\n";
524 $cmt_rev = $_[0];
526 svn_path => '');
527 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
528 print "No changes\n$d~1 == $d\n";
529 } elsif ($parents->{$d} && @{$parents->{$d}}) {
530 $gs->{inject_parents_dcommit}->{$cmt_rev} =
531 $parents->{$d};
533 $_fetch_all ? $gs->fetch_all : $gs->fetch;
534 $last_rev = $cmt_rev;
535 next if $_no_rebase;
537 # we always want to rebase against the current HEAD,
538 # not any head that was passed to us
539 my @diff = command('diff-tree', $d,
540 $gs->refname, '--');
541 my @finish;
542 if (@diff) {
543 @finish = rebase_cmd();
544 print STDERR "W: $d and ", $gs->refname,
545 " differ, using @finish:\n",
546 join("\n", @diff), "\n";
547 } else {
548 print "No changes between current HEAD and ",
549 $gs->refname,
550 "\nResetting to the latest ",
551 $gs->refname, "\n";
552 @finish = qw/reset --mixed/;
554 command_noisy(@finish, $gs->refname);
555 if (@diff) {
556 @refs = ();
557 my ($url_, $rev_, $uuid_, $gs_) =
558 working_head_info('HEAD', \@refs);
559 my ($linear_refs_, $parents_) =
560 linearize_history($gs_, \@refs);
561 if (scalar(@$linear_refs) !=
562 scalar(@$linear_refs_)) {
563 fatal "# of revisions changed ",
564 "\nbefore:\n",
565 join("\n", @$linear_refs),
566 "\n\nafter:\n",
567 join("\n", @$linear_refs_), "\n",
568 'If you are attempting to commit ',
569 "merges, try running:\n\t",
570 'git rebase --interactive',
571 '--preserve-merges ',
572 $gs->refname,
573 "\nBefore dcommitting";
575 if ($url_ ne $expect_url) {
576 fatal "URL mismatch after rebase: ",
577 "$url_ != $expect_url";
579 if ($uuid_ ne $uuid) {
580 fatal "uuid mismatch after rebase: ",
581 "$uuid_ != $uuid";
583 # remap parents
584 my (%p, @l, $i);
585 for ($i = 0; $i < scalar @$linear_refs; $i++) {
586 my $new = $linear_refs_->[$i] or next;
587 $p{$new} =
588 $parents->{$linear_refs->[$i]};
589 push @l, $new;
591 $parents = \%p;
592 $linear_refs = \@l;
597 if ($old_head) {
598 my $new_head = command_oneline(qw/rev-parse HEAD/);
599 my $new_is_symbolic = eval {
600 command_oneline(qw/symbolic-ref -q HEAD/);
602 if ($new_is_symbolic) {
603 print "dcommitted the branch ", $head, "\n";
604 } else {
605 print "dcommitted on a detached HEAD because you gave ",
606 "a revision argument.\n",
607 "The rewritten commit is: ", $new_head, "\n";
609 command(['checkout', $old_head], STDERR => 0);
612 unlink $gs->{index};
615 sub cmd_branch {
616 my ($branch_name, $head) = @_;
618 unless (defined $branch_name && length $branch_name) {
619 die(($_tag ? "tag" : "branch") . " name required\n");
621 $head ||= 'HEAD';
623 my ($src, $rev, undef, $gs) = working_head_info($head);
625 my $remote = Git::SVN::read_all_remotes()->{$gs->{repo_id}};
626 my $glob = $remote->{ $_tag ? 'tags' : 'branches' };
627 my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/};
628 my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ());
630 my $ctx = SVN::Client->new(
631 auth => Git::SVN::Ra::_auth_providers(),
632 log_msg => sub {
633 ${ $_[0] } = defined $_message
634 ? $_message
635 : 'Create ' . ($_tag ? 'tag ' : 'branch ' )
636 . $branch_name;
640 eval {
641 $ctx->ls($dst, 'HEAD', 0);
642 } and die "branch ${branch_name} already exists\n";
644 print "Copying ${src} at r${rev} to ${dst}...\n";
645 $ctx->copy($src, $rev, $dst)
646 unless $_dry_run;
648 $gs->fetch_all;
651 sub cmd_find_rev {
652 my $revision_or_hash = shift or die "SVN or git revision required ",
653 "as a command-line argument\n";
654 my $result;
655 if ($revision_or_hash =~ /^r\d+$/) {
656 my $head = shift;
657 $head ||= 'HEAD';
658 my @refs;
659 my (undef, undef, $uuid, $gs) = working_head_info($head, \@refs);
660 unless ($gs) {
661 die "Unable to determine upstream SVN information from ",
662 "$head history\n";
664 my $desired_revision = substr($revision_or_hash, 1);
665 $result = $gs->rev_map_get($desired_revision, $uuid);
666 } else {
667 my (undef, $rev, undef) = cmt_metadata($revision_or_hash);
668 $result = $rev;
670 print "$result\n" if $result;
673 sub cmd_rebase {
674 command_noisy(qw/update-index --refresh/);
675 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
676 unless ($gs) {
677 die "Unable to determine upstream SVN information from ",
678 "working tree history\n";
680 if ($_dry_run) {
681 print "Remote Branch: " . $gs->refname . "\n";
682 print "SVN URL: " . $url . "\n";
683 return;
685 if (command(qw/diff-index HEAD --/)) {
686 print STDERR "Cannot rebase with uncommited changes:\n";
687 command_noisy('status');
688 exit 1;
690 unless ($_local) {
691 # rebase will checkout for us, so no need to do it explicitly
692 $_no_checkout = 'true';
693 $_fetch_all ? $gs->fetch_all : $gs->fetch;
695 command_noisy(rebase_cmd(), $gs->refname);
698 sub cmd_show_ignore {
699 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
700 $gs ||= Git::SVN->new;
701 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
702 $gs->prop_walk($gs->{path}, $r, sub {
703 my ($gs, $path, $props) = @_;
704 print STDOUT "\n# $path\n";
705 my $s = $props->{'svn:ignore'} or return;
706 $s =~ s/[\r\n]+/\n/g;
707 chomp $s;
708 $s =~ s#^#$path#gm;
709 print STDOUT "$s\n";
713 sub cmd_show_externals {
714 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
715 $gs ||= Git::SVN->new;
716 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
717 $gs->prop_walk($gs->{path}, $r, sub {
718 my ($gs, $path, $props) = @_;
719 print STDOUT "\n# $path\n";
720 my $s = $props->{'svn:externals'} or return;
721 $s =~ s/[\r\n]+/\n/g;
722 chomp $s;
723 $s =~ s#^#$path#gm;
724 print STDOUT "$s\n";
728 sub cmd_create_ignore {
729 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
730 $gs ||= Git::SVN->new;
731 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
732 $gs->prop_walk($gs->{path}, $r, sub {
733 my ($gs, $path, $props) = @_;
734 # $path is of the form /path/to/dir/
735 $path = '.' . $path;
736 # SVN can have attributes on empty directories,
737 # which git won't track
738 mkpath([$path]) unless -d $path;
739 my $ignore = $path . '.gitignore';
740 my $s = $props->{'svn:ignore'} or return;
741 open(GITIGNORE, '>', $ignore)
742 or fatal("Failed to open `$ignore' for writing: $!");
743 $s =~ s/[\r\n]+/\n/g;
744 chomp $s;
745 # Prefix all patterns so that the ignore doesn't apply
746 # to sub-directories.
747 $s =~ s#^#/#gm;
748 print GITIGNORE "$s\n";
749 close(GITIGNORE)
750 or fatal("Failed to close `$ignore': $!");
751 command_noisy('add', '-f', $ignore);
755 sub canonicalize_path {
756 my ($path) = @_;
757 my $dot_slash_added = 0;
758 if (substr($path, 0, 1) ne "/") {
759 $path = "./" . $path;
760 $dot_slash_added = 1;
762 # File::Spec->canonpath doesn't collapse x/../y into y (for a
763 # good reason), so let's do this manually.
764 $path =~ s#/+#/#g;
765 $path =~ s#/\.(?:/|$)#/#g;
766 $path =~ s#/[^/]+/\.\.##g;
767 $path =~ s#/$##g;
768 $path =~ s#^\./## if $dot_slash_added;
769 $path =~ s#^/##;
770 $path =~ s#^\.$##;
771 return $path;
774 # get_svnprops(PATH)
775 # ------------------
776 # Helper for cmd_propget and cmd_proplist below.
777 sub get_svnprops {
778 my $path = shift;
779 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
780 $gs ||= Git::SVN->new;
782 # prefix THE PATH by the sub-directory from which the user
783 # invoked us.
784 $path = $cmd_dir_prefix . $path;
785 fatal("No such file or directory: $path") unless -e $path;
786 my $is_dir = -d $path ? 1 : 0;
787 $path = $gs->{path} . '/' . $path;
789 # canonicalize the path (otherwise libsvn will abort or fail to
790 # find the file)
791 $path = canonicalize_path($path);
793 my $r = (defined $_revision ? $_revision : $gs->ra->get_latest_revnum);
794 my $props;
795 if ($is_dir) {
796 (undef, undef, $props) = $gs->ra->get_dir($path, $r);
798 else {
799 (undef, $props) = $gs->ra->get_file($path, $r, undef);
801 return $props;
804 # cmd_propget (PROP, PATH)
805 # ------------------------
806 # Print the SVN property PROP for PATH.
807 sub cmd_propget {
808 my ($prop, $path) = @_;
809 $path = '.' if not defined $path;
810 usage(1) if not defined $prop;
811 my $props = get_svnprops($path);
812 if (not defined $props->{$prop}) {
813 fatal("`$path' does not have a `$prop' SVN property.");
815 print $props->{$prop} . "\n";
818 # cmd_proplist (PATH)
819 # -------------------
820 # Print the list of SVN properties for PATH.
821 sub cmd_proplist {
822 my $path = shift;
823 $path = '.' if not defined $path;
824 my $props = get_svnprops($path);
825 print "Properties on '$path':\n";
826 foreach (sort keys %{$props}) {
827 print " $_\n";
831 sub cmd_multi_init {
832 my $url = shift;
833 unless (defined $_trunk || defined $_branches || defined $_tags) {
834 usage(1);
837 # there are currently some bugs that prevent multi-init/multi-fetch
838 # setups from working well without this.
839 $Git::SVN::_minimize_url = 1;
841 $_prefix = '' unless defined $_prefix;
842 if (defined $url) {
843 $url =~ s#/+$##;
844 init_subdir(@_);
846 do_git_init_db();
847 if (defined $_trunk) {
848 my $trunk_ref = $_prefix . 'trunk';
849 # try both old-style and new-style lookups:
850 my $gs_trunk = eval { Git::SVN->new($trunk_ref) };
851 unless ($gs_trunk) {
852 my ($trunk_url, $trunk_path) =
853 complete_svn_url($url, $_trunk);
854 $gs_trunk = Git::SVN->init($trunk_url, $trunk_path,
855 undef, $trunk_ref);
858 return unless defined $_branches || defined $_tags;
859 my $ra = $url ? Git::SVN::Ra->new($url) : undef;
860 complete_url_ls_init($ra, $_branches, '--branches/-b', $_prefix);
861 complete_url_ls_init($ra, $_tags, '--tags/-t', $_prefix . 'tags/');
864 sub cmd_multi_fetch {
865 my $remotes = Git::SVN::read_all_remotes();
866 foreach my $repo_id (sort keys %$remotes) {
867 if ($remotes->{$repo_id}->{url}) {
868 Git::SVN::fetch_all($repo_id, $remotes);
873 # this command is special because it requires no metadata
874 sub cmd_commit_diff {
875 my ($ta, $tb, $url) = @_;
876 my $usage = "Usage: $0 commit-diff -r<revision> ".
877 "<tree-ish> <tree-ish> [<URL>]";
878 fatal($usage) if (!defined $ta || !defined $tb);
879 my $svn_path = '';
880 if (!defined $url) {
881 my $gs = eval { Git::SVN->new };
882 if (!$gs) {
883 fatal("Needed URL or usable git-svn --id in ",
884 "the command-line\n", $usage);
886 $url = $gs->{url};
887 $svn_path = $gs->{path};
889 unless (defined $_revision) {
890 fatal("-r|--revision is a required argument\n", $usage);
892 if (defined $_message && defined $_file) {
893 fatal("Both --message/-m and --file/-F specified ",
894 "for the commit message.\n",
895 "I have no idea what you mean");
897 if (defined $_file) {
898 $_message = file_to_s($_file);
899 } else {
900 $_message ||= get_commit_entry($tb)->{log};
902 my $ra ||= Git::SVN::Ra->new($url);
903 my $r = $_revision;
904 if ($r eq 'HEAD') {
905 $r = $ra->get_latest_revnum;
906 } elsif ($r !~ /^\d+$/) {
907 die "revision argument: $r not understood by git-svn\n";
909 my %ed_opts = ( r => $r,
910 log => $_message,
911 ra => $ra,
912 tree_a => $ta,
913 tree_b => $tb,
914 editor_cb => sub { print "Committed r$_[0]\n" },
915 svn_path => $svn_path );
916 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
917 print "No changes\n$ta == $tb\n";
921 sub escape_uri_only {
922 my ($uri) = @_;
923 my @tmp;
924 foreach (split m{/}, $uri) {
925 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
926 push @tmp, $_;
928 join('/', @tmp);
931 sub escape_url {
932 my ($url) = @_;
933 if ($url =~ m#^([^:]+)://([^/]*)(.*)$#) {
934 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
935 $url = "$scheme://$domain$uri";
937 $url;
940 sub cmd_info {
941 my $path = canonicalize_path(defined($_[0]) ? $_[0] : ".");
942 my $fullpath = canonicalize_path($cmd_dir_prefix . $path);
943 if (exists $_[1]) {
944 die "Too many arguments specified\n";
947 my ($file_type, $diff_status) = find_file_type_and_diff_status($path);
949 if (!$file_type && !$diff_status) {
950 print STDERR "svn: '$path' is not under version control\n";
951 exit 1;
954 my ($url, $rev, $uuid, $gs) = working_head_info('HEAD');
955 unless ($gs) {
956 die "Unable to determine upstream SVN information from ",
957 "working tree history\n";
960 # canonicalize_path() will return "" to make libsvn 1.5.x happy,
961 $path = "." if $path eq "";
963 my $full_url = $url . ($fullpath eq "" ? "" : "/$fullpath");
965 if ($_url) {
966 print escape_url($full_url), "\n";
967 return;
970 my $result = "Path: $path\n";
971 $result .= "Name: " . basename($path) . "\n" if $file_type ne "dir";
972 $result .= "URL: " . escape_url($full_url) . "\n";
974 eval {
975 my $repos_root = $gs->repos_root;
976 Git::SVN::remove_username($repos_root);
977 $result .= "Repository Root: " . escape_url($repos_root) . "\n";
979 if ($@) {
980 $result .= "Repository Root: (offline)\n";
982 $result .= "Repository UUID: $uuid\n" unless $diff_status eq "A" &&
983 ($SVN::Core::VERSION le '1.5.4' || $file_type ne "dir");
984 $result .= "Revision: " . ($diff_status eq "A" ? 0 : $rev) . "\n";
986 $result .= "Node Kind: " .
987 ($file_type eq "dir" ? "directory" : "file") . "\n";
989 my $schedule = $diff_status eq "A"
990 ? "add"
991 : ($diff_status eq "D" ? "delete" : "normal");
992 $result .= "Schedule: $schedule\n";
994 if ($diff_status eq "A") {
995 print $result, "\n";
996 return;
999 my ($lc_author, $lc_rev, $lc_date_utc);
1000 my @args = Git::SVN::Log::git_svn_log_cmd($rev, $rev, "--", $fullpath);
1001 my $log = command_output_pipe(@args);
1002 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
1003 while (<$log>) {
1004 if (/^${esc_color}author (.+) <[^>]+> (\d+) ([\-\+]?\d+)$/o) {
1005 $lc_author = $1;
1006 $lc_date_utc = Git::SVN::Log::parse_git_date($2, $3);
1007 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
1008 (undef, $lc_rev, undef) = ::extract_metadata($1);
1011 close $log;
1013 Git::SVN::Log::set_local_timezone();
1015 $result .= "Last Changed Author: $lc_author\n";
1016 $result .= "Last Changed Rev: $lc_rev\n";
1017 $result .= "Last Changed Date: " .
1018 Git::SVN::Log::format_svn_date($lc_date_utc) . "\n";
1020 if ($file_type ne "dir") {
1021 my $text_last_updated_date =
1022 ($diff_status eq "D" ? $lc_date_utc : (stat $path)[9]);
1023 $result .=
1024 "Text Last Updated: " .
1025 Git::SVN::Log::format_svn_date($text_last_updated_date) .
1026 "\n";
1027 my $checksum;
1028 if ($diff_status eq "D") {
1029 my ($fh, $ctx) =
1030 command_output_pipe(qw(cat-file blob), "HEAD:$path");
1031 if ($file_type eq "link") {
1032 my $file_name = <$fh>;
1033 $checksum = md5sum("link $file_name");
1034 } else {
1035 $checksum = md5sum($fh);
1037 command_close_pipe($fh, $ctx);
1038 } elsif ($file_type eq "link") {
1039 my $file_name =
1040 command(qw(cat-file blob), "HEAD:$path");
1041 $checksum =
1042 md5sum("link " . $file_name);
1043 } else {
1044 open FILE, "<", $path or die $!;
1045 $checksum = md5sum(\*FILE);
1046 close FILE or die $!;
1048 $result .= "Checksum: " . $checksum . "\n";
1051 print $result, "\n";
1054 ########################### utility functions #########################
1056 sub rebase_cmd {
1057 my @cmd = qw/rebase/;
1058 push @cmd, '-v' if $_verbose;
1059 push @cmd, qw/--merge/ if $_merge;
1060 push @cmd, "--strategy=$_strategy" if $_strategy;
1061 @cmd;
1064 sub post_fetch_checkout {
1065 return if $_no_checkout;
1066 my $gs = $Git::SVN::_head or return;
1067 return if verify_ref('refs/heads/master^0');
1069 my $valid_head = verify_ref('HEAD^0');
1070 command_noisy(qw(update-ref refs/heads/master), $gs->refname);
1071 return if ($valid_head || !verify_ref('HEAD^0'));
1073 return if $ENV{GIT_DIR} !~ m#^(?:.*/)?\.git$#;
1074 my $index = $ENV{GIT_INDEX_FILE} || "$ENV{GIT_DIR}/index";
1075 return if -f $index;
1077 return if command_oneline(qw/rev-parse --is-inside-work-tree/) eq 'false';
1078 return if command_oneline(qw/rev-parse --is-inside-git-dir/) eq 'true';
1079 command_noisy(qw/read-tree -m -u -v HEAD HEAD/);
1080 print STDERR "Checked out HEAD:\n ",
1081 $gs->full_url, " r", $gs->last_rev, "\n";
1084 sub complete_svn_url {
1085 my ($url, $path) = @_;
1086 $path =~ s#/+$##;
1087 if ($path !~ m#^[a-z\+]+://#) {
1088 if (!defined $url || $url !~ m#^[a-z\+]+://#) {
1089 fatal("E: '$path' is not a complete URL ",
1090 "and a separate URL is not specified");
1092 return ($url, $path);
1094 return ($path, '');
1097 sub complete_url_ls_init {
1098 my ($ra, $repo_path, $switch, $pfx) = @_;
1099 unless ($repo_path) {
1100 print STDERR "W: $switch not specified\n";
1101 return;
1103 $repo_path =~ s#/+$##;
1104 if ($repo_path =~ m#^[a-z\+]+://#) {
1105 $ra = Git::SVN::Ra->new($repo_path);
1106 $repo_path = '';
1107 } else {
1108 $repo_path =~ s#^/+##;
1109 unless ($ra) {
1110 fatal("E: '$repo_path' is not a complete URL ",
1111 "and a separate URL is not specified");
1114 my $url = $ra->{url};
1115 my $gs = Git::SVN->init($url, undef, undef, undef, 1);
1116 my $k = "svn-remote.$gs->{repo_id}.url";
1117 my $orig_url = eval { command_oneline(qw/config --get/, $k) };
1118 if ($orig_url && ($orig_url ne $gs->{url})) {
1119 die "$k already set: $orig_url\n",
1120 "wanted to set to: $gs->{url}\n";
1122 command_oneline('config', $k, $gs->{url}) unless $orig_url;
1123 my $remote_path = "$ra->{svn_path}/$repo_path";
1124 $remote_path =~ s#/+#/#g;
1125 $remote_path =~ s#^/##g;
1126 $remote_path .= "/*" if $remote_path !~ /\*/;
1127 my ($n) = ($switch =~ /^--(\w+)/);
1128 if (length $pfx && $pfx !~ m#/$#) {
1129 die "--prefix='$pfx' must have a trailing slash '/'\n";
1131 command_noisy('config',
1132 "svn-remote.$gs->{repo_id}.$n",
1133 "$remote_path:refs/remotes/$pfx*" .
1134 ('/*' x (($remote_path =~ tr/*/*/) - 1)) );
1137 sub verify_ref {
1138 my ($ref) = @_;
1139 eval { command_oneline([ 'rev-parse', '--verify', $ref ],
1140 { STDERR => 0 }); };
1143 sub get_tree_from_treeish {
1144 my ($treeish) = @_;
1145 # $treeish can be a symbolic ref, too:
1146 my $type = command_oneline(qw/cat-file -t/, $treeish);
1147 my $expected;
1148 while ($type eq 'tag') {
1149 ($treeish, $type) = command(qw/cat-file tag/, $treeish);
1151 if ($type eq 'commit') {
1152 $expected = (grep /^tree /, command(qw/cat-file commit/,
1153 $treeish))[0];
1154 ($expected) = ($expected =~ /^tree ($sha1)$/o);
1155 die "Unable to get tree from $treeish\n" unless $expected;
1156 } elsif ($type eq 'tree') {
1157 $expected = $treeish;
1158 } else {
1159 die "$treeish is a $type, expected tree, tag or commit\n";
1161 return $expected;
1164 sub get_commit_entry {
1165 my ($treeish) = shift;
1166 my %log_entry = ( log => '', tree => get_tree_from_treeish($treeish) );
1167 my $commit_editmsg = "$ENV{GIT_DIR}/COMMIT_EDITMSG";
1168 my $commit_msg = "$ENV{GIT_DIR}/COMMIT_MSG";
1169 open my $log_fh, '>', $commit_editmsg or croak $!;
1171 my $type = command_oneline(qw/cat-file -t/, $treeish);
1172 if ($type eq 'commit' || $type eq 'tag') {
1173 my ($msg_fh, $ctx) = command_output_pipe('cat-file',
1174 $type, $treeish);
1175 my $in_msg = 0;
1176 my $author;
1177 my $saw_from = 0;
1178 my $msgbuf = "";
1179 while (<$msg_fh>) {
1180 if (!$in_msg) {
1181 $in_msg = 1 if (/^\s*$/);
1182 $author = $1 if (/^author (.*>)/);
1183 } elsif (/^git-svn-id: /) {
1184 # skip this for now, we regenerate the
1185 # correct one on re-fetch anyways
1186 # TODO: set *:merge properties or like...
1187 } else {
1188 if (/^From:/ || /^Signed-off-by:/) {
1189 $saw_from = 1;
1191 $msgbuf .= $_;
1194 $msgbuf =~ s/\s+$//s;
1195 if ($Git::SVN::_add_author_from && defined($author)
1196 && !$saw_from) {
1197 $msgbuf .= "\n\nFrom: $author";
1199 print $log_fh $msgbuf or croak $!;
1200 command_close_pipe($msg_fh, $ctx);
1202 close $log_fh or croak $!;
1204 if ($_edit || ($type eq 'tree')) {
1205 my $editor = $ENV{VISUAL} || $ENV{EDITOR} || 'vi';
1206 # TODO: strip out spaces, comments, like git-commit.sh
1207 system($editor, $commit_editmsg);
1209 rename $commit_editmsg, $commit_msg or croak $!;
1211 require Encode;
1212 # SVN requires messages to be UTF-8 when entering the repo
1213 local $/;
1214 open $log_fh, '<', $commit_msg or croak $!;
1215 binmode $log_fh;
1216 chomp($log_entry{log} = <$log_fh>);
1218 my $enc = Git::config('i18n.commitencoding') || 'UTF-8';
1219 my $msg = $log_entry{log};
1221 eval { $msg = Encode::decode($enc, $msg, 1) };
1222 if ($@) {
1223 die "Could not decode as $enc:\n", $msg,
1224 "\nPerhaps you need to set i18n.commitencoding\n";
1227 eval { $msg = Encode::encode('UTF-8', $msg, 1) };
1228 die "Could not encode as UTF-8:\n$msg\n" if $@;
1230 $log_entry{log} = $msg;
1232 close $log_fh or croak $!;
1234 unlink $commit_msg;
1235 \%log_entry;
1238 sub s_to_file {
1239 my ($str, $file, $mode) = @_;
1240 open my $fd,'>',$file or croak $!;
1241 print $fd $str,"\n" or croak $!;
1242 close $fd or croak $!;
1243 chmod ($mode &~ umask, $file) if (defined $mode);
1246 sub file_to_s {
1247 my $file = shift;
1248 open my $fd,'<',$file or croak "$!: file: $file\n";
1249 local $/;
1250 my $ret = <$fd>;
1251 close $fd or croak $!;
1252 $ret =~ s/\s*$//s;
1253 return $ret;
1256 # '<svn username> = real-name <email address>' mapping based on git-svnimport:
1257 sub load_authors {
1258 open my $authors, '<', $_authors or die "Can't open $_authors $!\n";
1259 my $log = $cmd eq 'log';
1260 while (<$authors>) {
1261 chomp;
1262 next unless /^(.+?|\(no author\))\s*=\s*(.+?)\s*<(.+)>\s*$/;
1263 my ($user, $name, $email) = ($1, $2, $3);
1264 if ($log) {
1265 $Git::SVN::Log::rusers{"$name <$email>"} = $user;
1266 } else {
1267 $users{$user} = [$name, $email];
1270 close $authors or croak $!;
1273 # convert GetOpt::Long specs for use by git-config
1274 sub read_repo_config {
1275 return unless -d $ENV{GIT_DIR};
1276 my $opts = shift;
1277 my @config_only;
1278 foreach my $o (keys %$opts) {
1279 # if we have mixedCase and a long option-only, then
1280 # it's a config-only variable that we don't need for
1281 # the command-line.
1282 push @config_only, $o if ($o =~ /[A-Z]/ && $o =~ /^[a-z]+$/i);
1283 my $v = $opts->{$o};
1284 my ($key) = ($o =~ /^([a-zA-Z\-]+)/);
1285 $key =~ s/-//g;
1286 my $arg = 'git config';
1287 $arg .= ' --int' if ($o =~ /[:=]i$/);
1288 $arg .= ' --bool' if ($o !~ /[:=][sfi]$/);
1289 if (ref $v eq 'ARRAY') {
1290 chomp(my @tmp = `$arg --get-all svn.$key`);
1291 @$v = @tmp if @tmp;
1292 } else {
1293 chomp(my $tmp = `$arg --get svn.$key`);
1294 if ($tmp && !($arg =~ / --bool/ && $tmp eq 'false')) {
1295 $$v = $tmp;
1299 delete @$opts{@config_only} if @config_only;
1302 sub extract_metadata {
1303 my $id = shift or return (undef, undef, undef);
1304 my ($url, $rev, $uuid) = ($id =~ /^\s*git-svn-id:\s+(.*)\@(\d+)
1305 \s([a-f\d\-]+)$/x);
1306 if (!defined $rev || !$uuid || !$url) {
1307 # some of the original repositories I made had
1308 # identifiers like this:
1309 ($rev, $uuid) = ($id =~/^\s*git-svn-id:\s(\d+)\@([a-f\d\-]+)/);
1311 return ($url, $rev, $uuid);
1314 sub cmt_metadata {
1315 return extract_metadata((grep(/^git-svn-id: /,
1316 command(qw/cat-file commit/, shift)))[-1]);
1319 sub cmt_sha2rev_batch {
1320 my %s2r;
1321 my ($pid, $in, $out, $ctx) = command_bidi_pipe(qw/cat-file --batch/);
1322 my $list = shift;
1324 foreach my $sha (@{$list}) {
1325 my $first = 1;
1326 my $size = 0;
1327 print $out $sha, "\n";
1329 while (my $line = <$in>) {
1330 if ($first && $line =~ /^[[:xdigit:]]{40}\smissing$/) {
1331 last;
1332 } elsif ($first &&
1333 $line =~ /^[[:xdigit:]]{40}\scommit\s(\d+)$/) {
1334 $first = 0;
1335 $size = $1;
1336 next;
1337 } elsif ($line =~ /^(git-svn-id: )/) {
1338 my (undef, $rev, undef) =
1339 extract_metadata($line);
1340 $s2r{$sha} = $rev;
1343 $size -= length($line);
1344 last if ($size == 0);
1348 command_close_bidi_pipe($pid, $in, $out, $ctx);
1350 return \%s2r;
1353 sub working_head_info {
1354 my ($head, $refs) = @_;
1355 my @args = ('log', '--no-color', '--first-parent', '--pretty=medium');
1356 my ($fh, $ctx) = command_output_pipe(@args, $head);
1357 my $hash;
1358 my %max;
1359 while (<$fh>) {
1360 if ( m{^commit ($::sha1)$} ) {
1361 unshift @$refs, $hash if $hash and $refs;
1362 $hash = $1;
1363 next;
1365 next unless s{^\s*(git-svn-id:)}{$1};
1366 my ($url, $rev, $uuid) = extract_metadata($_);
1367 if (defined $url && defined $rev) {
1368 next if $max{$url} and $max{$url} < $rev;
1369 if (my $gs = Git::SVN->find_by_url($url)) {
1370 my $c = $gs->rev_map_get($rev, $uuid);
1371 if ($c && $c eq $hash) {
1372 close $fh; # break the pipe
1373 return ($url, $rev, $uuid, $gs);
1374 } else {
1375 $max{$url} ||= $gs->rev_map_max;
1380 command_close_pipe($fh, $ctx);
1381 (undef, undef, undef, undef);
1384 sub read_commit_parents {
1385 my ($parents, $c) = @_;
1386 chomp(my $p = command_oneline(qw/rev-list --parents -1/, $c));
1387 $p =~ s/^($c)\s*// or die "rev-list --parents -1 $c failed!\n";
1388 @{$parents->{$c}} = split(/ /, $p);
1391 sub linearize_history {
1392 my ($gs, $refs) = @_;
1393 my %parents;
1394 foreach my $c (@$refs) {
1395 read_commit_parents(\%parents, $c);
1398 my @linear_refs;
1399 my %skip = ();
1400 my $last_svn_commit = $gs->last_commit;
1401 foreach my $c (reverse @$refs) {
1402 next if $c eq $last_svn_commit;
1403 last if $skip{$c};
1405 unshift @linear_refs, $c;
1406 $skip{$c} = 1;
1408 # we only want the first parent to diff against for linear
1409 # history, we save the rest to inject when we finalize the
1410 # svn commit
1411 my $fp_a = verify_ref("$c~1");
1412 my $fp_b = shift @{$parents{$c}} if $parents{$c};
1413 if (!$fp_a || !$fp_b) {
1414 die "Commit $c\n",
1415 "has no parent commit, and therefore ",
1416 "nothing to diff against.\n",
1417 "You should be working from a repository ",
1418 "originally created by git-svn\n";
1420 if ($fp_a ne $fp_b) {
1421 die "$c~1 = $fp_a, however parsing commit $c ",
1422 "revealed that:\n$c~1 = $fp_b\nBUG!\n";
1425 foreach my $p (@{$parents{$c}}) {
1426 $skip{$p} = 1;
1429 (\@linear_refs, \%parents);
1432 sub find_file_type_and_diff_status {
1433 my ($path) = @_;
1434 return ('dir', '') if $path eq '';
1436 my $diff_output =
1437 command_oneline(qw(diff --cached --name-status --), $path) || "";
1438 my $diff_status = (split(' ', $diff_output))[0] || "";
1440 my $ls_tree = command_oneline(qw(ls-tree HEAD), $path) || "";
1442 return (undef, undef) if !$diff_status && !$ls_tree;
1444 if ($diff_status eq "A") {
1445 return ("link", $diff_status) if -l $path;
1446 return ("dir", $diff_status) if -d $path;
1447 return ("file", $diff_status);
1450 my $mode = (split(' ', $ls_tree))[0] || "";
1452 return ("link", $diff_status) if $mode eq "120000";
1453 return ("dir", $diff_status) if $mode eq "040000";
1454 return ("file", $diff_status);
1457 sub md5sum {
1458 my $arg = shift;
1459 my $ref = ref $arg;
1460 my $md5 = Digest::MD5->new();
1461 if ($ref eq 'GLOB' || $ref eq 'IO::File' || $ref eq 'File::Temp') {
1462 $md5->addfile($arg) or croak $!;
1463 } elsif ($ref eq 'SCALAR') {
1464 $md5->add($$arg) or croak $!;
1465 } elsif (!$ref) {
1466 $md5->add($arg) or croak $!;
1467 } else {
1468 ::fatal "Can't provide MD5 hash for unknown ref type: '", $ref, "'";
1470 return $md5->hexdigest();
1473 package Git::SVN;
1474 use strict;
1475 use warnings;
1476 use Fcntl qw/:DEFAULT :seek/;
1477 use constant rev_map_fmt => 'NH40';
1478 use vars qw/$default_repo_id $default_ref_id $_no_metadata $_follow_parent
1479 $_repack $_repack_flags $_use_svm_props $_head
1480 $_use_svnsync_props $no_reuse_existing $_minimize_url
1481 $_use_log_author $_add_author_from $_localtime/;
1482 use Carp qw/croak/;
1483 use File::Path qw/mkpath/;
1484 use File::Copy qw/copy/;
1485 use IPC::Open3;
1487 my ($_gc_nr, $_gc_period);
1489 # properties that we do not log:
1490 my %SKIP_PROP;
1491 BEGIN {
1492 %SKIP_PROP = map { $_ => 1 } qw/svn:wc:ra_dav:version-url
1493 svn:special svn:executable
1494 svn:entry:committed-rev
1495 svn:entry:last-author
1496 svn:entry:uuid
1497 svn:entry:committed-date/;
1499 # some options are read globally, but can be overridden locally
1500 # per [svn-remote "..."] section. Command-line options will *NOT*
1501 # override options set in an [svn-remote "..."] section
1502 no strict 'refs';
1503 for my $option (qw/follow_parent no_metadata use_svm_props
1504 use_svnsync_props/) {
1505 my $key = $option;
1506 $key =~ tr/_//d;
1507 my $prop = "-$option";
1508 *$option = sub {
1509 my ($self) = @_;
1510 return $self->{$prop} if exists $self->{$prop};
1511 my $k = "svn-remote.$self->{repo_id}.$key";
1512 eval { command_oneline(qw/config --get/, $k) };
1513 if ($@) {
1514 $self->{$prop} = ${"Git::SVN::_$option"};
1515 } else {
1516 my $v = command_oneline(qw/config --bool/,$k);
1517 $self->{$prop} = $v eq 'false' ? 0 : 1;
1519 return $self->{$prop};
1525 my (%LOCKFILES, %INDEX_FILES);
1526 END {
1527 unlink keys %LOCKFILES if %LOCKFILES;
1528 unlink keys %INDEX_FILES if %INDEX_FILES;
1531 sub resolve_local_globs {
1532 my ($url, $fetch, $glob_spec) = @_;
1533 return unless defined $glob_spec;
1534 my $ref = $glob_spec->{ref};
1535 my $path = $glob_spec->{path};
1536 foreach (command(qw#for-each-ref --format=%(refname) refs/remotes#)) {
1537 next unless m#^refs/remotes/$ref->{regex}$#;
1538 my $p = $1;
1539 my $pathname = desanitize_refname($path->full_path($p));
1540 my $refname = desanitize_refname($ref->full_path($p));
1541 if (my $existing = $fetch->{$pathname}) {
1542 if ($existing ne $refname) {
1543 die "Refspec conflict:\n",
1544 "existing: refs/remotes/$existing\n",
1545 " globbed: refs/remotes/$refname\n";
1547 my $u = (::cmt_metadata("refs/remotes/$refname"))[0];
1548 $u =~ s!^\Q$url\E(/|$)!! or die
1549 "refs/remotes/$refname: '$url' not found in '$u'\n";
1550 if ($pathname ne $u) {
1551 warn "W: Refspec glob conflict ",
1552 "(ref: refs/remotes/$refname):\n",
1553 "expected path: $pathname\n",
1554 " real path: $u\n",
1555 "Continuing ahead with $u\n";
1556 next;
1558 } else {
1559 $fetch->{$pathname} = $refname;
1564 sub parse_revision_argument {
1565 my ($base, $head) = @_;
1566 if (!defined $::_revision || $::_revision eq 'BASE:HEAD') {
1567 return ($base, $head);
1569 return ($1, $2) if ($::_revision =~ /^(\d+):(\d+)$/);
1570 return ($::_revision, $::_revision) if ($::_revision =~ /^\d+$/);
1571 return ($head, $head) if ($::_revision eq 'HEAD');
1572 return ($base, $1) if ($::_revision =~ /^BASE:(\d+)$/);
1573 return ($1, $head) if ($::_revision =~ /^(\d+):HEAD$/);
1574 die "revision argument: $::_revision not understood by git-svn\n";
1577 sub fetch_all {
1578 my ($repo_id, $remotes) = @_;
1579 if (ref $repo_id) {
1580 my $gs = $repo_id;
1581 $repo_id = undef;
1582 $repo_id = $gs->{repo_id};
1584 $remotes ||= read_all_remotes();
1585 my $remote = $remotes->{$repo_id} or
1586 die "[svn-remote \"$repo_id\"] unknown\n";
1587 my $fetch = $remote->{fetch};
1588 my $url = $remote->{url} or die "svn-remote.$repo_id.url not defined\n";
1589 my (@gs, @globs);
1590 my $ra = Git::SVN::Ra->new($url);
1591 my $uuid = $ra->get_uuid;
1592 my $head = $ra->get_latest_revnum;
1593 my $base = defined $fetch ? $head : 0;
1595 # read the max revs for wildcard expansion (branches/*, tags/*)
1596 foreach my $t (qw/branches tags/) {
1597 defined $remote->{$t} or next;
1598 push @globs, $remote->{$t};
1599 my $max_rev = eval { tmp_config(qw/--int --get/,
1600 "svn-remote.$repo_id.${t}-maxRev") };
1601 if (defined $max_rev && ($max_rev < $base)) {
1602 $base = $max_rev;
1603 } elsif (!defined $max_rev) {
1604 $base = 0;
1608 if ($fetch) {
1609 foreach my $p (sort keys %$fetch) {
1610 my $gs = Git::SVN->new($fetch->{$p}, $repo_id, $p);
1611 my $lr = $gs->rev_map_max;
1612 if (defined $lr) {
1613 $base = $lr if ($lr < $base);
1615 push @gs, $gs;
1619 ($base, $head) = parse_revision_argument($base, $head);
1620 $ra->gs_fetch_loop_common($base, $head, \@gs, \@globs);
1623 sub read_all_remotes {
1624 my $r = {};
1625 my $use_svm_props = eval { command_oneline(qw/config --bool
1626 svn.useSvmProps/) };
1627 $use_svm_props = $use_svm_props eq 'true' if $use_svm_props;
1628 foreach (grep { s/^svn-remote\.// } command(qw/config -l/)) {
1629 if (m!^(.+)\.fetch=\s*(.*)\s*:\s*(.+)\s*$!) {
1630 my ($remote, $local_ref, $_remote_ref) = ($1, $2, $3);
1631 die("svn-remote.$remote: remote ref '$_remote_ref' "
1632 . "must start with 'refs/remotes/'\n")
1633 unless $_remote_ref =~ m{^refs/remotes/(.+)};
1634 my $remote_ref = $1;
1635 $local_ref =~ s{^/}{};
1636 $r->{$remote}->{fetch}->{$local_ref} = $remote_ref;
1637 $r->{$remote}->{svm} = {} if $use_svm_props;
1638 } elsif (m!^(.+)\.usesvmprops=\s*(.*)\s*$!) {
1639 $r->{$1}->{svm} = {};
1640 } elsif (m!^(.+)\.url=\s*(.*)\s*$!) {
1641 $r->{$1}->{url} = $2;
1642 } elsif (m!^(.+)\.(branches|tags)=
1643 (.*):refs/remotes/(.+)\s*$/!x) {
1644 my ($p, $g) = ($3, $4);
1645 my $rs = $r->{$1}->{$2} = {
1646 t => $2,
1647 remote => $1,
1648 path => Git::SVN::GlobSpec->new($p),
1649 ref => Git::SVN::GlobSpec->new($g) };
1650 if (length($rs->{ref}->{right}) != 0) {
1651 die "The '*' glob character must be the last ",
1652 "character of '$g'\n";
1657 map {
1658 if (defined $r->{$_}->{svm}) {
1659 my $svm;
1660 eval {
1661 my $section = "svn-remote.$_";
1662 $svm = {
1663 source => tmp_config('--get',
1664 "$section.svm-source"),
1665 replace => tmp_config('--get',
1666 "$section.svm-replace"),
1669 $r->{$_}->{svm} = $svm;
1671 } keys %$r;
1676 sub init_vars {
1677 $_gc_nr = $_gc_period = 1000;
1678 if (defined $_repack || defined $_repack_flags) {
1679 warn "Repack options are obsolete; they have no effect.\n";
1683 sub verify_remotes_sanity {
1684 return unless -d $ENV{GIT_DIR};
1685 my %seen;
1686 foreach (command(qw/config -l/)) {
1687 if (m!^svn-remote\.(?:.+)\.fetch=.*:refs/remotes/(\S+)\s*$!) {
1688 if ($seen{$1}) {
1689 die "Remote ref refs/remote/$1 is tracked by",
1690 "\n \"$_\"\nand\n \"$seen{$1}\"\n",
1691 "Please resolve this ambiguity in ",
1692 "your git configuration file before ",
1693 "continuing\n";
1695 $seen{$1} = $_;
1700 sub find_existing_remote {
1701 my ($url, $remotes) = @_;
1702 return undef if $no_reuse_existing;
1703 my $existing;
1704 foreach my $repo_id (keys %$remotes) {
1705 my $u = $remotes->{$repo_id}->{url} or next;
1706 next if $u ne $url;
1707 $existing = $repo_id;
1708 last;
1710 $existing;
1713 sub init_remote_config {
1714 my ($self, $url, $no_write) = @_;
1715 $url =~ s!/+$!!; # strip trailing slash
1716 my $r = read_all_remotes();
1717 my $existing = find_existing_remote($url, $r);
1718 if ($existing) {
1719 unless ($no_write) {
1720 print STDERR "Using existing ",
1721 "[svn-remote \"$existing\"]\n";
1723 $self->{repo_id} = $existing;
1724 } elsif ($_minimize_url) {
1725 my $min_url = Git::SVN::Ra->new($url)->minimize_url;
1726 $existing = find_existing_remote($min_url, $r);
1727 if ($existing) {
1728 unless ($no_write) {
1729 print STDERR "Using existing ",
1730 "[svn-remote \"$existing\"]\n";
1732 $self->{repo_id} = $existing;
1734 if ($min_url ne $url) {
1735 unless ($no_write) {
1736 print STDERR "Using higher level of URL: ",
1737 "$url => $min_url\n";
1739 my $old_path = $self->{path};
1740 $self->{path} = $url;
1741 $self->{path} =~ s!^\Q$min_url\E(/|$)!!;
1742 if (length $old_path) {
1743 $self->{path} .= "/$old_path";
1745 $url = $min_url;
1748 my $orig_url;
1749 if (!$existing) {
1750 # verify that we aren't overwriting anything:
1751 $orig_url = eval {
1752 command_oneline('config', '--get',
1753 "svn-remote.$self->{repo_id}.url")
1755 if ($orig_url && ($orig_url ne $url)) {
1756 die "svn-remote.$self->{repo_id}.url already set: ",
1757 "$orig_url\nwanted to set to: $url\n";
1760 my ($xrepo_id, $xpath) = find_ref($self->refname);
1761 if (defined $xpath) {
1762 die "svn-remote.$xrepo_id.fetch already set to track ",
1763 "$xpath:refs/remotes/", $self->refname, "\n";
1765 unless ($no_write) {
1766 command_noisy('config',
1767 "svn-remote.$self->{repo_id}.url", $url);
1768 $self->{path} =~ s{^/}{};
1769 command_noisy('config', '--add',
1770 "svn-remote.$self->{repo_id}.fetch",
1771 "$self->{path}:".$self->refname);
1773 $self->{url} = $url;
1776 sub find_by_url { # repos_root and, path are optional
1777 my ($class, $full_url, $repos_root, $path) = @_;
1779 return undef unless defined $full_url;
1780 remove_username($full_url);
1781 remove_username($repos_root) if defined $repos_root;
1782 my $remotes = read_all_remotes();
1783 if (defined $full_url && defined $repos_root && !defined $path) {
1784 $path = $full_url;
1785 $path =~ s#^\Q$repos_root\E(?:/|$)##;
1787 foreach my $repo_id (keys %$remotes) {
1788 my $u = $remotes->{$repo_id}->{url} or next;
1789 remove_username($u);
1790 next if defined $repos_root && $repos_root ne $u;
1792 my $fetch = $remotes->{$repo_id}->{fetch} || {};
1793 foreach (qw/branches tags/) {
1794 resolve_local_globs($u, $fetch,
1795 $remotes->{$repo_id}->{$_});
1797 my $p = $path;
1798 my $rwr = rewrite_root({repo_id => $repo_id});
1799 my $svm = $remotes->{$repo_id}->{svm}
1800 if defined $remotes->{$repo_id}->{svm};
1801 unless (defined $p) {
1802 $p = $full_url;
1803 my $z = $u;
1804 my $prefix = '';
1805 if ($rwr) {
1806 $z = $rwr;
1807 remove_username($z);
1808 } elsif (defined $svm) {
1809 $z = $svm->{source};
1810 $prefix = $svm->{replace};
1811 $prefix =~ s#^\Q$u\E(?:/|$)##;
1812 $prefix =~ s#/$##;
1814 $p =~ s#^\Q$z\E(?:/|$)#$prefix# or next;
1816 foreach my $f (keys %$fetch) {
1817 next if $f ne $p;
1818 return Git::SVN->new($fetch->{$f}, $repo_id, $f);
1821 undef;
1824 sub init {
1825 my ($class, $url, $path, $repo_id, $ref_id, $no_write) = @_;
1826 my $self = _new($class, $repo_id, $ref_id, $path);
1827 if (defined $url) {
1828 $self->init_remote_config($url, $no_write);
1830 $self;
1833 sub find_ref {
1834 my ($ref_id) = @_;
1835 foreach (command(qw/config -l/)) {
1836 next unless m!^svn-remote\.(.+)\.fetch=
1837 \s*(.*)\s*:\s*refs/remotes/(.+)\s*$!x;
1838 my ($repo_id, $path, $ref) = ($1, $2, $3);
1839 if ($ref eq $ref_id) {
1840 $path = '' if ($path =~ m#^\./?#);
1841 return ($repo_id, $path);
1844 (undef, undef, undef);
1847 sub new {
1848 my ($class, $ref_id, $repo_id, $path) = @_;
1849 if (defined $ref_id && !defined $repo_id && !defined $path) {
1850 ($repo_id, $path) = find_ref($ref_id);
1851 if (!defined $repo_id) {
1852 die "Could not find a \"svn-remote.*.fetch\" key ",
1853 "in the repository configuration matching: ",
1854 "refs/remotes/$ref_id\n";
1857 my $self = _new($class, $repo_id, $ref_id, $path);
1858 if (!defined $self->{path} || !length $self->{path}) {
1859 my $fetch = command_oneline('config', '--get',
1860 "svn-remote.$repo_id.fetch",
1861 ":refs/remotes/$ref_id\$") or
1862 die "Failed to read \"svn-remote.$repo_id.fetch\" ",
1863 "\":refs/remotes/$ref_id\$\" in config\n";
1864 ($self->{path}, undef) = split(/\s*:\s*/, $fetch);
1866 $self->{url} = command_oneline('config', '--get',
1867 "svn-remote.$repo_id.url") or
1868 die "Failed to read \"svn-remote.$repo_id.url\" in config\n";
1869 $self->rebuild;
1870 $self;
1873 sub refname {
1874 my ($refname) = "refs/remotes/$_[0]->{ref_id}" ;
1876 # It cannot end with a slash /, we'll throw up on this because
1877 # SVN can't have directories with a slash in their name, either:
1878 if ($refname =~ m{/$}) {
1879 die "ref: '$refname' ends with a trailing slash, this is ",
1880 "not permitted by git nor Subversion\n";
1883 # It cannot have ASCII control character space, tilde ~, caret ^,
1884 # colon :, question-mark ?, asterisk *, space, or open bracket [
1885 # anywhere.
1887 # Additionally, % must be escaped because it is used for escaping
1888 # and we want our escaped refname to be reversible
1889 $refname =~ s{([ \%~\^:\?\*\[\t])}{uc sprintf('%%%02x',ord($1))}eg;
1891 # no slash-separated component can begin with a dot .
1892 # /.* becomes /%2E*
1893 $refname =~ s{/\.}{/%2E}g;
1895 # It cannot have two consecutive dots .. anywhere
1896 # .. becomes %2E%2E
1897 $refname =~ s{\.\.}{%2E%2E}g;
1899 return $refname;
1902 sub desanitize_refname {
1903 my ($refname) = @_;
1904 $refname =~ s{%(?:([0-9A-F]{2}))}{chr hex($1)}eg;
1905 return $refname;
1908 sub svm_uuid {
1909 my ($self) = @_;
1910 return $self->{svm}->{uuid} if $self->svm;
1911 $self->ra;
1912 unless ($self->{svm}) {
1913 die "SVM UUID not cached, and reading remotely failed\n";
1915 $self->{svm}->{uuid};
1918 sub svm {
1919 my ($self) = @_;
1920 return $self->{svm} if $self->{svm};
1921 my $svm;
1922 # see if we have it in our config, first:
1923 eval {
1924 my $section = "svn-remote.$self->{repo_id}";
1925 $svm = {
1926 source => tmp_config('--get', "$section.svm-source"),
1927 uuid => tmp_config('--get', "$section.svm-uuid"),
1928 replace => tmp_config('--get', "$section.svm-replace"),
1931 if ($svm && $svm->{source} && $svm->{uuid} && $svm->{replace}) {
1932 $self->{svm} = $svm;
1934 $self->{svm};
1937 sub _set_svm_vars {
1938 my ($self, $ra) = @_;
1939 return $ra if $self->svm;
1941 my @err = ( "useSvmProps set, but failed to read SVM properties\n",
1942 "(svm:source, svm:uuid) ",
1943 "from the following URLs:\n" );
1944 sub read_svm_props {
1945 my ($self, $ra, $path, $r) = @_;
1946 my $props = ($ra->get_dir($path, $r))[2];
1947 my $src = $props->{'svm:source'};
1948 my $uuid = $props->{'svm:uuid'};
1949 return undef if (!$src || !$uuid);
1951 chomp($src, $uuid);
1953 $uuid =~ m{^[0-9a-f\-]{30,}$}
1954 or die "doesn't look right - svm:uuid is '$uuid'\n";
1956 # the '!' is used to mark the repos_root!/relative/path
1957 $src =~ s{/?!/?}{/};
1958 $src =~ s{/+$}{}; # no trailing slashes please
1959 # username is of no interest
1960 $src =~ s{(^[a-z\+]*://)[^/@]*@}{$1};
1962 my $replace = $ra->{url};
1963 $replace .= "/$path" if length $path;
1965 my $section = "svn-remote.$self->{repo_id}";
1966 tmp_config("$section.svm-source", $src);
1967 tmp_config("$section.svm-replace", $replace);
1968 tmp_config("$section.svm-uuid", $uuid);
1969 $self->{svm} = {
1970 source => $src,
1971 uuid => $uuid,
1972 replace => $replace
1976 my $r = $ra->get_latest_revnum;
1977 my $path = $self->{path};
1978 my %tried;
1979 while (length $path) {
1980 unless ($tried{"$self->{url}/$path"}) {
1981 return $ra if $self->read_svm_props($ra, $path, $r);
1982 $tried{"$self->{url}/$path"} = 1;
1984 $path =~ s#/?[^/]+$##;
1986 die "Path: '$path' should be ''\n" if $path ne '';
1987 return $ra if $self->read_svm_props($ra, $path, $r);
1988 $tried{"$self->{url}/$path"} = 1;
1990 if ($ra->{repos_root} eq $self->{url}) {
1991 die @err, (map { " $_\n" } keys %tried), "\n";
1994 # nope, make sure we're connected to the repository root:
1995 my $ok;
1996 my @tried_b;
1997 $path = $ra->{svn_path};
1998 $ra = Git::SVN::Ra->new($ra->{repos_root});
1999 while (length $path) {
2000 unless ($tried{"$ra->{url}/$path"}) {
2001 $ok = $self->read_svm_props($ra, $path, $r);
2002 last if $ok;
2003 $tried{"$ra->{url}/$path"} = 1;
2005 $path =~ s#/?[^/]+$##;
2007 die "Path: '$path' should be ''\n" if $path ne '';
2008 $ok ||= $self->read_svm_props($ra, $path, $r);
2009 $tried{"$ra->{url}/$path"} = 1;
2010 if (!$ok) {
2011 die @err, (map { " $_\n" } keys %tried), "\n";
2013 Git::SVN::Ra->new($self->{url});
2016 sub svnsync {
2017 my ($self) = @_;
2018 return $self->{svnsync} if $self->{svnsync};
2020 if ($self->no_metadata) {
2021 die "Can't have both 'noMetadata' and ",
2022 "'useSvnsyncProps' options set!\n";
2024 if ($self->rewrite_root) {
2025 die "Can't have both 'useSvnsyncProps' and 'rewriteRoot' ",
2026 "options set!\n";
2029 my $svnsync;
2030 # see if we have it in our config, first:
2031 eval {
2032 my $section = "svn-remote.$self->{repo_id}";
2034 my $url = tmp_config('--get', "$section.svnsync-url");
2035 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2036 die "doesn't look right - svn:sync-from-url is '$url'\n";
2038 my $uuid = tmp_config('--get', "$section.svnsync-uuid");
2039 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2040 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2042 $svnsync = { url => $url, uuid => $uuid }
2044 if ($svnsync && $svnsync->{url} && $svnsync->{uuid}) {
2045 return $self->{svnsync} = $svnsync;
2048 my $err = "useSvnsyncProps set, but failed to read " .
2049 "svnsync property: svn:sync-from-";
2050 my $rp = $self->ra->rev_proplist(0);
2052 my $url = $rp->{'svn:sync-from-url'} or die $err . "url\n";
2053 ($url) = ($url =~ m{^([a-z\+]+://\S+)$}) or
2054 die "doesn't look right - svn:sync-from-url is '$url'\n";
2056 my $uuid = $rp->{'svn:sync-from-uuid'} or die $err . "uuid\n";
2057 ($uuid) = ($uuid =~ m{^([0-9a-f\-]{30,})$}) or
2058 die "doesn't look right - svn:sync-from-uuid is '$uuid'\n";
2060 my $section = "svn-remote.$self->{repo_id}";
2061 tmp_config('--add', "$section.svnsync-uuid", $uuid);
2062 tmp_config('--add', "$section.svnsync-url", $url);
2063 return $self->{svnsync} = { url => $url, uuid => $uuid };
2066 # this allows us to memoize our SVN::Ra UUID locally and avoid a
2067 # remote lookup (useful for 'git svn log').
2068 sub ra_uuid {
2069 my ($self) = @_;
2070 unless ($self->{ra_uuid}) {
2071 my $key = "svn-remote.$self->{repo_id}.uuid";
2072 my $uuid = eval { tmp_config('--get', $key) };
2073 if (!$@ && $uuid && $uuid =~ /^([a-f\d\-]{30,})$/) {
2074 $self->{ra_uuid} = $uuid;
2075 } else {
2076 die "ra_uuid called without URL\n" unless $self->{url};
2077 $self->{ra_uuid} = $self->ra->get_uuid;
2078 tmp_config('--add', $key, $self->{ra_uuid});
2081 $self->{ra_uuid};
2084 sub _set_repos_root {
2085 my ($self, $repos_root) = @_;
2086 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2087 $repos_root ||= $self->ra->{repos_root};
2088 tmp_config($k, $repos_root);
2089 $repos_root;
2092 sub repos_root {
2093 my ($self) = @_;
2094 my $k = "svn-remote.$self->{repo_id}.reposRoot";
2095 eval { tmp_config('--get', $k) } || $self->_set_repos_root;
2098 sub ra {
2099 my ($self) = shift;
2100 my $ra = Git::SVN::Ra->new($self->{url});
2101 $self->_set_repos_root($ra->{repos_root});
2102 if ($self->use_svm_props && !$self->{svm}) {
2103 if ($self->no_metadata) {
2104 die "Can't have both 'noMetadata' and ",
2105 "'useSvmProps' options set!\n";
2106 } elsif ($self->use_svnsync_props) {
2107 die "Can't have both 'useSvnsyncProps' and ",
2108 "'useSvmProps' options set!\n";
2110 $ra = $self->_set_svm_vars($ra);
2111 $self->{-want_revprops} = 1;
2113 $ra;
2116 sub rel_path {
2117 my ($self) = @_;
2118 my $repos_root = $self->ra->{repos_root};
2119 return $self->{path} if ($self->{url} eq $repos_root);
2120 my $url = $self->{url} .
2121 (length $self->{path} ? "/$self->{path}" : $self->{path});
2122 $url =~ s!^\Q$repos_root\E(?:/+|$)!!g;
2123 $url;
2126 # prop_walk(PATH, REV, SUB)
2127 # -------------------------
2128 # Recursively traverse PATH at revision REV and invoke SUB for each
2129 # directory that contains a SVN property. SUB will be invoked as
2130 # follows: &SUB(gs, path, props); where `gs' is this instance of
2131 # Git::SVN, `path' the path to the directory where the properties
2132 # `props' were found. The `path' will be relative to point of checkout,
2133 # that is, if url://repo/trunk is the current Git branch, and that
2134 # directory contains a sub-directory `d', SUB will be invoked with `/d/'
2135 # as `path' (note the trailing `/').
2136 sub prop_walk {
2137 my ($self, $path, $rev, $sub) = @_;
2139 $path =~ s#^/##;
2140 my ($dirent, undef, $props) = $self->ra->get_dir($path, $rev);
2141 $path =~ s#^/*#/#g;
2142 my $p = $path;
2143 # Strip the irrelevant part of the path.
2144 $p =~ s#^/+\Q$self->{path}\E(/|$)#/#;
2145 # Ensure the path is terminated by a `/'.
2146 $p =~ s#/*$#/#;
2148 # The properties contain all the internal SVN stuff nobody
2149 # (usually) cares about.
2150 my $interesting_props = 0;
2151 foreach (keys %{$props}) {
2152 # If it doesn't start with `svn:', it must be a
2153 # user-defined property.
2154 ++$interesting_props and next if $_ !~ /^svn:/;
2155 # FIXME: Fragile, if SVN adds new public properties,
2156 # this needs to be updated.
2157 ++$interesting_props if /^svn:(?:ignore|keywords|executable
2158 |eol-style|mime-type
2159 |externals|needs-lock)$/x;
2161 &$sub($self, $p, $props) if $interesting_props;
2163 foreach (sort keys %$dirent) {
2164 next if $dirent->{$_}->{kind} != $SVN::Node::dir;
2165 $self->prop_walk($self->{path} . $p . $_, $rev, $sub);
2169 sub last_rev { ($_[0]->last_rev_commit)[0] }
2170 sub last_commit { ($_[0]->last_rev_commit)[1] }
2172 # returns the newest SVN revision number and newest commit SHA1
2173 sub last_rev_commit {
2174 my ($self) = @_;
2175 if (defined $self->{last_rev} && defined $self->{last_commit}) {
2176 return ($self->{last_rev}, $self->{last_commit});
2178 my $c = ::verify_ref($self->refname.'^0');
2179 if ($c && !$self->use_svm_props && !$self->no_metadata) {
2180 my $rev = (::cmt_metadata($c))[1];
2181 if (defined $rev) {
2182 ($self->{last_rev}, $self->{last_commit}) = ($rev, $c);
2183 return ($rev, $c);
2186 my $map_path = $self->map_path;
2187 unless (-e $map_path) {
2188 ($self->{last_rev}, $self->{last_commit}) = (undef, undef);
2189 return (undef, undef);
2191 my ($rev, $commit) = $self->rev_map_max(1);
2192 ($self->{last_rev}, $self->{last_commit}) = ($rev, $commit);
2193 return ($rev, $commit);
2196 sub get_fetch_range {
2197 my ($self, $min, $max) = @_;
2198 $max ||= $self->ra->get_latest_revnum;
2199 $min ||= $self->rev_map_max;
2200 (++$min, $max);
2203 sub tmp_config {
2204 my (@args) = @_;
2205 my $old_def_config = "$ENV{GIT_DIR}/svn/config";
2206 my $config = "$ENV{GIT_DIR}/svn/.metadata";
2207 if (! -f $config && -f $old_def_config) {
2208 rename $old_def_config, $config or
2209 die "Failed rename $old_def_config => $config: $!\n";
2211 my $old_config = $ENV{GIT_CONFIG};
2212 $ENV{GIT_CONFIG} = $config;
2213 $@ = undef;
2214 my @ret = eval {
2215 unless (-f $config) {
2216 mkfile($config);
2217 open my $fh, '>', $config or
2218 die "Can't open $config: $!\n";
2219 print $fh "; This file is used internally by ",
2220 "git-svn\n" or die
2221 "Couldn't write to $config: $!\n";
2222 print $fh "; You should not have to edit it\n" or
2223 die "Couldn't write to $config: $!\n";
2224 close $fh or die "Couldn't close $config: $!\n";
2226 command('config', @args);
2228 my $err = $@;
2229 if (defined $old_config) {
2230 $ENV{GIT_CONFIG} = $old_config;
2231 } else {
2232 delete $ENV{GIT_CONFIG};
2234 die $err if $err;
2235 wantarray ? @ret : $ret[0];
2238 sub tmp_index_do {
2239 my ($self, $sub) = @_;
2240 my $old_index = $ENV{GIT_INDEX_FILE};
2241 $ENV{GIT_INDEX_FILE} = $self->{index};
2242 $@ = undef;
2243 my @ret = eval {
2244 my ($dir, $base) = ($self->{index} =~ m#^(.*?)/?([^/]+)$#);
2245 mkpath([$dir]) unless -d $dir;
2246 &$sub;
2248 my $err = $@;
2249 if (defined $old_index) {
2250 $ENV{GIT_INDEX_FILE} = $old_index;
2251 } else {
2252 delete $ENV{GIT_INDEX_FILE};
2254 die $err if $err;
2255 wantarray ? @ret : $ret[0];
2258 sub assert_index_clean {
2259 my ($self, $treeish) = @_;
2261 $self->tmp_index_do(sub {
2262 command_noisy('read-tree', $treeish) unless -e $self->{index};
2263 my $x = command_oneline('write-tree');
2264 my ($y) = (command(qw/cat-file commit/, $treeish) =~
2265 /^tree ($::sha1)/mo);
2266 return if $y eq $x;
2268 warn "Index mismatch: $y != $x\nrereading $treeish\n";
2269 unlink $self->{index} or die "unlink $self->{index}: $!\n";
2270 command_noisy('read-tree', $treeish);
2271 $x = command_oneline('write-tree');
2272 if ($y ne $x) {
2273 ::fatal "trees ($treeish) $y != $x\n",
2274 "Something is seriously wrong...";
2279 sub get_commit_parents {
2280 my ($self, $log_entry) = @_;
2281 my (%seen, @ret, @tmp);
2282 # legacy support for 'set-tree'; this is only used by set_tree_cb:
2283 if (my $ip = $self->{inject_parents}) {
2284 if (my $commit = delete $ip->{$log_entry->{revision}}) {
2285 push @tmp, $commit;
2288 if (my $cur = ::verify_ref($self->refname.'^0')) {
2289 push @tmp, $cur;
2291 if (my $ipd = $self->{inject_parents_dcommit}) {
2292 if (my $commit = delete $ipd->{$log_entry->{revision}}) {
2293 push @tmp, @$commit;
2296 push @tmp, $_ foreach (@{$log_entry->{parents}}, @tmp);
2297 while (my $p = shift @tmp) {
2298 next if $seen{$p};
2299 $seen{$p} = 1;
2300 push @ret, $p;
2301 # MAXPARENT is defined to 16 in commit-tree.c:
2302 last if @ret >= 16;
2304 if (@tmp) {
2305 die "r$log_entry->{revision}: No room for parents:\n\t",
2306 join("\n\t", @tmp), "\n";
2308 @ret;
2311 sub rewrite_root {
2312 my ($self) = @_;
2313 return $self->{-rewrite_root} if exists $self->{-rewrite_root};
2314 my $k = "svn-remote.$self->{repo_id}.rewriteRoot";
2315 my $rwr = eval { command_oneline(qw/config --get/, $k) };
2316 if ($rwr) {
2317 $rwr =~ s#/+$##;
2318 if ($rwr !~ m#^[a-z\+]+://#) {
2319 die "$rwr is not a valid URL (key: $k)\n";
2322 $self->{-rewrite_root} = $rwr;
2325 sub metadata_url {
2326 my ($self) = @_;
2327 ($self->rewrite_root || $self->{url}) .
2328 (length $self->{path} ? '/' . $self->{path} : '');
2331 sub full_url {
2332 my ($self) = @_;
2333 $self->{url} . (length $self->{path} ? '/' . $self->{path} : '');
2337 sub set_commit_header_env {
2338 my ($log_entry) = @_;
2339 my %env;
2340 foreach my $ned (qw/NAME EMAIL DATE/) {
2341 foreach my $ac (qw/AUTHOR COMMITTER/) {
2342 $env{"GIT_${ac}_${ned}"} = $ENV{"GIT_${ac}_${ned}"};
2346 $ENV{GIT_AUTHOR_NAME} = $log_entry->{name};
2347 $ENV{GIT_AUTHOR_EMAIL} = $log_entry->{email};
2348 $ENV{GIT_AUTHOR_DATE} = $ENV{GIT_COMMITTER_DATE} = $log_entry->{date};
2350 $ENV{GIT_COMMITTER_NAME} = (defined $log_entry->{commit_name})
2351 ? $log_entry->{commit_name}
2352 : $log_entry->{name};
2353 $ENV{GIT_COMMITTER_EMAIL} = (defined $log_entry->{commit_email})
2354 ? $log_entry->{commit_email}
2355 : $log_entry->{email};
2356 \%env;
2359 sub restore_commit_header_env {
2360 my ($env) = @_;
2361 foreach my $ned (qw/NAME EMAIL DATE/) {
2362 foreach my $ac (qw/AUTHOR COMMITTER/) {
2363 my $k = "GIT_${ac}_${ned}";
2364 if (defined $env->{$k}) {
2365 $ENV{$k} = $env->{$k};
2366 } else {
2367 delete $ENV{$k};
2373 sub gc {
2374 command_noisy('gc', '--auto');
2377 sub do_git_commit {
2378 my ($self, $log_entry) = @_;
2379 my $lr = $self->last_rev;
2380 if (defined $lr && $lr >= $log_entry->{revision}) {
2381 die "Last fetched revision of ", $self->refname,
2382 " was r$lr, but we are about to fetch: ",
2383 "r$log_entry->{revision}!\n";
2385 if (my $c = $self->rev_map_get($log_entry->{revision})) {
2386 croak "$log_entry->{revision} = $c already exists! ",
2387 "Why are we refetching it?\n";
2389 my $old_env = set_commit_header_env($log_entry);
2390 my $tree = $log_entry->{tree};
2391 if (!defined $tree) {
2392 $tree = $self->tmp_index_do(sub {
2393 command_oneline('write-tree') });
2395 die "Tree is not a valid sha1: $tree\n" if $tree !~ /^$::sha1$/o;
2397 my @exec = ('git', 'commit-tree', $tree);
2398 foreach ($self->get_commit_parents($log_entry)) {
2399 push @exec, '-p', $_;
2401 defined(my $pid = open3(my $msg_fh, my $out_fh, '>&STDERR', @exec))
2402 or croak $!;
2403 binmode $msg_fh;
2405 # we always get UTF-8 from SVN, but we may want our commits in
2406 # a different encoding.
2407 if (my $enc = Git::config('i18n.commitencoding')) {
2408 require Encode;
2409 Encode::from_to($log_entry->{log}, 'UTF-8', $enc);
2411 print $msg_fh $log_entry->{log} or croak $!;
2412 restore_commit_header_env($old_env);
2413 unless ($self->no_metadata) {
2414 print $msg_fh "\ngit-svn-id: $log_entry->{metadata}\n"
2415 or croak $!;
2417 $msg_fh->flush == 0 or croak $!;
2418 close $msg_fh or croak $!;
2419 chomp(my $commit = do { local $/; <$out_fh> });
2420 close $out_fh or croak $!;
2421 waitpid $pid, 0;
2422 croak $? if $?;
2423 if ($commit !~ /^$::sha1$/o) {
2424 die "Failed to commit, invalid sha1: $commit\n";
2427 $self->rev_map_set($log_entry->{revision}, $commit, 1);
2429 $self->{last_rev} = $log_entry->{revision};
2430 $self->{last_commit} = $commit;
2431 print "r$log_entry->{revision}" unless $::_q > 1;
2432 if (defined $log_entry->{svm_revision}) {
2433 print " (\@$log_entry->{svm_revision})" unless $::_q > 1;
2434 $self->rev_map_set($log_entry->{svm_revision}, $commit,
2435 0, $self->svm_uuid);
2437 print " = $commit ($self->{ref_id})\n" unless $::_q > 1;
2438 if (--$_gc_nr == 0) {
2439 $_gc_nr = $_gc_period;
2440 gc();
2442 return $commit;
2445 sub match_paths {
2446 my ($self, $paths, $r) = @_;
2447 return 1 if $self->{path} eq '';
2448 if (my $path = $paths->{"/$self->{path}"}) {
2449 return ($path->{action} eq 'D') ? 0 : 1;
2451 my $repos_root = $self->ra->{repos_root};
2452 my $extended_path = $self->{url} . '/' . $self->{path};
2453 $extended_path =~ s#^\Q$repos_root\E(/|$)##;
2454 $self->{path_regex} ||= qr/^\/\Q$extended_path\E\//;
2455 if (grep /$self->{path_regex}/, keys %$paths) {
2456 return 1;
2458 my $c = '';
2459 foreach (split m#/#, $self->{path}) {
2460 $c .= "/$_";
2461 next unless ($paths->{$c} &&
2462 ($paths->{$c}->{action} =~ /^[AR]$/));
2463 if ($self->ra->check_path($self->{path}, $r) ==
2464 $SVN::Node::dir) {
2465 return 1;
2468 return 0;
2471 sub find_parent_branch {
2472 my ($self, $paths, $rev) = @_;
2473 return undef unless $self->follow_parent;
2474 unless (defined $paths) {
2475 my $err_handler = $SVN::Error::handler;
2476 $SVN::Error::handler = \&Git::SVN::Ra::skip_unknown_revs;
2477 $self->ra->get_log([$self->{path}], $rev, $rev, 0, 1, 1, sub {
2478 $paths =
2479 Git::SVN::Ra::dup_changed_paths($_[0]) });
2480 $SVN::Error::handler = $err_handler;
2482 return undef unless defined $paths;
2484 # look for a parent from another branch:
2485 my @b_path_components = split m#/#, $self->rel_path;
2486 my @a_path_components;
2487 my $i;
2488 while (@b_path_components) {
2489 $i = $paths->{'/'.join('/', @b_path_components)};
2490 last if $i && defined $i->{copyfrom_path};
2491 unshift(@a_path_components, pop(@b_path_components));
2493 return undef unless defined $i && defined $i->{copyfrom_path};
2494 my $branch_from = $i->{copyfrom_path};
2495 if (@a_path_components) {
2496 print STDERR "branch_from: $branch_from => ";
2497 $branch_from .= '/'.join('/', @a_path_components);
2498 print STDERR $branch_from, "\n";
2500 my $r = $i->{copyfrom_rev};
2501 my $repos_root = $self->ra->{repos_root};
2502 my $url = $self->ra->{url};
2503 my $new_url = $repos_root . $branch_from;
2504 print STDERR "Found possible branch point: ",
2505 "$new_url => ", $self->full_url, ", $r\n";
2506 $branch_from =~ s#^/##;
2507 my $gs = $self->other_gs($new_url, $url, $repos_root,
2508 $branch_from, $r, $self->{ref_id});
2509 my ($r0, $parent) = $gs->find_rev_before($r, 1);
2511 my ($base, $head);
2512 if (!defined $r0 || !defined $parent) {
2513 ($base, $head) = parse_revision_argument(0, $r);
2514 } else {
2515 if ($r0 < $r) {
2516 $gs->ra->get_log([$gs->{path}], $r0 + 1, $r, 1,
2517 0, 1, sub { $base = $_[1] - 1 });
2520 if (defined $base && $base <= $r) {
2521 $gs->fetch($base, $r);
2523 ($r0, $parent) = $gs->find_rev_before($r, 1);
2525 if (defined $r0 && defined $parent) {
2526 print STDERR "Found branch parent: ($self->{ref_id}) $parent\n";
2527 my $ed;
2528 if ($self->ra->can_do_switch) {
2529 $self->assert_index_clean($parent);
2530 print STDERR "Following parent with do_switch\n";
2531 # do_switch works with svn/trunk >= r22312, but that
2532 # is not included with SVN 1.4.3 (the latest version
2533 # at the moment), so we can't rely on it
2534 $self->{last_rev} = $r0;
2535 $self->{last_commit} = $parent;
2536 $ed = SVN::Git::Fetcher->new($self, $gs->{path});
2537 $gs->ra->gs_do_switch($r0, $rev, $gs,
2538 $self->full_url, $ed)
2539 or die "SVN connection failed somewhere...\n";
2540 } elsif ($self->ra->trees_match($new_url, $r0,
2541 $self->full_url, $rev)) {
2542 print STDERR "Trees match:\n",
2543 " $new_url\@$r0\n",
2544 " ${\$self->full_url}\@$rev\n",
2545 "Following parent with no changes\n";
2546 $self->tmp_index_do(sub {
2547 command_noisy('read-tree', $parent);
2549 $self->{last_commit} = $parent;
2550 } else {
2551 print STDERR "Following parent with do_update\n";
2552 $ed = SVN::Git::Fetcher->new($self);
2553 $self->ra->gs_do_update($rev, $rev, $self, $ed)
2554 or die "SVN connection failed somewhere...\n";
2556 print STDERR "Successfully followed parent\n";
2557 return $self->make_log_entry($rev, [$parent], $ed);
2559 return undef;
2562 sub do_fetch {
2563 my ($self, $paths, $rev) = @_;
2564 my $ed;
2565 my ($last_rev, @parents);
2566 if (my $lc = $self->last_commit) {
2567 # we can have a branch that was deleted, then re-added
2568 # under the same name but copied from another path, in
2569 # which case we'll have multiple parents (we don't
2570 # want to break the original ref, nor lose copypath info):
2571 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2572 push @{$log_entry->{parents}}, $lc;
2573 return $log_entry;
2575 $ed = SVN::Git::Fetcher->new($self);
2576 $last_rev = $self->{last_rev};
2577 $ed->{c} = $lc;
2578 @parents = ($lc);
2579 } else {
2580 $last_rev = $rev;
2581 if (my $log_entry = $self->find_parent_branch($paths, $rev)) {
2582 return $log_entry;
2584 $ed = SVN::Git::Fetcher->new($self);
2586 unless ($self->ra->gs_do_update($last_rev, $rev, $self, $ed)) {
2587 die "SVN connection failed somewhere...\n";
2589 $self->make_log_entry($rev, \@parents, $ed);
2592 sub get_untracked {
2593 my ($self, $ed) = @_;
2594 my @out;
2595 my $h = $ed->{empty};
2596 foreach (sort keys %$h) {
2597 my $act = $h->{$_} ? '+empty_dir' : '-empty_dir';
2598 push @out, " $act: " . uri_encode($_);
2599 warn "W: $act: $_\n";
2601 foreach my $t (qw/dir_prop file_prop/) {
2602 $h = $ed->{$t} or next;
2603 foreach my $path (sort keys %$h) {
2604 my $ppath = $path eq '' ? '.' : $path;
2605 foreach my $prop (sort keys %{$h->{$path}}) {
2606 next if $SKIP_PROP{$prop};
2607 my $v = $h->{$path}->{$prop};
2608 my $t_ppath_prop = "$t: " .
2609 uri_encode($ppath) . ' ' .
2610 uri_encode($prop);
2611 if (defined $v) {
2612 push @out, " +$t_ppath_prop " .
2613 uri_encode($v);
2614 } else {
2615 push @out, " -$t_ppath_prop";
2620 foreach my $t (qw/absent_file absent_directory/) {
2621 $h = $ed->{$t} or next;
2622 foreach my $parent (sort keys %$h) {
2623 foreach my $path (sort @{$h->{$parent}}) {
2624 push @out, " $t: " .
2625 uri_encode("$parent/$path");
2626 warn "W: $t: $parent/$path ",
2627 "Insufficient permissions?\n";
2631 \@out;
2634 # parse_svn_date(DATE)
2635 # --------------------
2636 # Given a date (in UTC) from Subversion, return a string in the format
2637 # "<TZ Offset> <local date/time>" that Git will use.
2639 # By default the parsed date will be in UTC; if $Git::SVN::_localtime
2640 # is true we'll convert it to the local timezone instead.
2641 sub parse_svn_date {
2642 my $date = shift || return '+0000 1970-01-01 00:00:00';
2643 my ($Y,$m,$d,$H,$M,$S) = ($date =~ /^(\d{4})\-(\d\d)\-(\d\d)T
2644 (\d\d)\:(\d\d)\:(\d\d)\.\d*Z$/x) or
2645 croak "Unable to parse date: $date\n";
2646 my $parsed_date; # Set next.
2648 if ($Git::SVN::_localtime) {
2649 # Translate the Subversion datetime to an epoch time.
2650 # Begin by switching ourselves to $date's timezone, UTC.
2651 my $old_env_TZ = $ENV{TZ};
2652 $ENV{TZ} = 'UTC';
2654 my $epoch_in_UTC =
2655 POSIX::strftime('%s', $S, $M, $H, $d, $m - 1, $Y - 1900);
2657 # Determine our local timezone (including DST) at the
2658 # time of $epoch_in_UTC. $Git::SVN::Log::TZ stored the
2659 # value of TZ, if any, at the time we were run.
2660 if (defined $Git::SVN::Log::TZ) {
2661 $ENV{TZ} = $Git::SVN::Log::TZ;
2662 } else {
2663 delete $ENV{TZ};
2666 my $our_TZ =
2667 POSIX::strftime('%Z', $S, $M, $H, $d, $m - 1, $Y - 1900);
2669 # This converts $epoch_in_UTC into our local timezone.
2670 my ($sec, $min, $hour, $mday, $mon, $year,
2671 $wday, $yday, $isdst) = localtime($epoch_in_UTC);
2673 $parsed_date = sprintf('%s %04d-%02d-%02d %02d:%02d:%02d',
2674 $our_TZ, $year + 1900, $mon + 1,
2675 $mday, $hour, $min, $sec);
2677 # Reset us to the timezone in effect when we entered
2678 # this routine.
2679 if (defined $old_env_TZ) {
2680 $ENV{TZ} = $old_env_TZ;
2681 } else {
2682 delete $ENV{TZ};
2684 } else {
2685 $parsed_date = "+0000 $Y-$m-$d $H:$M:$S";
2688 return $parsed_date;
2691 sub other_gs {
2692 my ($self, $new_url, $url, $repos_root,
2693 $branch_from, $r, $old_ref_id) = @_;
2694 my $gs = Git::SVN->find_by_url($new_url, $repos_root, $branch_from);
2695 unless ($gs) {
2696 my $ref_id = $old_ref_id;
2697 $ref_id =~ s/\@\d+$//;
2698 $ref_id .= "\@$r";
2699 # just grow a tail if we're not unique enough :x
2700 $ref_id .= '-' while find_ref($ref_id);
2701 print STDERR "Initializing parent: $ref_id\n";
2702 my ($u, $p, $repo_id) = ($new_url, '', $ref_id);
2703 if ($u =~ s#^\Q$url\E(/|$)##) {
2704 $p = $u;
2705 $u = $url;
2706 $repo_id = $self->{repo_id};
2708 $gs = Git::SVN->init($u, $p, $repo_id, $ref_id, 1);
2713 sub call_authors_prog {
2714 my ($orig_author) = @_;
2715 my $author = `$::_authors_prog $orig_author`;
2716 if ($? != 0) {
2717 die "$::_authors_prog failed with exit code $?\n"
2719 if ($author =~ /^\s*(.+?)\s*<(.*)>\s*$/) {
2720 my ($name, $email) = ($1, $2);
2721 $email = undef if length $2 == 0;
2722 return [$name, $email];
2723 } else {
2724 die "Author: $orig_author: $::_authors_prog returned "
2725 . "invalid author format: $author\n";
2729 sub check_author {
2730 my ($author) = @_;
2731 if (!defined $author || length $author == 0) {
2732 $author = '(no author)';
2734 if (!defined $::users{$author}) {
2735 if (defined $::_authors_prog) {
2736 $::users{$author} = call_authors_prog($author);
2737 } elsif (defined $::_authors) {
2738 die "Author: $author not defined in $::_authors file\n";
2741 $author;
2744 sub make_log_entry {
2745 my ($self, $rev, $parents, $ed) = @_;
2746 my $untracked = $self->get_untracked($ed);
2748 open my $un, '>>', "$self->{dir}/unhandled.log" or croak $!;
2749 print $un "r$rev\n" or croak $!;
2750 print $un $_, "\n" foreach @$untracked;
2751 my %log_entry = ( parents => $parents || [], revision => $rev,
2752 log => '');
2754 my $headrev;
2755 my $logged = delete $self->{logged_rev_props};
2756 if (!$logged || $self->{-want_revprops}) {
2757 my $rp = $self->ra->rev_proplist($rev);
2758 foreach (sort keys %$rp) {
2759 my $v = $rp->{$_};
2760 if (/^svn:(author|date|log)$/) {
2761 $log_entry{$1} = $v;
2762 } elsif ($_ eq 'svm:headrev') {
2763 $headrev = $v;
2764 } else {
2765 print $un " rev_prop: ", uri_encode($_), ' ',
2766 uri_encode($v), "\n";
2769 } else {
2770 map { $log_entry{$_} = $logged->{$_} } keys %$logged;
2772 close $un or croak $!;
2774 $log_entry{date} = parse_svn_date($log_entry{date});
2775 $log_entry{log} .= "\n";
2776 my $author = $log_entry{author} = check_author($log_entry{author});
2777 my ($name, $email) = defined $::users{$author} ? @{$::users{$author}}
2778 : ($author, undef);
2780 my ($commit_name, $commit_email) = ($name, $email);
2781 if ($_use_log_author) {
2782 my $name_field;
2783 if ($log_entry{log} =~ /From:\s+(.*\S)\s*\n/i) {
2784 $name_field = $1;
2785 } elsif ($log_entry{log} =~ /Signed-off-by:\s+(.*\S)\s*\n/i) {
2786 $name_field = $1;
2788 if (!defined $name_field) {
2789 if (!defined $email) {
2790 $email = $name;
2792 } elsif ($name_field =~ /(.*?)\s+<(.*)>/) {
2793 ($name, $email) = ($1, $2);
2794 } elsif ($name_field =~ /(.*)@/) {
2795 ($name, $email) = ($1, $name_field);
2796 } else {
2797 ($name, $email) = ($name_field, $name_field);
2800 if (defined $headrev && $self->use_svm_props) {
2801 if ($self->rewrite_root) {
2802 die "Can't have both 'useSvmProps' and 'rewriteRoot' ",
2803 "options set!\n";
2805 my ($uuid, $r) = $headrev =~ m{^([a-f\d\-]{30,}):(\d+)$};
2806 # we don't want "SVM: initializing mirror for junk" ...
2807 return undef if $r == 0;
2808 my $svm = $self->svm;
2809 if ($uuid ne $svm->{uuid}) {
2810 die "UUID mismatch on SVM path:\n",
2811 "expected: $svm->{uuid}\n",
2812 " got: $uuid\n";
2814 my $full_url = $self->full_url;
2815 $full_url =~ s#^\Q$svm->{replace}\E(/|$)#$svm->{source}$1# or
2816 die "Failed to replace '$svm->{replace}' with ",
2817 "'$svm->{source}' in $full_url\n";
2818 # throw away username for storing in records
2819 remove_username($full_url);
2820 $log_entry{metadata} = "$full_url\@$r $uuid";
2821 $log_entry{svm_revision} = $r;
2822 $email ||= "$author\@$uuid";
2823 $commit_email ||= "$author\@$uuid";
2824 } elsif ($self->use_svnsync_props) {
2825 my $full_url = $self->svnsync->{url};
2826 $full_url .= "/$self->{path}" if length $self->{path};
2827 remove_username($full_url);
2828 my $uuid = $self->svnsync->{uuid};
2829 $log_entry{metadata} = "$full_url\@$rev $uuid";
2830 $email ||= "$author\@$uuid";
2831 $commit_email ||= "$author\@$uuid";
2832 } else {
2833 my $url = $self->metadata_url;
2834 remove_username($url);
2835 $log_entry{metadata} = "$url\@$rev " .
2836 $self->ra->get_uuid;
2837 $email ||= "$author\@" . $self->ra->get_uuid;
2838 $commit_email ||= "$author\@" . $self->ra->get_uuid;
2840 $log_entry{name} = $name;
2841 $log_entry{email} = $email;
2842 $log_entry{commit_name} = $commit_name;
2843 $log_entry{commit_email} = $commit_email;
2844 \%log_entry;
2847 sub fetch {
2848 my ($self, $min_rev, $max_rev, @parents) = @_;
2849 my ($last_rev, $last_commit) = $self->last_rev_commit;
2850 my ($base, $head) = $self->get_fetch_range($min_rev, $max_rev);
2851 $self->ra->gs_fetch_loop_common($base, $head, [$self]);
2854 sub set_tree_cb {
2855 my ($self, $log_entry, $tree, $rev, $date, $author) = @_;
2856 $self->{inject_parents} = { $rev => $tree };
2857 $self->fetch(undef, undef);
2860 sub set_tree {
2861 my ($self, $tree) = (shift, shift);
2862 my $log_entry = ::get_commit_entry($tree);
2863 unless ($self->{last_rev}) {
2864 ::fatal("Must have an existing revision to commit");
2866 my %ed_opts = ( r => $self->{last_rev},
2867 log => $log_entry->{log},
2868 ra => $self->ra,
2869 tree_a => $self->{last_commit},
2870 tree_b => $tree,
2871 editor_cb => sub {
2872 $self->set_tree_cb($log_entry, $tree, @_) },
2873 svn_path => $self->{path} );
2874 if (!SVN::Git::Editor->new(\%ed_opts)->apply_diff) {
2875 print "No changes\nr$self->{last_rev} = $tree\n";
2879 sub rebuild_from_rev_db {
2880 my ($self, $path) = @_;
2881 my $r = -1;
2882 open my $fh, '<', $path or croak "open: $!";
2883 binmode $fh or croak "binmode: $!";
2884 while (<$fh>) {
2885 length($_) == 41 or croak "inconsistent size in ($_) != 41";
2886 chomp($_);
2887 ++$r;
2888 next if $_ eq ('0' x 40);
2889 $self->rev_map_set($r, $_);
2890 print "r$r = $_\n";
2892 close $fh or croak "close: $!";
2893 unlink $path or croak "unlink: $!";
2896 sub rebuild {
2897 my ($self) = @_;
2898 my $map_path = $self->map_path;
2899 my $partial = (-e $map_path && ! -z $map_path);
2900 return unless ::verify_ref($self->refname.'^0');
2901 if (!$partial && ($self->use_svm_props || $self->no_metadata)) {
2902 my $rev_db = $self->rev_db_path;
2903 $self->rebuild_from_rev_db($rev_db);
2904 if ($self->use_svm_props) {
2905 my $svm_rev_db = $self->rev_db_path($self->svm_uuid);
2906 $self->rebuild_from_rev_db($svm_rev_db);
2908 $self->unlink_rev_db_symlink;
2909 return;
2911 print "Rebuilding $map_path ...\n" if (!$partial);
2912 my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) :
2913 (undef, undef));
2914 my ($log, $ctx) =
2915 command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/,
2916 ($head ? "$head.." : "") . $self->refname,
2917 '--');
2918 my $metadata_url = $self->metadata_url;
2919 remove_username($metadata_url);
2920 my $svn_uuid = $self->ra_uuid;
2921 my $c;
2922 while (<$log>) {
2923 if ( m{^commit ($::sha1)$} ) {
2924 $c = $1;
2925 next;
2927 next unless s{^\s*(git-svn-id:)}{$1};
2928 my ($url, $rev, $uuid) = ::extract_metadata($_);
2929 remove_username($url);
2931 # ignore merges (from set-tree)
2932 next if (!defined $rev || !$uuid);
2934 # if we merged or otherwise started elsewhere, this is
2935 # how we break out of it
2936 if (($uuid ne $svn_uuid) ||
2937 ($metadata_url && $url && ($url ne $metadata_url))) {
2938 next;
2940 if ($partial && $head) {
2941 print "Partial-rebuilding $map_path ...\n";
2942 print "Currently at $base_rev = $head\n";
2943 $head = undef;
2946 $self->rev_map_set($rev, $c);
2947 print "r$rev = $c\n";
2949 command_close_pipe($log, $ctx);
2950 print "Done rebuilding $map_path\n" if (!$partial || !$head);
2951 my $rev_db_path = $self->rev_db_path;
2952 if (-f $self->rev_db_path) {
2953 unlink $self->rev_db_path or croak "unlink: $!";
2955 $self->unlink_rev_db_symlink;
2958 # rev_map:
2959 # Tie::File seems to be prone to offset errors if revisions get sparse,
2960 # it's not that fast, either. Tie::File is also not in Perl 5.6. So
2961 # one of my favorite modules is out :< Next up would be one of the DBM
2962 # modules, but I'm not sure which is most portable...
2964 # This is the replacement for the rev_db format, which was too big
2965 # and inefficient for large repositories with a lot of sparse history
2966 # (mainly tags)
2968 # The format is this:
2969 # - 24 bytes for every record,
2970 # * 4 bytes for the integer representing an SVN revision number
2971 # * 20 bytes representing the sha1 of a git commit
2972 # - No empty padding records like the old format
2973 # (except the last record, which can be overwritten)
2974 # - new records are written append-only since SVN revision numbers
2975 # increase monotonically
2976 # - lookups on SVN revision number are done via a binary search
2977 # - Piping the file to xxd -c24 is a good way of dumping it for
2978 # viewing or editing (piped back through xxd -r), should the need
2979 # ever arise.
2980 # - The last record can be padding revision with an all-zero sha1
2981 # This is used to optimize fetch performance when using multiple
2982 # "fetch" directives in .git/config
2984 # These files are disposable unless noMetadata or useSvmProps is set
2986 sub _rev_map_set {
2987 my ($fh, $rev, $commit) = @_;
2989 binmode $fh or croak "binmode: $!";
2990 my $size = (stat($fh))[7];
2991 ($size % 24) == 0 or croak "inconsistent size: $size";
2993 my $wr_offset = 0;
2994 if ($size > 0) {
2995 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
2996 my $read = sysread($fh, my $buf, 24) or croak "read: $!";
2997 $read == 24 or croak "read only $read bytes (!= 24)";
2998 my ($last_rev, $last_commit) = unpack(rev_map_fmt, $buf);
2999 if ($last_commit eq ('0' x40)) {
3000 if ($size >= 48) {
3001 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3002 $read = sysread($fh, $buf, 24) or
3003 croak "read: $!";
3004 $read == 24 or
3005 croak "read only $read bytes (!= 24)";
3006 ($last_rev, $last_commit) =
3007 unpack(rev_map_fmt, $buf);
3008 if ($last_commit eq ('0' x40)) {
3009 croak "inconsistent .rev_map\n";
3012 if ($last_rev >= $rev) {
3013 croak "last_rev is higher!: $last_rev >= $rev";
3015 $wr_offset = -24;
3018 sysseek($fh, $wr_offset, SEEK_END) or croak "seek: $!";
3019 syswrite($fh, pack(rev_map_fmt, $rev, $commit), 24) == 24 or
3020 croak "write: $!";
3023 sub mkfile {
3024 my ($path) = @_;
3025 unless (-e $path) {
3026 my ($dir, $base) = ($path =~ m#^(.*?)/?([^/]+)$#);
3027 mkpath([$dir]) unless -d $dir;
3028 open my $fh, '>>', $path or die "Couldn't create $path: $!\n";
3029 close $fh or die "Couldn't close (create) $path: $!\n";
3033 sub rev_map_set {
3034 my ($self, $rev, $commit, $update_ref, $uuid) = @_;
3035 length $commit == 40 or die "arg3 must be a full SHA1 hexsum\n";
3036 my $db = $self->map_path($uuid);
3037 my $db_lock = "$db.lock";
3038 my $sig;
3039 if ($update_ref) {
3040 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3041 $SIG{USR1} = $SIG{USR2} = sub { $sig = $_[0] };
3043 mkfile($db);
3045 $LOCKFILES{$db_lock} = 1;
3046 my $sync;
3047 # both of these options make our .rev_db file very, very important
3048 # and we can't afford to lose it because rebuild() won't work
3049 if ($self->use_svm_props || $self->no_metadata) {
3050 $sync = 1;
3051 copy($db, $db_lock) or die "rev_map_set(@_): ",
3052 "Failed to copy: ",
3053 "$db => $db_lock ($!)\n";
3054 } else {
3055 rename $db, $db_lock or die "rev_map_set(@_): ",
3056 "Failed to rename: ",
3057 "$db => $db_lock ($!)\n";
3060 sysopen(my $fh, $db_lock, O_RDWR | O_CREAT)
3061 or croak "Couldn't open $db_lock: $!\n";
3062 _rev_map_set($fh, $rev, $commit);
3063 if ($sync) {
3064 $fh->flush or die "Couldn't flush $db_lock: $!\n";
3065 $fh->sync or die "Couldn't sync $db_lock: $!\n";
3067 close $fh or croak $!;
3068 if ($update_ref) {
3069 $_head = $self;
3070 command_noisy('update-ref', '-m', "r$rev",
3071 $self->refname, $commit);
3073 rename $db_lock, $db or die "rev_map_set(@_): ", "Failed to rename: ",
3074 "$db_lock => $db ($!)\n";
3075 delete $LOCKFILES{$db_lock};
3076 if ($update_ref) {
3077 $SIG{INT} = $SIG{HUP} = $SIG{TERM} = $SIG{ALRM} = $SIG{PIPE} =
3078 $SIG{USR1} = $SIG{USR2} = 'DEFAULT';
3079 kill $sig, $$ if defined $sig;
3083 # If want_commit, this will return an array of (rev, commit) where
3084 # commit _must_ be a valid commit in the archive.
3085 # Otherwise, it'll return the max revision (whether or not the
3086 # commit is valid or just a 0x40 placeholder).
3087 sub rev_map_max {
3088 my ($self, $want_commit) = @_;
3089 $self->rebuild;
3090 my ($r, $c) = $self->rev_map_max_norebuild($want_commit);
3091 $want_commit ? ($r, $c) : $r;
3094 sub rev_map_max_norebuild {
3095 my ($self, $want_commit) = @_;
3096 my $map_path = $self->map_path;
3097 stat $map_path or return $want_commit ? (0, undef) : 0;
3098 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3099 binmode $fh or croak "binmode: $!";
3100 my $size = (stat($fh))[7];
3101 ($size % 24) == 0 or croak "inconsistent size: $size";
3103 if ($size == 0) {
3104 close $fh or croak "close: $!";
3105 return $want_commit ? (0, undef) : 0;
3108 sysseek($fh, -24, SEEK_END) or croak "seek: $!";
3109 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3110 my ($r, $c) = unpack(rev_map_fmt, $buf);
3111 if ($want_commit && $c eq ('0' x40)) {
3112 if ($size < 48) {
3113 return $want_commit ? (0, undef) : 0;
3115 sysseek($fh, -48, SEEK_END) or croak "seek: $!";
3116 sysread($fh, $buf, 24) == 24 or croak "read: $!";
3117 ($r, $c) = unpack(rev_map_fmt, $buf);
3118 if ($c eq ('0'x40)) {
3119 croak "Penultimate record is all-zeroes in $map_path";
3122 close $fh or croak "close: $!";
3123 $want_commit ? ($r, $c) : $r;
3126 sub rev_map_get {
3127 my ($self, $rev, $uuid) = @_;
3128 my $map_path = $self->map_path($uuid);
3129 return undef unless -e $map_path;
3131 sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!";
3132 binmode $fh or croak "binmode: $!";
3133 my $size = (stat($fh))[7];
3134 ($size % 24) == 0 or croak "inconsistent size: $size";
3136 if ($size == 0) {
3137 close $fh or croak "close: $fh";
3138 return undef;
3141 my ($l, $u) = (0, $size - 24);
3142 my ($r, $c, $buf);
3144 while ($l <= $u) {
3145 my $i = int(($l/24 + $u/24) / 2) * 24;
3146 sysseek($fh, $i, SEEK_SET) or croak "seek: $!";
3147 sysread($fh, my $buf, 24) == 24 or croak "read: $!";
3148 my ($r, $c) = unpack('NH40', $buf);
3150 if ($r < $rev) {
3151 $l = $i + 24;
3152 } elsif ($r > $rev) {
3153 $u = $i - 24;
3154 } else { # $r == $rev
3155 close($fh) or croak "close: $!";
3156 return $c eq ('0' x 40) ? undef : $c;
3159 close($fh) or croak "close: $!";
3160 undef;
3163 # Finds the first svn revision that exists on (if $eq_ok is true) or
3164 # before $rev for the current branch. It will not search any lower
3165 # than $min_rev. Returns the git commit hash and svn revision number
3166 # if found, else (undef, undef).
3167 sub find_rev_before {
3168 my ($self, $rev, $eq_ok, $min_rev) = @_;
3169 --$rev unless $eq_ok;
3170 $min_rev ||= 1;
3171 while ($rev >= $min_rev) {
3172 if (my $c = $self->rev_map_get($rev)) {
3173 return ($rev, $c);
3175 --$rev;
3177 return (undef, undef);
3180 # Finds the first svn revision that exists on (if $eq_ok is true) or
3181 # after $rev for the current branch. It will not search any higher
3182 # than $max_rev. Returns the git commit hash and svn revision number
3183 # if found, else (undef, undef).
3184 sub find_rev_after {
3185 my ($self, $rev, $eq_ok, $max_rev) = @_;
3186 ++$rev unless $eq_ok;
3187 $max_rev ||= $self->rev_map_max;
3188 while ($rev <= $max_rev) {
3189 if (my $c = $self->rev_map_get($rev)) {
3190 return ($rev, $c);
3192 ++$rev;
3194 return (undef, undef);
3197 sub _new {
3198 my ($class, $repo_id, $ref_id, $path) = @_;
3199 unless (defined $repo_id && length $repo_id) {
3200 $repo_id = $Git::SVN::default_repo_id;
3202 unless (defined $ref_id && length $ref_id) {
3203 $_[2] = $ref_id = $Git::SVN::default_ref_id;
3205 $_[1] = $repo_id;
3206 my $dir = "$ENV{GIT_DIR}/svn/$ref_id";
3207 $_[3] = $path = '' unless (defined $path);
3208 mkpath(["$ENV{GIT_DIR}/svn"]);
3209 bless {
3210 ref_id => $ref_id, dir => $dir, index => "$dir/index",
3211 path => $path, config => "$ENV{GIT_DIR}/svn/config",
3212 map_root => "$dir/.rev_map", repo_id => $repo_id }, $class;
3215 # for read-only access of old .rev_db formats
3216 sub unlink_rev_db_symlink {
3217 my ($self) = @_;
3218 my $link = $self->rev_db_path;
3219 $link =~ s/\.[\w-]+$// or croak "missing UUID at the end of $link";
3220 if (-l $link) {
3221 unlink $link or croak "unlink: $link failed!";
3225 sub rev_db_path {
3226 my ($self, $uuid) = @_;
3227 my $db_path = $self->map_path($uuid);
3228 $db_path =~ s{/\.rev_map\.}{/\.rev_db\.}
3229 or croak "map_path: $db_path does not contain '/.rev_map.' !";
3230 $db_path;
3233 # the new replacement for .rev_db
3234 sub map_path {
3235 my ($self, $uuid) = @_;
3236 $uuid ||= $self->ra_uuid;
3237 "$self->{map_root}.$uuid";
3240 sub uri_encode {
3241 my ($f) = @_;
3242 $f =~ s#([^a-zA-Z0-9\*!\:_\./\-])#uc sprintf("%%%02x",ord($1))#eg;
3246 sub remove_username {
3247 $_[0] =~ s{^([^:]*://)[^@]+@}{$1};
3250 package Git::SVN::Prompt;
3251 use strict;
3252 use warnings;
3253 require SVN::Core;
3254 use vars qw/$_no_auth_cache $_username/;
3256 sub simple {
3257 my ($cred, $realm, $default_username, $may_save, $pool) = @_;
3258 $may_save = undef if $_no_auth_cache;
3259 $default_username = $_username if defined $_username;
3260 if (defined $default_username && length $default_username) {
3261 if (defined $realm && length $realm) {
3262 print STDERR "Authentication realm: $realm\n";
3263 STDERR->flush;
3265 $cred->username($default_username);
3266 } else {
3267 username($cred, $realm, $may_save, $pool);
3269 $cred->password(_read_password("Password for '" .
3270 $cred->username . "': ", $realm));
3271 $cred->may_save($may_save);
3272 $SVN::_Core::SVN_NO_ERROR;
3275 sub ssl_server_trust {
3276 my ($cred, $realm, $failures, $cert_info, $may_save, $pool) = @_;
3277 $may_save = undef if $_no_auth_cache;
3278 print STDERR "Error validating server certificate for '$realm':\n";
3280 no warnings 'once';
3281 # All variables SVN::Auth::SSL::* are used only once,
3282 # so we're shutting up Perl warnings about this.
3283 if ($failures & $SVN::Auth::SSL::UNKNOWNCA) {
3284 print STDERR " - The certificate is not issued ",
3285 "by a trusted authority. Use the\n",
3286 " fingerprint to validate ",
3287 "the certificate manually!\n";
3289 if ($failures & $SVN::Auth::SSL::CNMISMATCH) {
3290 print STDERR " - The certificate hostname ",
3291 "does not match.\n";
3293 if ($failures & $SVN::Auth::SSL::NOTYETVALID) {
3294 print STDERR " - The certificate is not yet valid.\n";
3296 if ($failures & $SVN::Auth::SSL::EXPIRED) {
3297 print STDERR " - The certificate has expired.\n";
3299 if ($failures & $SVN::Auth::SSL::OTHER) {
3300 print STDERR " - The certificate has ",
3301 "an unknown error.\n";
3303 } # no warnings 'once'
3304 printf STDERR
3305 "Certificate information:\n".
3306 " - Hostname: %s\n".
3307 " - Valid: from %s until %s\n".
3308 " - Issuer: %s\n".
3309 " - Fingerprint: %s\n",
3310 map $cert_info->$_, qw(hostname valid_from valid_until
3311 issuer_dname fingerprint);
3312 my $choice;
3313 prompt:
3314 print STDERR $may_save ?
3315 "(R)eject, accept (t)emporarily or accept (p)ermanently? " :
3316 "(R)eject or accept (t)emporarily? ";
3317 STDERR->flush;
3318 $choice = lc(substr(<STDIN> || 'R', 0, 1));
3319 if ($choice =~ /^t$/i) {
3320 $cred->may_save(undef);
3321 } elsif ($choice =~ /^r$/i) {
3322 return -1;
3323 } elsif ($may_save && $choice =~ /^p$/i) {
3324 $cred->may_save($may_save);
3325 } else {
3326 goto prompt;
3328 $cred->accepted_failures($failures);
3329 $SVN::_Core::SVN_NO_ERROR;
3332 sub ssl_client_cert {
3333 my ($cred, $realm, $may_save, $pool) = @_;
3334 $may_save = undef if $_no_auth_cache;
3335 print STDERR "Client certificate filename: ";
3336 STDERR->flush;
3337 chomp(my $filename = <STDIN>);
3338 $cred->cert_file($filename);
3339 $cred->may_save($may_save);
3340 $SVN::_Core::SVN_NO_ERROR;
3343 sub ssl_client_cert_pw {
3344 my ($cred, $realm, $may_save, $pool) = @_;
3345 $may_save = undef if $_no_auth_cache;
3346 $cred->password(_read_password("Password: ", $realm));
3347 $cred->may_save($may_save);
3348 $SVN::_Core::SVN_NO_ERROR;
3351 sub username {
3352 my ($cred, $realm, $may_save, $pool) = @_;
3353 $may_save = undef if $_no_auth_cache;
3354 if (defined $realm && length $realm) {
3355 print STDERR "Authentication realm: $realm\n";
3357 my $username;
3358 if (defined $_username) {
3359 $username = $_username;
3360 } else {
3361 print STDERR "Username: ";
3362 STDERR->flush;
3363 chomp($username = <STDIN>);
3365 $cred->username($username);
3366 $cred->may_save($may_save);
3367 $SVN::_Core::SVN_NO_ERROR;
3370 sub _read_password {
3371 my ($prompt, $realm) = @_;
3372 print STDERR $prompt;
3373 STDERR->flush;
3374 require Term::ReadKey;
3375 Term::ReadKey::ReadMode('noecho');
3376 my $password = '';
3377 while (defined(my $key = Term::ReadKey::ReadKey(0))) {
3378 last if $key =~ /[\012\015]/; # \n\r
3379 $password .= $key;
3381 Term::ReadKey::ReadMode('restore');
3382 print STDERR "\n";
3383 STDERR->flush;
3384 $password;
3387 package SVN::Git::Fetcher;
3388 use vars qw/@ISA/;
3389 use strict;
3390 use warnings;
3391 use Carp qw/croak/;
3392 use File::Temp qw/tempfile/;
3393 use IO::File qw//;
3394 use vars qw/$_ignore_regex/;
3396 # file baton members: path, mode_a, mode_b, pool, fh, blob, base
3397 sub new {
3398 my ($class, $git_svn, $switch_path) = @_;
3399 my $self = SVN::Delta::Editor->new;
3400 bless $self, $class;
3401 if (exists $git_svn->{last_commit}) {
3402 $self->{c} = $git_svn->{last_commit};
3403 $self->{empty_symlinks} =
3404 _mark_empty_symlinks($git_svn, $switch_path);
3406 $self->{ignore_regex} = eval { command_oneline('config', '--get',
3407 "svn-remote.$git_svn->{repo_id}.ignore-paths") };
3408 $self->{empty} = {};
3409 $self->{dir_prop} = {};
3410 $self->{file_prop} = {};
3411 $self->{absent_dir} = {};
3412 $self->{absent_file} = {};
3413 $self->{gii} = $git_svn->tmp_index_do(sub { Git::IndexInfo->new });
3414 $self;
3417 # this uses the Ra object, so it must be called before do_{switch,update},
3418 # not inside them (when the Git::SVN::Fetcher object is passed) to
3419 # do_{switch,update}
3420 sub _mark_empty_symlinks {
3421 my ($git_svn, $switch_path) = @_;
3422 my $bool = Git::config_bool('svn.brokenSymlinkWorkaround');
3423 return {} if (!defined($bool)) || (defined($bool) && ! $bool);
3425 my %ret;
3426 my ($rev, $cmt) = $git_svn->last_rev_commit;
3427 return {} unless ($rev && $cmt);
3429 # allow the warning to be printed for each revision we fetch to
3430 # ensure the user sees it. The user can also disable the workaround
3431 # on the repository even while git svn is running and the next
3432 # revision fetched will skip this expensive function.
3433 my $printed_warning;
3434 chomp(my $empty_blob = `git hash-object -t blob --stdin < /dev/null`);
3435 my ($ls, $ctx) = command_output_pipe(qw/ls-tree -r -z/, $cmt);
3436 local $/ = "\0";
3437 my $pfx = defined($switch_path) ? $switch_path : $git_svn->{path};
3438 $pfx .= '/' if length($pfx);
3439 while (<$ls>) {
3440 chomp;
3441 s/\A100644 blob $empty_blob\t//o or next;
3442 unless ($printed_warning) {
3443 print STDERR "Scanning for empty symlinks, ",
3444 "this may take a while if you have ",
3445 "many empty files\n",
3446 "You may disable this with `",
3447 "git config svn.brokenSymlinkWorkaround ",
3448 "false'.\n",
3449 "This may be done in a different ",
3450 "terminal without restarting ",
3451 "git svn\n";
3452 $printed_warning = 1;
3454 my $path = $_;
3455 my (undef, $props) =
3456 $git_svn->ra->get_file($pfx.$path, $rev, undef);
3457 if ($props->{'svn:special'}) {
3458 $ret{$path} = 1;
3461 command_close_pipe($ls, $ctx);
3462 \%ret;
3465 # returns true if a given path is inside a ".git" directory
3466 sub in_dot_git {
3467 $_[0] =~ m{(?:^|/)\.git(?:/|$)};
3470 # return value: 0 -- don't ignore, 1 -- ignore
3471 sub is_path_ignored {
3472 my ($self, $path) = @_;
3473 return 1 if in_dot_git($path);
3474 return 1 if defined($self->{ignore_regex}) &&
3475 $path =~ m!$self->{ignore_regex}!;
3476 return 0 unless defined($_ignore_regex);
3477 return 1 if $path =~ m!$_ignore_regex!o;
3478 return 0;
3481 sub set_path_strip {
3482 my ($self, $path) = @_;
3483 $self->{path_strip} = qr/^\Q$path\E(\/|$)/ if length $path;
3486 sub open_root {
3487 { path => '' };
3490 sub open_directory {
3491 my ($self, $path, $pb, $rev) = @_;
3492 { path => $path };
3495 sub git_path {
3496 my ($self, $path) = @_;
3497 if ($self->{path_strip}) {
3498 $path =~ s!$self->{path_strip}!! or
3499 die "Failed to strip path '$path' ($self->{path_strip})\n";
3501 $path;
3504 sub delete_entry {
3505 my ($self, $path, $rev, $pb) = @_;
3506 return undef if $self->is_path_ignored($path);
3508 my $gpath = $self->git_path($path);
3509 return undef if ($gpath eq '');
3511 # remove entire directories.
3512 my ($tree) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3513 =~ /\A040000 tree ([a-f\d]{40})\t\Q$gpath\E\0/);
3514 if ($tree) {
3515 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3516 -r --name-only -z/,
3517 $tree);
3518 local $/ = "\0";
3519 while (<$ls>) {
3520 chomp;
3521 my $rmpath = "$gpath/$_";
3522 $self->{gii}->remove($rmpath);
3523 print "\tD\t$rmpath\n" unless $::_q;
3525 print "\tD\t$gpath/\n" unless $::_q;
3526 command_close_pipe($ls, $ctx);
3527 $self->{empty}->{$path} = 0
3528 } else {
3529 $self->{gii}->remove($gpath);
3530 print "\tD\t$gpath\n" unless $::_q;
3532 undef;
3535 sub open_file {
3536 my ($self, $path, $pb, $rev) = @_;
3537 my ($mode, $blob);
3539 goto out if $self->is_path_ignored($path);
3541 my $gpath = $self->git_path($path);
3542 ($mode, $blob) = (command('ls-tree', '-z', $self->{c}, "./$gpath")
3543 =~ /\A(\d{6}) blob ([a-f\d]{40})\t\Q$gpath\E\0/);
3544 unless (defined $mode && defined $blob) {
3545 die "$path was not found in commit $self->{c} (r$rev)\n";
3547 if ($mode eq '100644' && $self->{empty_symlinks}->{$path}) {
3548 $mode = '120000';
3550 out:
3551 { path => $path, mode_a => $mode, mode_b => $mode, blob => $blob,
3552 pool => SVN::Pool->new, action => 'M' };
3555 sub add_file {
3556 my ($self, $path, $pb, $cp_path, $cp_rev) = @_;
3557 my $mode;
3559 if (!$self->is_path_ignored($path)) {
3560 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3561 delete $self->{empty}->{$dir};
3562 $mode = '100644';
3564 { path => $path, mode_a => $mode, mode_b => $mode,
3565 pool => SVN::Pool->new, action => 'A' };
3568 sub add_directory {
3569 my ($self, $path, $cp_path, $cp_rev) = @_;
3570 goto out if $self->is_path_ignored($path);
3571 my $gpath = $self->git_path($path);
3572 if ($gpath eq '') {
3573 my ($ls, $ctx) = command_output_pipe(qw/ls-tree
3574 -r --name-only -z/,
3575 $self->{c});
3576 local $/ = "\0";
3577 while (<$ls>) {
3578 chomp;
3579 $self->{gii}->remove($_);
3580 print "\tD\t$_\n" unless $::_q;
3582 command_close_pipe($ls, $ctx);
3583 $self->{empty}->{$path} = 0;
3585 my ($dir, $file) = ($path =~ m#^(.*?)/?([^/]+)$#);
3586 delete $self->{empty}->{$dir};
3587 $self->{empty}->{$path} = 1;
3588 out:
3589 { path => $path };
3592 sub change_dir_prop {
3593 my ($self, $db, $prop, $value) = @_;
3594 return undef if $self->is_path_ignored($db->{path});
3595 $self->{dir_prop}->{$db->{path}} ||= {};
3596 $self->{dir_prop}->{$db->{path}}->{$prop} = $value;
3597 undef;
3600 sub absent_directory {
3601 my ($self, $path, $pb) = @_;
3602 return undef if $self->is_path_ignored($path);
3603 $self->{absent_dir}->{$pb->{path}} ||= [];
3604 push @{$self->{absent_dir}->{$pb->{path}}}, $path;
3605 undef;
3608 sub absent_file {
3609 my ($self, $path, $pb) = @_;
3610 return undef if $self->is_path_ignored($path);
3611 $self->{absent_file}->{$pb->{path}} ||= [];
3612 push @{$self->{absent_file}->{$pb->{path}}}, $path;
3613 undef;
3616 sub change_file_prop {
3617 my ($self, $fb, $prop, $value) = @_;
3618 return undef if $self->is_path_ignored($fb->{path});
3619 if ($prop eq 'svn:executable') {
3620 if ($fb->{mode_b} != 120000) {
3621 $fb->{mode_b} = defined $value ? 100755 : 100644;
3623 } elsif ($prop eq 'svn:special') {
3624 $fb->{mode_b} = defined $value ? 120000 : 100644;
3625 } else {
3626 $self->{file_prop}->{$fb->{path}} ||= {};
3627 $self->{file_prop}->{$fb->{path}}->{$prop} = $value;
3629 undef;
3632 sub apply_textdelta {
3633 my ($self, $fb, $exp) = @_;
3634 return undef if $self->is_path_ignored($fb->{path});
3635 my $fh = $::_repository->temp_acquire('svn_delta');
3636 # $fh gets auto-closed() by SVN::TxDelta::apply(),
3637 # (but $base does not,) so dup() it for reading in close_file
3638 open my $dup, '<&', $fh or croak $!;
3639 my $base = $::_repository->temp_acquire('git_blob');
3641 if ($fb->{blob}) {
3642 my ($base_is_link, $size);
3644 if ($fb->{mode_a} eq '120000' &&
3645 ! $self->{empty_symlinks}->{$fb->{path}}) {
3646 print $base 'link ' or die "print $!\n";
3647 $base_is_link = 1;
3649 retry:
3650 $size = $::_repository->cat_blob($fb->{blob}, $base);
3651 die "Failed to read object $fb->{blob}" if ($size < 0);
3653 if (defined $exp) {
3654 seek $base, 0, 0 or croak $!;
3655 my $got = ::md5sum($base);
3656 if ($got ne $exp) {
3657 my $err = "Checksum mismatch: ".
3658 "$fb->{path} $fb->{blob}\n" .
3659 "expected: $exp\n" .
3660 " got: $got\n";
3661 if ($base_is_link) {
3662 warn $err,
3663 "Retrying... (possibly ",
3664 "a bad symlink from SVN)\n";
3665 $::_repository->temp_reset($base);
3666 $base_is_link = 0;
3667 goto retry;
3669 die $err;
3673 seek $base, 0, 0 or croak $!;
3674 $fb->{fh} = $fh;
3675 $fb->{base} = $base;
3676 [ SVN::TxDelta::apply($base, $dup, undef, $fb->{path}, $fb->{pool}) ];
3679 sub close_file {
3680 my ($self, $fb, $exp) = @_;
3681 return undef if $self->is_path_ignored($fb->{path});
3683 my $hash;
3684 my $path = $self->git_path($fb->{path});
3685 if (my $fh = $fb->{fh}) {
3686 if (defined $exp) {
3687 seek($fh, 0, 0) or croak $!;
3688 my $got = ::md5sum($fh);
3689 if ($got ne $exp) {
3690 die "Checksum mismatch: $path\n",
3691 "expected: $exp\n got: $got\n";
3694 if ($fb->{mode_b} == 120000) {
3695 sysseek($fh, 0, 0) or croak $!;
3696 my $rd = sysread($fh, my $buf, 5);
3698 if (!defined $rd) {
3699 croak "sysread: $!\n";
3700 } elsif ($rd == 0) {
3701 warn "$path has mode 120000",
3702 " but it points to nothing\n",
3703 "converting to an empty file with mode",
3704 " 100644\n";
3705 $fb->{mode_b} = '100644';
3706 } elsif ($buf ne 'link ') {
3707 warn "$path has mode 120000",
3708 " but is not a link\n";
3709 } else {
3710 my $tmp_fh = $::_repository->temp_acquire(
3711 'svn_hash');
3712 my $res;
3713 while ($res = sysread($fh, my $str, 1024)) {
3714 my $out = syswrite($tmp_fh, $str, $res);
3715 defined($out) && $out == $res
3716 or croak("write ",
3717 Git::temp_path($tmp_fh),
3718 ": $!\n");
3720 defined $res or croak $!;
3722 ($fh, $tmp_fh) = ($tmp_fh, $fh);
3723 Git::temp_release($tmp_fh, 1);
3727 $hash = $::_repository->hash_and_insert_object(
3728 Git::temp_path($fh));
3729 $hash =~ /^[a-f\d]{40}$/ or die "not a sha1: $hash\n";
3731 Git::temp_release($fb->{base}, 1);
3732 Git::temp_release($fh, 1);
3733 } else {
3734 $hash = $fb->{blob} or die "no blob information\n";
3736 $fb->{pool}->clear;
3737 $self->{gii}->update($fb->{mode_b}, $hash, $path) or croak $!;
3738 print "\t$fb->{action}\t$path\n" if $fb->{action} && ! $::_q;
3739 undef;
3742 sub abort_edit {
3743 my $self = shift;
3744 $self->{nr} = $self->{gii}->{nr};
3745 delete $self->{gii};
3746 $self->SUPER::abort_edit(@_);
3749 sub close_edit {
3750 my $self = shift;
3751 $self->{git_commit_ok} = 1;
3752 $self->{nr} = $self->{gii}->{nr};
3753 delete $self->{gii};
3754 $self->SUPER::close_edit(@_);
3757 package SVN::Git::Editor;
3758 use vars qw/@ISA $_rmdir $_cp_similarity $_find_copies_harder $_rename_limit/;
3759 use strict;
3760 use warnings;
3761 use Carp qw/croak/;
3762 use IO::File;
3764 sub new {
3765 my ($class, $opts) = @_;
3766 foreach (qw/svn_path r ra tree_a tree_b log editor_cb/) {
3767 die "$_ required!\n" unless (defined $opts->{$_});
3770 my $pool = SVN::Pool->new;
3771 my $mods = generate_diff($opts->{tree_a}, $opts->{tree_b});
3772 my $types = check_diff_paths($opts->{ra}, $opts->{svn_path},
3773 $opts->{r}, $mods);
3775 # $opts->{ra} functions should not be used after this:
3776 my @ce = $opts->{ra}->get_commit_editor($opts->{log},
3777 $opts->{editor_cb}, $pool);
3778 my $self = SVN::Delta::Editor->new(@ce, $pool);
3779 bless $self, $class;
3780 foreach (qw/svn_path r tree_a tree_b/) {
3781 $self->{$_} = $opts->{$_};
3783 $self->{url} = $opts->{ra}->{url};
3784 $self->{mods} = $mods;
3785 $self->{types} = $types;
3786 $self->{pool} = $pool;
3787 $self->{bat} = { '' => $self->open_root($self->{r}, $self->{pool}) };
3788 $self->{rm} = { };
3789 $self->{path_prefix} = length $self->{svn_path} ?
3790 "$self->{svn_path}/" : '';
3791 $self->{config} = $opts->{config};
3792 return $self;
3795 sub generate_diff {
3796 my ($tree_a, $tree_b) = @_;
3797 my @diff_tree = qw(diff-tree -z -r);
3798 if ($_cp_similarity) {
3799 push @diff_tree, "-C$_cp_similarity";
3800 } else {
3801 push @diff_tree, '-C';
3803 push @diff_tree, '--find-copies-harder' if $_find_copies_harder;
3804 push @diff_tree, "-l$_rename_limit" if defined $_rename_limit;
3805 push @diff_tree, $tree_a, $tree_b;
3806 my ($diff_fh, $ctx) = command_output_pipe(@diff_tree);
3807 local $/ = "\0";
3808 my $state = 'meta';
3809 my @mods;
3810 while (<$diff_fh>) {
3811 chomp $_; # this gets rid of the trailing "\0"
3812 if ($state eq 'meta' && /^:(\d{6})\s(\d{6})\s
3813 ($::sha1)\s($::sha1)\s
3814 ([MTCRAD])\d*$/xo) {
3815 push @mods, { mode_a => $1, mode_b => $2,
3816 sha1_a => $3, sha1_b => $4,
3817 chg => $5 };
3818 if ($5 =~ /^(?:C|R)$/) {
3819 $state = 'file_a';
3820 } else {
3821 $state = 'file_b';
3823 } elsif ($state eq 'file_a') {
3824 my $x = $mods[$#mods] or croak "Empty array\n";
3825 if ($x->{chg} !~ /^(?:C|R)$/) {
3826 croak "Error parsing $_, $x->{chg}\n";
3828 $x->{file_a} = $_;
3829 $state = 'file_b';
3830 } elsif ($state eq 'file_b') {
3831 my $x = $mods[$#mods] or croak "Empty array\n";
3832 if (exists $x->{file_a} && $x->{chg} !~ /^(?:C|R)$/) {
3833 croak "Error parsing $_, $x->{chg}\n";
3835 if (!exists $x->{file_a} && $x->{chg} =~ /^(?:C|R)$/) {
3836 croak "Error parsing $_, $x->{chg}\n";
3838 $x->{file_b} = $_;
3839 $state = 'meta';
3840 } else {
3841 croak "Error parsing $_\n";
3844 command_close_pipe($diff_fh, $ctx);
3845 \@mods;
3848 sub check_diff_paths {
3849 my ($ra, $pfx, $rev, $mods) = @_;
3850 my %types;
3851 $pfx .= '/' if length $pfx;
3853 sub type_diff_paths {
3854 my ($ra, $types, $path, $rev) = @_;
3855 my @p = split m#/+#, $path;
3856 my $c = shift @p;
3857 unless (defined $types->{$c}) {
3858 $types->{$c} = $ra->check_path($c, $rev);
3860 while (@p) {
3861 $c .= '/' . shift @p;
3862 next if defined $types->{$c};
3863 $types->{$c} = $ra->check_path($c, $rev);
3867 foreach my $m (@$mods) {
3868 foreach my $f (qw/file_a file_b/) {
3869 next unless defined $m->{$f};
3870 my ($dir) = ($m->{$f} =~ m#^(.*?)/?(?:[^/]+)$#);
3871 if (length $pfx.$dir && ! defined $types{$dir}) {
3872 type_diff_paths($ra, \%types, $pfx.$dir, $rev);
3876 \%types;
3879 sub split_path {
3880 return ($_[0] =~ m#^(.*?)/?([^/]+)$#);
3883 sub repo_path {
3884 my ($self, $path) = @_;
3885 $self->{path_prefix}.(defined $path ? $path : '');
3888 sub url_path {
3889 my ($self, $path) = @_;
3890 if ($self->{url} =~ m#^https?://#) {
3891 $path =~ s/([^~a-zA-Z0-9_.-])/uc sprintf("%%%02x",ord($1))/eg;
3893 $self->{url} . '/' . $self->repo_path($path);
3896 sub rmdirs {
3897 my ($self) = @_;
3898 my $rm = $self->{rm};
3899 delete $rm->{''}; # we never delete the url we're tracking
3900 return unless %$rm;
3902 foreach (keys %$rm) {
3903 my @d = split m#/#, $_;
3904 my $c = shift @d;
3905 $rm->{$c} = 1;
3906 while (@d) {
3907 $c .= '/' . shift @d;
3908 $rm->{$c} = 1;
3911 delete $rm->{$self->{svn_path}};
3912 delete $rm->{''}; # we never delete the url we're tracking
3913 return unless %$rm;
3915 my ($fh, $ctx) = command_output_pipe(qw/ls-tree --name-only -r -z/,
3916 $self->{tree_b});
3917 local $/ = "\0";
3918 while (<$fh>) {
3919 chomp;
3920 my @dn = split m#/#, $_;
3921 while (pop @dn) {
3922 delete $rm->{join '/', @dn};
3924 unless (%$rm) {
3925 close $fh;
3926 return;
3929 command_close_pipe($fh, $ctx);
3931 my ($r, $p, $bat) = ($self->{r}, $self->{pool}, $self->{bat});
3932 foreach my $d (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$rm) {
3933 $self->close_directory($bat->{$d}, $p);
3934 my ($dn) = ($d =~ m#^(.*?)/?(?:[^/]+)$#);
3935 print "\tD+\t$d/\n" unless $::_q;
3936 $self->SUPER::delete_entry($d, $r, $bat->{$dn}, $p);
3937 delete $bat->{$d};
3941 sub open_or_add_dir {
3942 my ($self, $full_path, $baton) = @_;
3943 my $t = $self->{types}->{$full_path};
3944 if (!defined $t) {
3945 die "$full_path not known in r$self->{r} or we have a bug!\n";
3948 no warnings 'once';
3949 # SVN::Node::none and SVN::Node::file are used only once,
3950 # so we're shutting up Perl's warnings about them.
3951 if ($t == $SVN::Node::none) {
3952 return $self->add_directory($full_path, $baton,
3953 undef, -1, $self->{pool});
3954 } elsif ($t == $SVN::Node::dir) {
3955 return $self->open_directory($full_path, $baton,
3956 $self->{r}, $self->{pool});
3957 } # no warnings 'once'
3958 print STDERR "$full_path already exists in repository at ",
3959 "r$self->{r} and it is not a directory (",
3960 ($t == $SVN::Node::file ? 'file' : 'unknown'),"/$t)\n";
3961 } # no warnings 'once'
3962 exit 1;
3965 sub ensure_path {
3966 my ($self, $path) = @_;
3967 my $bat = $self->{bat};
3968 my $repo_path = $self->repo_path($path);
3969 return $bat->{''} unless (length $repo_path);
3970 my @p = split m#/+#, $repo_path;
3971 my $c = shift @p;
3972 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{''});
3973 while (@p) {
3974 my $c0 = $c;
3975 $c .= '/' . shift @p;
3976 $bat->{$c} ||= $self->open_or_add_dir($c, $bat->{$c0});
3978 return $bat->{$c};
3981 # Subroutine to convert a globbing pattern to a regular expression.
3982 # From perl cookbook.
3983 sub glob2pat {
3984 my $globstr = shift;
3985 my %patmap = ('*' => '.*', '?' => '.', '[' => '[', ']' => ']');
3986 $globstr =~ s{(.)} { $patmap{$1} || "\Q$1" }ge;
3987 return '^' . $globstr . '$';
3990 sub check_autoprop {
3991 my ($self, $pattern, $properties, $file, $fbat) = @_;
3992 # Convert the globbing pattern to a regular expression.
3993 my $regex = glob2pat($pattern);
3994 # Check if the pattern matches the file name.
3995 if($file =~ m/($regex)/) {
3996 # Parse the list of properties to set.
3997 my @props = split(/;/, $properties);
3998 foreach my $prop (@props) {
3999 # Parse 'name=value' syntax and set the property.
4000 if ($prop =~ /([^=]+)=(.*)/) {
4001 my ($n,$v) = ($1,$2);
4002 for ($n, $v) {
4003 s/^\s+//; s/\s+$//;
4005 $self->change_file_prop($fbat, $n, $v);
4011 sub apply_autoprops {
4012 my ($self, $file, $fbat) = @_;
4013 my $conf_t = ${$self->{config}}{'config'};
4014 no warnings 'once';
4015 # Check [miscellany]/enable-auto-props in svn configuration.
4016 if (SVN::_Core::svn_config_get_bool(
4017 $conf_t,
4018 $SVN::_Core::SVN_CONFIG_SECTION_MISCELLANY,
4019 $SVN::_Core::SVN_CONFIG_OPTION_ENABLE_AUTO_PROPS,
4020 0)) {
4021 # Auto-props are enabled. Enumerate them to look for matches.
4022 my $callback = sub {
4023 $self->check_autoprop($_[0], $_[1], $file, $fbat);
4025 SVN::_Core::svn_config_enumerate(
4026 $conf_t,
4027 $SVN::_Core::SVN_CONFIG_SECTION_AUTO_PROPS,
4028 $callback);
4032 sub A {
4033 my ($self, $m) = @_;
4034 my ($dir, $file) = split_path($m->{file_b});
4035 my $pbat = $self->ensure_path($dir);
4036 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4037 undef, -1);
4038 print "\tA\t$m->{file_b}\n" unless $::_q;
4039 $self->apply_autoprops($file, $fbat);
4040 $self->chg_file($fbat, $m);
4041 $self->close_file($fbat,undef,$self->{pool});
4044 sub C {
4045 my ($self, $m) = @_;
4046 my ($dir, $file) = split_path($m->{file_b});
4047 my $pbat = $self->ensure_path($dir);
4048 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4049 $self->url_path($m->{file_a}), $self->{r});
4050 print "\tC\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4051 $self->chg_file($fbat, $m);
4052 $self->close_file($fbat,undef,$self->{pool});
4055 sub delete_entry {
4056 my ($self, $path, $pbat) = @_;
4057 my $rpath = $self->repo_path($path);
4058 my ($dir, $file) = split_path($rpath);
4059 $self->{rm}->{$dir} = 1;
4060 $self->SUPER::delete_entry($rpath, $self->{r}, $pbat, $self->{pool});
4063 sub R {
4064 my ($self, $m) = @_;
4065 my ($dir, $file) = split_path($m->{file_b});
4066 my $pbat = $self->ensure_path($dir);
4067 my $fbat = $self->add_file($self->repo_path($m->{file_b}), $pbat,
4068 $self->url_path($m->{file_a}), $self->{r});
4069 print "\tR\t$m->{file_a} => $m->{file_b}\n" unless $::_q;
4070 $self->apply_autoprops($file, $fbat);
4071 $self->chg_file($fbat, $m);
4072 $self->close_file($fbat,undef,$self->{pool});
4074 ($dir, $file) = split_path($m->{file_a});
4075 $pbat = $self->ensure_path($dir);
4076 $self->delete_entry($m->{file_a}, $pbat);
4079 sub M {
4080 my ($self, $m) = @_;
4081 my ($dir, $file) = split_path($m->{file_b});
4082 my $pbat = $self->ensure_path($dir);
4083 my $fbat = $self->open_file($self->repo_path($m->{file_b}),
4084 $pbat,$self->{r},$self->{pool});
4085 print "\t$m->{chg}\t$m->{file_b}\n" unless $::_q;
4086 $self->chg_file($fbat, $m);
4087 $self->close_file($fbat,undef,$self->{pool});
4090 sub T { shift->M(@_) }
4092 sub change_file_prop {
4093 my ($self, $fbat, $pname, $pval) = @_;
4094 $self->SUPER::change_file_prop($fbat, $pname, $pval, $self->{pool});
4097 sub _chg_file_get_blob ($$$$) {
4098 my ($self, $fbat, $m, $which) = @_;
4099 my $fh = $::_repository->temp_acquire("git_blob_$which");
4100 if ($m->{"mode_$which"} =~ /^120/) {
4101 print $fh 'link ' or croak $!;
4102 $self->change_file_prop($fbat,'svn:special','*');
4103 } elsif ($m->{mode_a} =~ /^120/ && $m->{"mode_$which"} !~ /^120/) {
4104 $self->change_file_prop($fbat,'svn:special',undef);
4106 my $blob = $m->{"sha1_$which"};
4107 return ($fh,) if ($blob =~ /^0{40}$/);
4108 my $size = $::_repository->cat_blob($blob, $fh);
4109 croak "Failed to read object $blob" if ($size < 0);
4110 $fh->flush == 0 or croak $!;
4111 seek $fh, 0, 0 or croak $!;
4113 my $exp = ::md5sum($fh);
4114 seek $fh, 0, 0 or croak $!;
4115 return ($fh, $exp);
4118 sub chg_file {
4119 my ($self, $fbat, $m) = @_;
4120 if ($m->{mode_b} =~ /755$/ && $m->{mode_a} !~ /755$/) {
4121 $self->change_file_prop($fbat,'svn:executable','*');
4122 } elsif ($m->{mode_b} !~ /755$/ && $m->{mode_a} =~ /755$/) {
4123 $self->change_file_prop($fbat,'svn:executable',undef);
4125 my ($fh_a, $exp_a) = _chg_file_get_blob $self, $fbat, $m, 'a';
4126 my ($fh_b, $exp_b) = _chg_file_get_blob $self, $fbat, $m, 'b';
4127 my $pool = SVN::Pool->new;
4128 my $atd = $self->apply_textdelta($fbat, $exp_a, $pool);
4129 if (-s $fh_a) {
4130 my $txstream = SVN::TxDelta::new ($fh_a, $fh_b, $pool);
4131 my $res = SVN::TxDelta::send_txstream($txstream, @$atd, $pool);
4132 if (defined $res) {
4133 die "Unexpected result from send_txstream: $res\n",
4134 "(SVN::Core::VERSION: $SVN::Core::VERSION)\n";
4136 } else {
4137 my $got = SVN::TxDelta::send_stream($fh_b, @$atd, $pool);
4138 die "Checksum mismatch\nexpected: $exp_b\ngot: $got\n"
4139 if ($got ne $exp_b);
4141 Git::temp_release($fh_b, 1);
4142 Git::temp_release($fh_a, 1);
4143 $pool->clear;
4146 sub D {
4147 my ($self, $m) = @_;
4148 my ($dir, $file) = split_path($m->{file_b});
4149 my $pbat = $self->ensure_path($dir);
4150 print "\tD\t$m->{file_b}\n" unless $::_q;
4151 $self->delete_entry($m->{file_b}, $pbat);
4154 sub close_edit {
4155 my ($self) = @_;
4156 my ($p,$bat) = ($self->{pool}, $self->{bat});
4157 foreach (sort { $b =~ tr#/#/# <=> $a =~ tr#/#/# } keys %$bat) {
4158 next if $_ eq '';
4159 $self->close_directory($bat->{$_}, $p);
4161 $self->close_directory($bat->{''}, $p);
4162 $self->SUPER::close_edit($p);
4163 $p->clear;
4166 sub abort_edit {
4167 my ($self) = @_;
4168 $self->SUPER::abort_edit($self->{pool});
4171 sub DESTROY {
4172 my $self = shift;
4173 $self->SUPER::DESTROY(@_);
4174 $self->{pool}->clear;
4177 # this drives the editor
4178 sub apply_diff {
4179 my ($self) = @_;
4180 my $mods = $self->{mods};
4181 my %o = ( D => 1, R => 0, C => -1, A => 3, M => 3, T => 3 );
4182 foreach my $m (sort { $o{$a->{chg}} <=> $o{$b->{chg}} } @$mods) {
4183 my $f = $m->{chg};
4184 if (defined $o{$f}) {
4185 $self->$f($m);
4186 } else {
4187 fatal("Invalid change type: $f");
4190 $self->rmdirs if $_rmdir;
4191 if (@$mods == 0) {
4192 $self->abort_edit;
4193 } else {
4194 $self->close_edit;
4196 return scalar @$mods;
4199 package Git::SVN::Ra;
4200 use vars qw/@ISA $config_dir $_log_window_size/;
4201 use strict;
4202 use warnings;
4203 my ($ra_invalid, $can_do_switch, %ignored_err, $RA);
4205 BEGIN {
4206 # enforce temporary pool usage for some simple functions
4207 no strict 'refs';
4208 for my $f (qw/rev_proplist get_latest_revnum get_uuid get_repos_root
4209 get_file/) {
4210 my $SUPER = "SUPER::$f";
4211 *$f = sub {
4212 my $self = shift;
4213 my $pool = SVN::Pool->new;
4214 my @ret = $self->$SUPER(@_,$pool);
4215 $pool->clear;
4216 wantarray ? @ret : $ret[0];
4221 sub _auth_providers () {
4223 SVN::Client::get_simple_provider(),
4224 SVN::Client::get_ssl_server_trust_file_provider(),
4225 SVN::Client::get_simple_prompt_provider(
4226 \&Git::SVN::Prompt::simple, 2),
4227 SVN::Client::get_ssl_client_cert_file_provider(),
4228 SVN::Client::get_ssl_client_cert_prompt_provider(
4229 \&Git::SVN::Prompt::ssl_client_cert, 2),
4230 SVN::Client::get_ssl_client_cert_pw_file_provider(),
4231 SVN::Client::get_ssl_client_cert_pw_prompt_provider(
4232 \&Git::SVN::Prompt::ssl_client_cert_pw, 2),
4233 SVN::Client::get_username_provider(),
4234 SVN::Client::get_ssl_server_trust_prompt_provider(
4235 \&Git::SVN::Prompt::ssl_server_trust),
4236 SVN::Client::get_username_prompt_provider(
4237 \&Git::SVN::Prompt::username, 2)
4241 sub escape_uri_only {
4242 my ($uri) = @_;
4243 my @tmp;
4244 foreach (split m{/}, $uri) {
4245 s/([^~\w.%+-]|%(?![a-fA-F0-9]{2}))/sprintf("%%%02X",ord($1))/eg;
4246 push @tmp, $_;
4248 join('/', @tmp);
4251 sub escape_url {
4252 my ($url) = @_;
4253 if ($url =~ m#^(https?)://([^/]+)(.*)$#) {
4254 my ($scheme, $domain, $uri) = ($1, $2, escape_uri_only($3));
4255 $url = "$scheme://$domain$uri";
4257 $url;
4260 sub new {
4261 my ($class, $url) = @_;
4262 $url =~ s!/+$!!;
4263 return $RA if ($RA && $RA->{url} eq $url);
4265 SVN::_Core::svn_config_ensure($config_dir, undef);
4266 my ($baton, $callbacks) = SVN::Core::auth_open_helper(_auth_providers);
4267 my $config = SVN::Core::config_get_config($config_dir);
4268 $RA = undef;
4269 my $dont_store_passwords = 1;
4270 my $conf_t = ${$config}{'config'};
4272 no warnings 'once';
4273 # The usage of $SVN::_Core::SVN_CONFIG_* variables
4274 # produces warnings that variables are used only once.
4275 # I had not found the better way to shut them up, so
4276 # the warnings of type 'once' are disabled in this block.
4277 if (SVN::_Core::svn_config_get_bool($conf_t,
4278 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4279 $SVN::_Core::SVN_CONFIG_OPTION_STORE_PASSWORDS,
4280 1) == 0) {
4281 SVN::_Core::svn_auth_set_parameter($baton,
4282 $SVN::_Core::SVN_AUTH_PARAM_DONT_STORE_PASSWORDS,
4283 bless (\$dont_store_passwords, "_p_void"));
4285 if (SVN::_Core::svn_config_get_bool($conf_t,
4286 $SVN::_Core::SVN_CONFIG_SECTION_AUTH,
4287 $SVN::_Core::SVN_CONFIG_OPTION_STORE_AUTH_CREDS,
4288 1) == 0) {
4289 $Git::SVN::Prompt::_no_auth_cache = 1;
4291 } # no warnings 'once'
4292 my $self = SVN::Ra->new(url => escape_url($url), auth => $baton,
4293 config => $config,
4294 pool => SVN::Pool->new,
4295 auth_provider_callbacks => $callbacks);
4296 $self->{url} = $url;
4297 $self->{svn_path} = $url;
4298 $self->{repos_root} = $self->get_repos_root;
4299 $self->{svn_path} =~ s#^\Q$self->{repos_root}\E(/|$)##;
4300 $self->{cache} = { check_path => { r => 0, data => {} },
4301 get_dir => { r => 0, data => {} } };
4302 $RA = bless $self, $class;
4305 sub check_path {
4306 my ($self, $path, $r) = @_;
4307 my $cache = $self->{cache}->{check_path};
4308 if ($r == $cache->{r} && exists $cache->{data}->{$path}) {
4309 return $cache->{data}->{$path};
4311 my $pool = SVN::Pool->new;
4312 my $t = $self->SUPER::check_path($path, $r, $pool);
4313 $pool->clear;
4314 if ($r != $cache->{r}) {
4315 %{$cache->{data}} = ();
4316 $cache->{r} = $r;
4318 $cache->{data}->{$path} = $t;
4321 sub get_dir {
4322 my ($self, $dir, $r) = @_;
4323 my $cache = $self->{cache}->{get_dir};
4324 if ($r == $cache->{r}) {
4325 if (my $x = $cache->{data}->{$dir}) {
4326 return wantarray ? @$x : $x->[0];
4329 my $pool = SVN::Pool->new;
4330 my ($d, undef, $props) = $self->SUPER::get_dir($dir, $r, $pool);
4331 my %dirents = map { $_ => { kind => $d->{$_}->kind } } keys %$d;
4332 $pool->clear;
4333 if ($r != $cache->{r}) {
4334 %{$cache->{data}} = ();
4335 $cache->{r} = $r;
4337 $cache->{data}->{$dir} = [ \%dirents, $r, $props ];
4338 wantarray ? (\%dirents, $r, $props) : \%dirents;
4341 sub DESTROY {
4342 # do not call the real DESTROY since we store ourselves in $RA
4345 # get_log(paths, start, end, limit,
4346 # discover_changed_paths, strict_node_history, receiver)
4347 sub get_log {
4348 my ($self, @args) = @_;
4349 my $pool = SVN::Pool->new;
4351 # the limit parameter was not supported in SVN 1.1.x, so we
4352 # drop it. Therefore, the receiver callback passed to it
4353 # is made aware of this limitation by being wrapped if
4354 # the limit passed to is being wrapped.
4355 if ($SVN::Core::VERSION le '1.2.0') {
4356 my $limit = splice(@args, 3, 1);
4357 if ($limit > 0) {
4358 my $receiver = pop @args;
4359 push(@args, sub { &$receiver(@_) if (--$limit >= 0) });
4362 my $ret = $self->SUPER::get_log(@args, $pool);
4363 $pool->clear;
4364 $ret;
4367 sub trees_match {
4368 my ($self, $url1, $rev1, $url2, $rev2) = @_;
4369 my $ctx = SVN::Client->new(auth => _auth_providers);
4370 my $out = IO::File->new_tmpfile;
4372 # older SVN (1.1.x) doesn't take $pool as the last parameter for
4373 # $ctx->diff(), so we'll create a default one
4374 my $pool = SVN::Pool->new_default_sub;
4376 $ra_invalid = 1; # this will open a new SVN::Ra connection to $url1
4377 $ctx->diff([], $url1, $rev1, $url2, $rev2, 1, 1, 0, $out, $out);
4378 $out->flush;
4379 my $ret = (($out->stat)[7] == 0);
4380 close $out or croak $!;
4382 $ret;
4385 sub get_commit_editor {
4386 my ($self, $log, $cb, $pool) = @_;
4387 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef, 0) : ();
4388 $self->SUPER::get_commit_editor($log, $cb, @lock, $pool);
4391 sub gs_do_update {
4392 my ($self, $rev_a, $rev_b, $gs, $editor) = @_;
4393 my $new = ($rev_a == $rev_b);
4394 my $path = $gs->{path};
4396 if ($new && -e $gs->{index}) {
4397 unlink $gs->{index} or die
4398 "Couldn't unlink index: $gs->{index}: $!\n";
4400 my $pool = SVN::Pool->new;
4401 $editor->set_path_strip($path);
4402 my (@pc) = split m#/#, $path;
4403 my $reporter = $self->do_update($rev_b, (@pc ? shift @pc : ''),
4404 1, $editor, $pool);
4405 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4407 # Since we can't rely on svn_ra_reparent being available, we'll
4408 # just have to do some magic with set_path to make it so
4409 # we only want a partial path.
4410 my $sp = '';
4411 my $final = join('/', @pc);
4412 while (@pc) {
4413 $reporter->set_path($sp, $rev_b, 0, @lock, $pool);
4414 $sp .= '/' if length $sp;
4415 $sp .= shift @pc;
4417 die "BUG: '$sp' != '$final'\n" if ($sp ne $final);
4419 $reporter->set_path($sp, $rev_a, $new, @lock, $pool);
4421 $reporter->finish_report($pool);
4422 $pool->clear;
4423 $editor->{git_commit_ok};
4426 # this requires SVN 1.4.3 or later (do_switch didn't work before 1.4.3, and
4427 # svn_ra_reparent didn't work before 1.4)
4428 sub gs_do_switch {
4429 my ($self, $rev_a, $rev_b, $gs, $url_b, $editor) = @_;
4430 my $path = $gs->{path};
4431 my $pool = SVN::Pool->new;
4433 my $full_url = $self->{url};
4434 my $old_url = $full_url;
4435 $full_url .= '/' . escape_uri_only($path) if length $path;
4436 my ($ra, $reparented);
4438 if ($old_url =~ m#^svn(\+ssh)?://#) {
4439 $_[0] = undef;
4440 $self = undef;
4441 $RA = undef;
4442 $ra = Git::SVN::Ra->new($full_url);
4443 $ra_invalid = 1;
4444 } elsif ($old_url ne $full_url) {
4445 SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool);
4446 $self->{url} = $full_url;
4447 $reparented = 1;
4450 $ra ||= $self;
4451 $url_b = escape_url($url_b);
4452 my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool);
4453 my @lock = $SVN::Core::VERSION ge '1.2.0' ? (undef) : ();
4454 $reporter->set_path('', $rev_a, 0, @lock, $pool);
4455 $reporter->finish_report($pool);
4457 if ($reparented) {
4458 SVN::_Ra::svn_ra_reparent($self->{session}, $old_url, $pool);
4459 $self->{url} = $old_url;
4462 $pool->clear;
4463 $editor->{git_commit_ok};
4466 sub longest_common_path {
4467 my ($gsv, $globs) = @_;
4468 my %common;
4469 my $common_max = scalar @$gsv;
4471 foreach my $gs (@$gsv) {
4472 my @tmp = split m#/#, $gs->{path};
4473 my $p = '';
4474 foreach (@tmp) {
4475 $p .= length($p) ? "/$_" : $_;
4476 $common{$p} ||= 0;
4477 $common{$p}++;
4480 $globs ||= [];
4481 $common_max += scalar @$globs;
4482 foreach my $glob (@$globs) {
4483 my @tmp = split m#/#, $glob->{path}->{left};
4484 my $p = '';
4485 foreach (@tmp) {
4486 $p .= length($p) ? "/$_" : $_;
4487 $common{$p} ||= 0;
4488 $common{$p}++;
4492 my $longest_path = '';
4493 foreach (sort {length $b <=> length $a} keys %common) {
4494 if ($common{$_} == $common_max) {
4495 $longest_path = $_;
4496 last;
4499 $longest_path;
4502 sub gs_fetch_loop_common {
4503 my ($self, $base, $head, $gsv, $globs) = @_;
4504 return if ($base > $head);
4505 my $inc = $_log_window_size;
4506 my ($min, $max) = ($base, $head < $base + $inc ? $head : $base + $inc);
4507 my $longest_path = longest_common_path($gsv, $globs);
4508 my $ra_url = $self->{url};
4509 my $find_trailing_edge;
4510 while (1) {
4511 my %revs;
4512 my $err;
4513 my $err_handler = $SVN::Error::handler;
4514 $SVN::Error::handler = sub {
4515 ($err) = @_;
4516 skip_unknown_revs($err);
4518 sub _cb {
4519 my ($paths, $r, $author, $date, $log) = @_;
4520 [ dup_changed_paths($paths),
4521 { author => $author, date => $date, log => $log } ];
4523 $self->get_log([$longest_path], $min, $max, 0, 1, 1,
4524 sub { $revs{$_[1]} = _cb(@_) });
4525 if ($err) {
4526 print "Checked through r$max\r";
4527 } else {
4528 $find_trailing_edge = 1;
4530 if ($err and $find_trailing_edge) {
4531 print STDERR "Path '$longest_path' ",
4532 "was probably deleted:\n",
4533 $err->expanded_message,
4534 "\nWill attempt to follow ",
4535 "revisions r$min .. r$max ",
4536 "committed before the deletion\n";
4537 my $hi = $max;
4538 while (--$hi >= $min) {
4539 my $ok;
4540 $self->get_log([$longest_path], $min, $hi,
4541 0, 1, 1, sub {
4542 $ok = $_[1];
4543 $revs{$_[1]} = _cb(@_) });
4544 if ($ok) {
4545 print STDERR "r$min .. r$ok OK\n";
4546 last;
4549 $find_trailing_edge = 0;
4551 $SVN::Error::handler = $err_handler;
4553 my %exists = map { $_->{path} => $_ } @$gsv;
4554 foreach my $r (sort {$a <=> $b} keys %revs) {
4555 my ($paths, $logged) = @{$revs{$r}};
4557 foreach my $gs ($self->match_globs(\%exists, $paths,
4558 $globs, $r)) {
4559 if ($gs->rev_map_max >= $r) {
4560 next;
4562 next unless $gs->match_paths($paths, $r);
4563 $gs->{logged_rev_props} = $logged;
4564 if (my $last_commit = $gs->last_commit) {
4565 $gs->assert_index_clean($last_commit);
4567 my $log_entry = $gs->do_fetch($paths, $r);
4568 if ($log_entry) {
4569 $gs->do_git_commit($log_entry);
4571 $INDEX_FILES{$gs->{index}} = 1;
4573 foreach my $g (@$globs) {
4574 my $k = "svn-remote.$g->{remote}." .
4575 "$g->{t}-maxRev";
4576 Git::SVN::tmp_config($k, $r);
4578 if ($ra_invalid) {
4579 $_[0] = undef;
4580 $self = undef;
4581 $RA = undef;
4582 $self = Git::SVN::Ra->new($ra_url);
4583 $ra_invalid = undef;
4586 # pre-fill the .rev_db since it'll eventually get filled in
4587 # with '0' x40 if something new gets committed
4588 foreach my $gs (@$gsv) {
4589 next if $gs->rev_map_max >= $max;
4590 next if defined $gs->rev_map_get($max);
4591 $gs->rev_map_set($max, 0 x40);
4593 foreach my $g (@$globs) {
4594 my $k = "svn-remote.$g->{remote}.$g->{t}-maxRev";
4595 Git::SVN::tmp_config($k, $max);
4597 last if $max >= $head;
4598 $min = $max + 1;
4599 $max += $inc;
4600 $max = $head if ($max > $head);
4602 Git::SVN::gc();
4605 sub get_dir_globbed {
4606 my ($self, $left, $depth, $r) = @_;
4608 my @x = eval { $self->get_dir($left, $r) };
4609 return unless scalar @x == 3;
4610 my $dirents = $x[0];
4611 my @finalents;
4612 foreach my $de (keys %$dirents) {
4613 next if $dirents->{$de}->{kind} != $SVN::Node::dir;
4614 if ($depth > 1) {
4615 my @args = ("$left/$de", $depth - 1, $r);
4616 foreach my $dir ($self->get_dir_globbed(@args)) {
4617 push @finalents, "$de/$dir";
4619 } else {
4620 push @finalents, $de;
4623 @finalents;
4626 sub match_globs {
4627 my ($self, $exists, $paths, $globs, $r) = @_;
4629 sub get_dir_check {
4630 my ($self, $exists, $g, $r) = @_;
4632 my @dirs = $self->get_dir_globbed($g->{path}->{left},
4633 $g->{path}->{depth},
4634 $r);
4636 foreach my $de (@dirs) {
4637 my $p = $g->{path}->full_path($de);
4638 next if $exists->{$p};
4639 next if (length $g->{path}->{right} &&
4640 ($self->check_path($p, $r) !=
4641 $SVN::Node::dir));
4642 $exists->{$p} = Git::SVN->init($self->{url}, $p, undef,
4643 $g->{ref}->full_path($de), 1);
4646 foreach my $g (@$globs) {
4647 if (my $path = $paths->{"/$g->{path}->{left}"}) {
4648 if ($path->{action} =~ /^[AR]$/) {
4649 get_dir_check($self, $exists, $g, $r);
4652 foreach (keys %$paths) {
4653 if (/$g->{path}->{left_regex}/ &&
4654 !/$g->{path}->{regex}/) {
4655 next if $paths->{$_}->{action} !~ /^[AR]$/;
4656 get_dir_check($self, $exists, $g, $r);
4658 next unless /$g->{path}->{regex}/;
4659 my $p = $1;
4660 my $pathname = $g->{path}->full_path($p);
4661 next if $exists->{$pathname};
4662 next if ($self->check_path($pathname, $r) !=
4663 $SVN::Node::dir);
4664 $exists->{$pathname} = Git::SVN->init(
4665 $self->{url}, $pathname, undef,
4666 $g->{ref}->full_path($p), 1);
4668 my $c = '';
4669 foreach (split m#/#, $g->{path}->{left}) {
4670 $c .= "/$_";
4671 next unless ($paths->{$c} &&
4672 ($paths->{$c}->{action} =~ /^[AR]$/));
4673 get_dir_check($self, $exists, $g, $r);
4676 values %$exists;
4679 sub minimize_url {
4680 my ($self) = @_;
4681 return $self->{url} if ($self->{url} eq $self->{repos_root});
4682 my $url = $self->{repos_root};
4683 my @components = split(m!/!, $self->{svn_path});
4684 my $c = '';
4685 do {
4686 $url .= "/$c" if length $c;
4687 eval { (ref $self)->new($url)->get_latest_revnum };
4688 } while ($@ && ($c = shift @components));
4689 $url;
4692 sub can_do_switch {
4693 my $self = shift;
4694 unless (defined $can_do_switch) {
4695 my $pool = SVN::Pool->new;
4696 my $rep = eval {
4697 $self->do_switch(1, '', 0, $self->{url},
4698 SVN::Delta::Editor->new, $pool);
4700 if ($@) {
4701 $can_do_switch = 0;
4702 } else {
4703 $rep->abort_report($pool);
4704 $can_do_switch = 1;
4706 $pool->clear;
4708 $can_do_switch;
4711 sub skip_unknown_revs {
4712 my ($err) = @_;
4713 my $errno = $err->apr_err();
4714 # Maybe the branch we're tracking didn't
4715 # exist when the repo started, so it's
4716 # not an error if it doesn't, just continue
4718 # Wonderfully consistent library, eh?
4719 # 160013 - svn:// and file://
4720 # 175002 - http(s)://
4721 # 175007 - http(s):// (this repo required authorization, too...)
4722 # More codes may be discovered later...
4723 if ($errno == 175007 || $errno == 175002 || $errno == 160013) {
4724 my $err_key = $err->expanded_message;
4725 # revision numbers change every time, filter them out
4726 $err_key =~ s/\d+/\0/g;
4727 $err_key = "$errno\0$err_key";
4728 unless ($ignored_err{$err_key}) {
4729 warn "W: Ignoring error from SVN, path probably ",
4730 "does not exist: ($errno): ",
4731 $err->expanded_message,"\n";
4732 warn "W: Do not be alarmed at the above message ",
4733 "git-svn is just searching aggressively for ",
4734 "old history.\n",
4735 "This may take a while on large repositories\n";
4736 $ignored_err{$err_key} = 1;
4738 return;
4740 die "Error from SVN, ($errno): ", $err->expanded_message,"\n";
4743 # svn_log_changed_path_t objects passed to get_log are likely to be
4744 # overwritten even if only the refs are copied to an external variable,
4745 # so we should dup the structures in their entirety. Using an externally
4746 # passed pool (instead of our temporary and quickly cleared pool in
4747 # Git::SVN::Ra) does not help matters at all...
4748 sub dup_changed_paths {
4749 my ($paths) = @_;
4750 return undef unless $paths;
4751 my %ret;
4752 foreach my $p (keys %$paths) {
4753 my $i = $paths->{$p};
4754 my %s = map { $_ => $i->$_ }
4755 qw/copyfrom_path copyfrom_rev action/;
4756 $ret{$p} = \%s;
4758 \%ret;
4761 package Git::SVN::Log;
4762 use strict;
4763 use warnings;
4764 use POSIX qw/strftime/;
4765 use Time::Local;
4766 use constant commit_log_separator => ('-' x 72) . "\n";
4767 use vars qw/$TZ $limit $color $pager $non_recursive $verbose $oneline
4768 %rusers $show_commit $incremental/;
4769 my $l_fmt;
4771 sub cmt_showable {
4772 my ($c) = @_;
4773 return 1 if defined $c->{r};
4775 # big commit message got truncated by the 16k pretty buffer in rev-list
4776 if ($c->{l} && $c->{l}->[-1] eq "...\n" &&
4777 $c->{a_raw} =~ /\@([a-f\d\-]+)>$/) {
4778 @{$c->{l}} = ();
4779 my @log = command(qw/cat-file commit/, $c->{c});
4781 # shift off the headers
4782 shift @log while ($log[0] ne '');
4783 shift @log;
4785 # TODO: make $c->{l} not have a trailing newline in the future
4786 @{$c->{l}} = map { "$_\n" } grep !/^git-svn-id: /, @log;
4788 (undef, $c->{r}, undef) = ::extract_metadata(
4789 (grep(/^git-svn-id: /, @log))[-1]);
4791 return defined $c->{r};
4794 sub log_use_color {
4795 return $color || Git->repository->get_colorbool('color.diff');
4798 sub git_svn_log_cmd {
4799 my ($r_min, $r_max, @args) = @_;
4800 my $head = 'HEAD';
4801 my (@files, @log_opts);
4802 foreach my $x (@args) {
4803 if ($x eq '--' || @files) {
4804 push @files, $x;
4805 } else {
4806 if (::verify_ref("$x^0")) {
4807 $head = $x;
4808 } else {
4809 push @log_opts, $x;
4814 my ($url, $rev, $uuid, $gs) = ::working_head_info($head);
4815 $gs ||= Git::SVN->_new;
4816 my @cmd = (qw/log --abbrev-commit --pretty=raw --default/,
4817 $gs->refname);
4818 push @cmd, '-r' unless $non_recursive;
4819 push @cmd, qw/--raw --name-status/ if $verbose;
4820 push @cmd, '--color' if log_use_color();
4821 push @cmd, @log_opts;
4822 if (defined $r_max && $r_max == $r_min) {
4823 push @cmd, '--max-count=1';
4824 if (my $c = $gs->rev_map_get($r_max)) {
4825 push @cmd, $c;
4827 } elsif (defined $r_max) {
4828 if ($r_max < $r_min) {
4829 ($r_min, $r_max) = ($r_max, $r_min);
4831 my (undef, $c_max) = $gs->find_rev_before($r_max, 1, $r_min);
4832 my (undef, $c_min) = $gs->find_rev_after($r_min, 1, $r_max);
4833 # If there are no commits in the range, both $c_max and $c_min
4834 # will be undefined. If there is at least 1 commit in the
4835 # range, both will be defined.
4836 return () if !defined $c_min || !defined $c_max;
4837 if ($c_min eq $c_max) {
4838 push @cmd, '--max-count=1', $c_min;
4839 } else {
4840 push @cmd, '--boundary', "$c_min..$c_max";
4843 return (@cmd, @files);
4846 # adapted from pager.c
4847 sub config_pager {
4848 $pager ||= $ENV{GIT_PAGER} || $ENV{PAGER};
4849 if (!defined $pager) {
4850 $pager = 'less';
4851 } elsif (length $pager == 0 || $pager eq 'cat') {
4852 $pager = undef;
4854 $ENV{GIT_PAGER_IN_USE} = defined($pager);
4857 sub run_pager {
4858 return unless -t *STDOUT && defined $pager;
4859 pipe my ($rfd, $wfd) or return;
4860 defined(my $pid = fork) or ::fatal "Can't fork: $!";
4861 if (!$pid) {
4862 open STDOUT, '>&', $wfd or
4863 ::fatal "Can't redirect to stdout: $!";
4864 return;
4866 open STDIN, '<&', $rfd or ::fatal "Can't redirect stdin: $!";
4867 $ENV{LESS} ||= 'FRSX';
4868 exec $pager or ::fatal "Can't run pager: $! ($pager)";
4871 sub format_svn_date {
4872 # some systmes don't handle or mishandle %z, so be creative.
4873 my $t = shift || time;
4874 my $gm = timelocal(gmtime($t));
4875 my $sign = qw( + + - )[ $t <=> $gm ];
4876 my $gmoff = sprintf("%s%02d%02d", $sign, (gmtime(abs($t - $gm)))[2,1]);
4877 return strftime("%Y-%m-%d %H:%M:%S $gmoff (%a, %d %b %Y)", localtime($t));
4880 sub parse_git_date {
4881 my ($t, $tz) = @_;
4882 # Date::Parse isn't in the standard Perl distro :(
4883 if ($tz =~ s/^\+//) {
4884 $t += tz_to_s_offset($tz);
4885 } elsif ($tz =~ s/^\-//) {
4886 $t -= tz_to_s_offset($tz);
4888 return $t;
4891 sub set_local_timezone {
4892 if (defined $TZ) {
4893 $ENV{TZ} = $TZ;
4894 } else {
4895 delete $ENV{TZ};
4899 sub tz_to_s_offset {
4900 my ($tz) = @_;
4901 $tz =~ s/(\d\d)$//;
4902 return ($1 * 60) + ($tz * 3600);
4905 sub get_author_info {
4906 my ($dest, $author, $t, $tz) = @_;
4907 $author =~ s/(?:^\s*|\s*$)//g;
4908 $dest->{a_raw} = $author;
4909 my $au;
4910 if ($::_authors) {
4911 $au = $rusers{$author} || undef;
4913 if (!$au) {
4914 ($au) = ($author =~ /<([^>]+)\@[^>]+>$/);
4916 $dest->{t} = $t;
4917 $dest->{tz} = $tz;
4918 $dest->{a} = $au;
4919 $dest->{t_utc} = parse_git_date($t, $tz);
4922 sub process_commit {
4923 my ($c, $r_min, $r_max, $defer) = @_;
4924 if (defined $r_min && defined $r_max) {
4925 if ($r_min == $c->{r} && $r_min == $r_max) {
4926 show_commit($c);
4927 return 0;
4929 return 1 if $r_min == $r_max;
4930 if ($r_min < $r_max) {
4931 # we need to reverse the print order
4932 return 0 if (defined $limit && --$limit < 0);
4933 push @$defer, $c;
4934 return 1;
4936 if ($r_min != $r_max) {
4937 return 1 if ($r_min < $c->{r});
4938 return 1 if ($r_max > $c->{r});
4941 return 0 if (defined $limit && --$limit < 0);
4942 show_commit($c);
4943 return 1;
4946 sub show_commit {
4947 my $c = shift;
4948 if ($oneline) {
4949 my $x = "\n";
4950 if (my $l = $c->{l}) {
4951 while ($l->[0] =~ /^\s*$/) { shift @$l }
4952 $x = $l->[0];
4954 $l_fmt ||= 'A' . length($c->{r});
4955 print 'r',pack($l_fmt, $c->{r}),' | ';
4956 print "$c->{c} | " if $show_commit;
4957 print $x;
4958 } else {
4959 show_commit_normal($c);
4963 sub show_commit_changed_paths {
4964 my ($c) = @_;
4965 return unless $c->{changed};
4966 print "Changed paths:\n", @{$c->{changed}};
4969 sub show_commit_normal {
4970 my ($c) = @_;
4971 print commit_log_separator, "r$c->{r} | ";
4972 print "$c->{c} | " if $show_commit;
4973 print "$c->{a} | ", format_svn_date($c->{t_utc}), ' | ';
4974 my $nr_line = 0;
4976 if (my $l = $c->{l}) {
4977 while ($l->[$#$l] eq "\n" && $#$l > 0
4978 && $l->[($#$l - 1)] eq "\n") {
4979 pop @$l;
4981 $nr_line = scalar @$l;
4982 if (!$nr_line) {
4983 print "1 line\n\n\n";
4984 } else {
4985 if ($nr_line == 1) {
4986 $nr_line = '1 line';
4987 } else {
4988 $nr_line .= ' lines';
4990 print $nr_line, "\n";
4991 show_commit_changed_paths($c);
4992 print "\n";
4993 print $_ foreach @$l;
4995 } else {
4996 print "1 line\n";
4997 show_commit_changed_paths($c);
4998 print "\n";
5001 foreach my $x (qw/raw stat diff/) {
5002 if ($c->{$x}) {
5003 print "\n";
5004 print $_ foreach @{$c->{$x}}
5009 sub cmd_show_log {
5010 my (@args) = @_;
5011 my ($r_min, $r_max);
5012 my $r_last = -1; # prevent dupes
5013 set_local_timezone();
5014 if (defined $::_revision) {
5015 if ($::_revision =~ /^(\d+):(\d+)$/) {
5016 ($r_min, $r_max) = ($1, $2);
5017 } elsif ($::_revision =~ /^\d+$/) {
5018 $r_min = $r_max = $::_revision;
5019 } else {
5020 ::fatal "-r$::_revision is not supported, use ",
5021 "standard 'git log' arguments instead";
5025 config_pager();
5026 @args = git_svn_log_cmd($r_min, $r_max, @args);
5027 if (!@args) {
5028 print commit_log_separator unless $incremental || $oneline;
5029 return;
5031 my $log = command_output_pipe(@args);
5032 run_pager();
5033 my (@k, $c, $d, $stat);
5034 my $esc_color = qr/(?:\033\[(?:(?:\d+;)*\d*)?m)*/;
5035 while (<$log>) {
5036 if (/^${esc_color}commit -?($::sha1_short)/o) {
5037 my $cmt = $1;
5038 if ($c && cmt_showable($c) && $c->{r} != $r_last) {
5039 $r_last = $c->{r};
5040 process_commit($c, $r_min, $r_max, \@k) or
5041 goto out;
5043 $d = undef;
5044 $c = { c => $cmt };
5045 } elsif (/^${esc_color}author (.+) (\d+) ([\-\+]?\d+)$/o) {
5046 get_author_info($c, $1, $2, $3);
5047 } elsif (/^${esc_color}(?:tree|parent|committer) /o) {
5048 # ignore
5049 } elsif (/^${esc_color}:\d{6} \d{6} $::sha1_short/o) {
5050 push @{$c->{raw}}, $_;
5051 } elsif (/^${esc_color}[ACRMDT]\t/) {
5052 # we could add $SVN->{svn_path} here, but that requires
5053 # remote access at the moment (repo_path_split)...
5054 s#^(${esc_color})([ACRMDT])\t#$1 $2 #o;
5055 push @{$c->{changed}}, $_;
5056 } elsif (/^${esc_color}diff /o) {
5057 $d = 1;
5058 push @{$c->{diff}}, $_;
5059 } elsif ($d) {
5060 push @{$c->{diff}}, $_;
5061 } elsif (/^\ .+\ \|\s*\d+\ $esc_color[\+\-]*
5062 $esc_color*[\+\-]*$esc_color$/x) {
5063 $stat = 1;
5064 push @{$c->{stat}}, $_;
5065 } elsif ($stat && /^ \d+ files changed, \d+ insertions/) {
5066 push @{$c->{stat}}, $_;
5067 $stat = undef;
5068 } elsif (/^${esc_color} (git-svn-id:.+)$/o) {
5069 ($c->{url}, $c->{r}, undef) = ::extract_metadata($1);
5070 } elsif (s/^${esc_color} //o) {
5071 push @{$c->{l}}, $_;
5074 if ($c && defined $c->{r} && $c->{r} != $r_last) {
5075 $r_last = $c->{r};
5076 process_commit($c, $r_min, $r_max, \@k);
5078 if (@k) {
5079 ($r_min, $r_max) = ($r_max, $r_min);
5080 process_commit($_, $r_min, $r_max) foreach reverse @k;
5082 out:
5083 close $log;
5084 print commit_log_separator unless $incremental || $oneline;
5087 sub cmd_blame {
5088 my $path = pop;
5090 config_pager();
5091 run_pager();
5093 my ($fh, $ctx, $rev);
5095 if ($_git_format) {
5096 ($fh, $ctx) = command_output_pipe('blame', @_, $path);
5097 while (my $line = <$fh>) {
5098 if ($line =~ /^\^?([[:xdigit:]]+)\s/) {
5099 # Uncommitted edits show up as a rev ID of
5100 # all zeros, which we can't look up with
5101 # cmt_metadata
5102 if ($1 !~ /^0+$/) {
5103 (undef, $rev, undef) =
5104 ::cmt_metadata($1);
5105 $rev = '0' if (!$rev);
5106 } else {
5107 $rev = '0';
5109 $rev = sprintf('%-10s', $rev);
5110 $line =~ s/^\^?[[:xdigit:]]+(\s)/$rev$1/;
5112 print $line;
5114 } else {
5115 ($fh, $ctx) = command_output_pipe('blame', '-p', @_, 'HEAD',
5116 '--', $path);
5117 my ($sha1);
5118 my %authors;
5119 my @buffer;
5120 my %dsha; #distinct sha keys
5122 while (my $line = <$fh>) {
5123 push @buffer, $line;
5124 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5125 $dsha{$1} = 1;
5129 my $s2r = ::cmt_sha2rev_batch([keys %dsha]);
5131 foreach my $line (@buffer) {
5132 if ($line =~ /^([[:xdigit:]]{40})\s\d+\s\d+/) {
5133 $rev = $s2r->{$1};
5134 $rev = '0' if (!$rev)
5136 elsif ($line =~ /^author (.*)/) {
5137 $authors{$rev} = $1;
5138 $authors{$rev} =~ s/\s/_/g;
5140 elsif ($line =~ /^\t(.*)$/) {
5141 printf("%6s %10s %s\n", $rev, $authors{$rev}, $1);
5145 command_close_pipe($fh, $ctx);
5148 package Git::SVN::Migration;
5149 # these version numbers do NOT correspond to actual version numbers
5150 # of git nor git-svn. They are just relative.
5152 # v0 layout: .git/$id/info/url, refs/heads/$id-HEAD
5154 # v1 layout: .git/$id/info/url, refs/remotes/$id
5156 # v2 layout: .git/svn/$id/info/url, refs/remotes/$id
5158 # v3 layout: .git/svn/$id, refs/remotes/$id
5159 # - info/url may remain for backwards compatibility
5160 # - this is what we migrate up to this layout automatically,
5161 # - this will be used by git svn init on single branches
5162 # v3.1 layout (auto migrated):
5163 # - .rev_db => .rev_db.$UUID, .rev_db will remain as a symlink
5164 # for backwards compatibility
5166 # v4 layout: .git/svn/$repo_id/$id, refs/remotes/$repo_id/$id
5167 # - this is only created for newly multi-init-ed
5168 # repositories. Similar in spirit to the
5169 # --use-separate-remotes option in git-clone (now default)
5170 # - we do not automatically migrate to this (following
5171 # the example set by core git)
5173 # v5 layout: .rev_db.$UUID => .rev_map.$UUID
5174 # - newer, more-efficient format that uses 24-bytes per record
5175 # with no filler space.
5176 # - use xxd -c24 < .rev_map.$UUID to view and debug
5177 # - This is a one-way migration, repositories updated to the
5178 # new format will not be able to use old git-svn without
5179 # rebuilding the .rev_db. Rebuilding the rev_db is not
5180 # possible if noMetadata or useSvmProps are set; but should
5181 # be no problem for users that use the (sensible) defaults.
5182 use strict;
5183 use warnings;
5184 use Carp qw/croak/;
5185 use File::Path qw/mkpath/;
5186 use File::Basename qw/dirname basename/;
5187 use vars qw/$_minimize/;
5189 sub migrate_from_v0 {
5190 my $git_dir = $ENV{GIT_DIR};
5191 return undef unless -d $git_dir;
5192 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5193 my $migrated = 0;
5194 while (<$fh>) {
5195 chomp;
5196 my ($id, $orig_ref) = ($_, $_);
5197 next unless $id =~ s#^refs/heads/(.+)-HEAD$#$1#;
5198 next unless -f "$git_dir/$id/info/url";
5199 my $new_ref = "refs/remotes/$id";
5200 if (::verify_ref("$new_ref^0")) {
5201 print STDERR "W: $orig_ref is probably an old ",
5202 "branch used by an ancient version of ",
5203 "git-svn.\n",
5204 "However, $new_ref also exists.\n",
5205 "We will not be able ",
5206 "to use this branch until this ",
5207 "ambiguity is resolved.\n";
5208 next;
5210 print STDERR "Migrating from v0 layout...\n" if !$migrated;
5211 print STDERR "Renaming ref: $orig_ref => $new_ref\n";
5212 command_noisy('update-ref', $new_ref, $orig_ref);
5213 command_noisy('update-ref', '-d', $orig_ref, $orig_ref);
5214 $migrated++;
5216 command_close_pipe($fh, $ctx);
5217 print STDERR "Done migrating from v0 layout...\n" if $migrated;
5218 $migrated;
5221 sub migrate_from_v1 {
5222 my $git_dir = $ENV{GIT_DIR};
5223 my $migrated = 0;
5224 return $migrated unless -d $git_dir;
5225 my $svn_dir = "$git_dir/svn";
5227 # just in case somebody used 'svn' as their $id at some point...
5228 return $migrated if -d $svn_dir && ! -f "$svn_dir/info/url";
5230 print STDERR "Migrating from a git-svn v1 layout...\n";
5231 mkpath([$svn_dir]);
5232 print STDERR "Data from a previous version of git-svn exists, but\n\t",
5233 "$svn_dir\n\t(required for this version ",
5234 "($::VERSION) of git-svn) does not exist.\n";
5235 my ($fh, $ctx) = command_output_pipe(qw/rev-parse --symbolic --all/);
5236 while (<$fh>) {
5237 my $x = $_;
5238 next unless $x =~ s#^refs/remotes/##;
5239 chomp $x;
5240 next unless -f "$git_dir/$x/info/url";
5241 my $u = eval { ::file_to_s("$git_dir/$x/info/url") };
5242 next unless $u;
5243 my $dn = dirname("$git_dir/svn/$x");
5244 mkpath([$dn]) unless -d $dn;
5245 if ($x eq 'svn') { # they used 'svn' as GIT_SVN_ID:
5246 mkpath(["$git_dir/svn/svn"]);
5247 print STDERR " - $git_dir/$x/info => ",
5248 "$git_dir/svn/$x/info\n";
5249 rename "$git_dir/$x/info", "$git_dir/svn/$x/info" or
5250 croak "$!: $x";
5251 # don't worry too much about these, they probably
5252 # don't exist with repos this old (save for index,
5253 # and we can easily regenerate that)
5254 foreach my $f (qw/unhandled.log index .rev_db/) {
5255 rename "$git_dir/$x/$f", "$git_dir/svn/$x/$f";
5257 } else {
5258 print STDERR " - $git_dir/$x => $git_dir/svn/$x\n";
5259 rename "$git_dir/$x", "$git_dir/svn/$x" or
5260 croak "$!: $x";
5262 $migrated++;
5264 command_close_pipe($fh, $ctx);
5265 print STDERR "Done migrating from a git-svn v1 layout\n";
5266 $migrated;
5269 sub read_old_urls {
5270 my ($l_map, $pfx, $path) = @_;
5271 my @dir;
5272 foreach (<$path/*>) {
5273 if (-r "$_/info/url") {
5274 $pfx .= '/' if $pfx && $pfx !~ m!/$!;
5275 my $ref_id = $pfx . basename $_;
5276 my $url = ::file_to_s("$_/info/url");
5277 $l_map->{$ref_id} = $url;
5278 } elsif (-d $_) {
5279 push @dir, $_;
5282 foreach (@dir) {
5283 my $x = $_;
5284 $x =~ s!^\Q$ENV{GIT_DIR}\E/svn/!!o;
5285 read_old_urls($l_map, $x, $_);
5289 sub migrate_from_v2 {
5290 my @cfg = command(qw/config -l/);
5291 return if grep /^svn-remote\..+\.url=/, @cfg;
5292 my %l_map;
5293 read_old_urls(\%l_map, '', "$ENV{GIT_DIR}/svn");
5294 my $migrated = 0;
5296 foreach my $ref_id (sort keys %l_map) {
5297 eval { Git::SVN->init($l_map{$ref_id}, '', undef, $ref_id) };
5298 if ($@) {
5299 Git::SVN->init($l_map{$ref_id}, '', $ref_id, $ref_id);
5301 $migrated++;
5303 $migrated;
5306 sub minimize_connections {
5307 my $r = Git::SVN::read_all_remotes();
5308 my $new_urls = {};
5309 my $root_repos = {};
5310 foreach my $repo_id (keys %$r) {
5311 my $url = $r->{$repo_id}->{url} or next;
5312 my $fetch = $r->{$repo_id}->{fetch} or next;
5313 my $ra = Git::SVN::Ra->new($url);
5315 # skip existing cases where we already connect to the root
5316 if (($ra->{url} eq $ra->{repos_root}) ||
5317 ($ra->{repos_root} eq $repo_id)) {
5318 $root_repos->{$ra->{url}} = $repo_id;
5319 next;
5322 my $root_ra = Git::SVN::Ra->new($ra->{repos_root});
5323 my $root_path = $ra->{url};
5324 $root_path =~ s#^\Q$ra->{repos_root}\E(/|$)##;
5325 foreach my $path (keys %$fetch) {
5326 my $ref_id = $fetch->{$path};
5327 my $gs = Git::SVN->new($ref_id, $repo_id, $path);
5329 # make sure we can read when connecting to
5330 # a higher level of a repository
5331 my ($last_rev, undef) = $gs->last_rev_commit;
5332 if (!defined $last_rev) {
5333 $last_rev = eval {
5334 $root_ra->get_latest_revnum;
5336 next if $@;
5338 my $new = $root_path;
5339 $new .= length $path ? "/$path" : '';
5340 eval {
5341 $root_ra->get_log([$new], $last_rev, $last_rev,
5342 0, 0, 1, sub { });
5344 next if $@;
5345 $new_urls->{$ra->{repos_root}}->{$new} =
5346 { ref_id => $ref_id,
5347 old_repo_id => $repo_id,
5348 old_path => $path };
5352 my @emptied;
5353 foreach my $url (keys %$new_urls) {
5354 # see if we can re-use an existing [svn-remote "repo_id"]
5355 # instead of creating a(n ugly) new section:
5356 my $repo_id = $root_repos->{$url} || $url;
5358 my $fetch = $new_urls->{$url};
5359 foreach my $path (keys %$fetch) {
5360 my $x = $fetch->{$path};
5361 Git::SVN->init($url, $path, $repo_id, $x->{ref_id});
5362 my $pfx = "svn-remote.$x->{old_repo_id}";
5364 my $old_fetch = quotemeta("$x->{old_path}:".
5365 "refs/remotes/$x->{ref_id}");
5366 command_noisy(qw/config --unset/,
5367 "$pfx.fetch", '^'. $old_fetch . '$');
5368 delete $r->{$x->{old_repo_id}}->
5369 {fetch}->{$x->{old_path}};
5370 if (!keys %{$r->{$x->{old_repo_id}}->{fetch}}) {
5371 command_noisy(qw/config --unset/,
5372 "$pfx.url");
5373 push @emptied, $x->{old_repo_id}
5377 if (@emptied) {
5378 my $file = $ENV{GIT_CONFIG} || "$ENV{GIT_DIR}/config";
5379 print STDERR <<EOF;
5380 The following [svn-remote] sections in your config file ($file) are empty
5381 and can be safely removed:
5383 print STDERR "[svn-remote \"$_\"]\n" foreach @emptied;
5387 sub migration_check {
5388 migrate_from_v0();
5389 migrate_from_v1();
5390 migrate_from_v2();
5391 minimize_connections() if $_minimize;
5394 package Git::IndexInfo;
5395 use strict;
5396 use warnings;
5397 use Git qw/command_input_pipe command_close_pipe/;
5399 sub new {
5400 my ($class) = @_;
5401 my ($gui, $ctx) = command_input_pipe(qw/update-index -z --index-info/);
5402 bless { gui => $gui, ctx => $ctx, nr => 0}, $class;
5405 sub remove {
5406 my ($self, $path) = @_;
5407 if (print { $self->{gui} } '0 ', 0 x 40, "\t", $path, "\0") {
5408 return ++$self->{nr};
5410 undef;
5413 sub update {
5414 my ($self, $mode, $hash, $path) = @_;
5415 if (print { $self->{gui} } $mode, ' ', $hash, "\t", $path, "\0") {
5416 return ++$self->{nr};
5418 undef;
5421 sub DESTROY {
5422 my ($self) = @_;
5423 command_close_pipe($self->{gui}, $self->{ctx});
5426 package Git::SVN::GlobSpec;
5427 use strict;
5428 use warnings;
5430 sub new {
5431 my ($class, $glob) = @_;
5432 my $re = $glob;
5433 $re =~ s!/+$!!g; # no need for trailing slashes
5434 $re =~ m!^([^*]*)(\*(?:/\*)*)([^*]*)$!;
5435 my $temp = $re;
5436 my ($left, $right) = ($1, $3);
5437 $re = $2;
5438 my $depth = $re =~ tr/*/*/;
5439 if ($depth != $temp =~ tr/*/*/) {
5440 die "Only one set of wildcard directories " .
5441 "(e.g. '*' or '*/*/*') is supported: '$glob'\n";
5443 if ($depth == 0) {
5444 die "One '*' is needed for glob: '$glob'\n";
5446 $re =~ s!\*!\[^/\]*!g;
5447 $re = quotemeta($left) . "($re)" . quotemeta($right);
5448 if (length $left && !($left =~ s!/+$!!g)) {
5449 die "Missing trailing '/' on left side of: '$glob' ($left)\n";
5451 if (length $right && !($right =~ s!^/+!!g)) {
5452 die "Missing leading '/' on right side of: '$glob' ($right)\n";
5454 my $left_re = qr/^\/\Q$left\E(\/|$)/;
5455 bless { left => $left, right => $right, left_regex => $left_re,
5456 regex => qr/$re/, glob => $glob, depth => $depth }, $class;
5459 sub full_path {
5460 my ($self, $path) = @_;
5461 return (length $self->{left} ? "$self->{left}/" : '') .
5462 $path . (length $self->{right} ? "/$self->{right}" : '');
5465 __END__
5467 Data structures:
5470 $remotes = { # returned by read_all_remotes()
5471 'svn' => {
5472 # svn-remote.svn.url=https://svn.musicpd.org
5473 url => 'https://svn.musicpd.org',
5474 # svn-remote.svn.fetch=mpd/trunk:trunk
5475 fetch => {
5476 'mpd/trunk' => 'trunk',
5478 # svn-remote.svn.tags=mpd/tags/*:tags/*
5479 tags => {
5480 path => {
5481 left => 'mpd/tags',
5482 right => '',
5483 regex => qr!mpd/tags/([^/]+)$!,
5484 glob => 'tags/*',
5486 ref => {
5487 left => 'tags',
5488 right => '',
5489 regex => qr!tags/([^/]+)$!,
5490 glob => 'tags/*',
5496 $log_entry hashref as returned by libsvn_log_entry()
5498 log => 'whitespace-formatted log entry
5499 ', # trailing newline is preserved
5500 revision => '8', # integer
5501 date => '2004-02-24T17:01:44.108345Z', # commit date
5502 author => 'committer name'
5506 # this is generated by generate_diff();
5507 @mods = array of diff-index line hashes, each element represents one line
5508 of diff-index output
5510 diff-index line ($m hash)
5512 mode_a => first column of diff-index output, no leading ':',
5513 mode_b => second column of diff-index output,
5514 sha1_b => sha1sum of the final blob,
5515 chg => change type [MCRADT],
5516 file_a => original file name of a file (iff chg is 'C' or 'R')
5517 file_b => new/current file name of a file (any chg)
5521 # retval of read_url_paths{,_all}();
5522 $l_map = {
5523 # repository root url
5524 'https://svn.musicpd.org' => {
5525 # repository path # GIT_SVN_ID
5526 'mpd/trunk' => 'trunk',
5527 'mpd/tags/0.11.5' => 'tags/0.11.5',
5531 Notes:
5532 I don't trust the each() function on unless I created %hash myself
5533 because the internal iterator may not have started at base.